blob: d64af69dbfb2393bc0eae7b8c9ad32619f1218db [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)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001447 self.assertEqual(cm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001448 cm.x = 42
1449 self.assertEqual(cm.x, 42)
1450 self.assertEqual(cm.__dict__, {"x" : 42})
1451 del cm.x
1452 self.assertFalse(hasattr(cm, "x"))
1453
Benjamin Petersone549ead2009-03-28 21:42:05 +00001454 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001455 def test_classmethods_in_c(self):
1456 # Testing C-based class methods...
1457 import xxsubtype as spam
1458 a = (1, 2, 3)
1459 d = {'abc': 123}
1460 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1461 self.assertEqual(x, spam.spamlist)
1462 self.assertEqual(a, a1)
1463 self.assertEqual(d, d1)
1464 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1465 self.assertEqual(x, spam.spamlist)
1466 self.assertEqual(a, a1)
1467 self.assertEqual(d, d1)
1468
1469 def test_staticmethods(self):
1470 # Testing static methods...
1471 class C(object):
1472 def foo(*a): return a
1473 goo = staticmethod(foo)
1474 c = C()
1475 self.assertEqual(C.goo(1), (1,))
1476 self.assertEqual(c.goo(1), (1,))
1477 self.assertEqual(c.foo(1), (c, 1,))
1478 class D(C):
1479 pass
1480 d = D()
1481 self.assertEqual(D.goo(1), (1,))
1482 self.assertEqual(d.goo(1), (1,))
1483 self.assertEqual(d.foo(1), (d, 1))
1484 self.assertEqual(D.foo(d, 1), (d, 1))
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001485 sm = staticmethod(None)
Benjamin Petersonb900d6a2012-02-19 10:17:30 -05001486 self.assertEqual(sm.__dict__, {})
Benjamin Peterson01d7eba2012-02-19 01:10:25 -05001487 sm.x = 42
1488 self.assertEqual(sm.x, 42)
1489 self.assertEqual(sm.__dict__, {"x" : 42})
1490 del sm.x
1491 self.assertFalse(hasattr(sm, "x"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001492
Benjamin Petersone549ead2009-03-28 21:42:05 +00001493 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001494 def test_staticmethods_in_c(self):
1495 # Testing C-based static methods...
1496 import xxsubtype as spam
1497 a = (1, 2, 3)
1498 d = {"abc": 123}
1499 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1500 self.assertEqual(x, None)
1501 self.assertEqual(a, a1)
1502 self.assertEqual(d, d1)
1503 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1504 self.assertEqual(x, None)
1505 self.assertEqual(a, a1)
1506 self.assertEqual(d, d1)
1507
1508 def test_classic(self):
1509 # Testing classic classes...
1510 class C:
1511 def foo(*a): return a
1512 goo = classmethod(foo)
1513 c = C()
1514 self.assertEqual(C.goo(1), (C, 1))
1515 self.assertEqual(c.goo(1), (C, 1))
1516 self.assertEqual(c.foo(1), (c, 1))
1517 class D(C):
1518 pass
1519 d = D()
1520 self.assertEqual(D.goo(1), (D, 1))
1521 self.assertEqual(d.goo(1), (D, 1))
1522 self.assertEqual(d.foo(1), (d, 1))
1523 self.assertEqual(D.foo(d, 1), (d, 1))
1524 class E: # *not* subclassing from C
1525 foo = C.foo
1526 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001527 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001528
1529 def test_compattr(self):
1530 # Testing computed attributes...
1531 class C(object):
1532 class computed_attribute(object):
1533 def __init__(self, get, set=None, delete=None):
1534 self.__get = get
1535 self.__set = set
1536 self.__delete = delete
1537 def __get__(self, obj, type=None):
1538 return self.__get(obj)
1539 def __set__(self, obj, value):
1540 return self.__set(obj, value)
1541 def __delete__(self, obj):
1542 return self.__delete(obj)
1543 def __init__(self):
1544 self.__x = 0
1545 def __get_x(self):
1546 x = self.__x
1547 self.__x = x+1
1548 return x
1549 def __set_x(self, x):
1550 self.__x = x
1551 def __delete_x(self):
1552 del self.__x
1553 x = computed_attribute(__get_x, __set_x, __delete_x)
1554 a = C()
1555 self.assertEqual(a.x, 0)
1556 self.assertEqual(a.x, 1)
1557 a.x = 10
1558 self.assertEqual(a.x, 10)
1559 self.assertEqual(a.x, 11)
1560 del a.x
1561 self.assertEqual(hasattr(a, 'x'), 0)
1562
1563 def test_newslots(self):
1564 # Testing __new__ slot override...
1565 class C(list):
1566 def __new__(cls):
1567 self = list.__new__(cls)
1568 self.foo = 1
1569 return self
1570 def __init__(self):
1571 self.foo = self.foo + 2
1572 a = C()
1573 self.assertEqual(a.foo, 3)
1574 self.assertEqual(a.__class__, C)
1575 class D(C):
1576 pass
1577 b = D()
1578 self.assertEqual(b.foo, 3)
1579 self.assertEqual(b.__class__, D)
1580
1581 def test_altmro(self):
1582 # Testing mro() and overriding it...
1583 class A(object):
1584 def f(self): return "A"
1585 class B(A):
1586 pass
1587 class C(A):
1588 def f(self): return "C"
1589 class D(B, C):
1590 pass
1591 self.assertEqual(D.mro(), [D, B, C, A, object])
1592 self.assertEqual(D.__mro__, (D, B, C, A, object))
1593 self.assertEqual(D().f(), "C")
1594
1595 class PerverseMetaType(type):
1596 def mro(cls):
1597 L = type.mro(cls)
1598 L.reverse()
1599 return L
1600 class X(D,B,C,A, metaclass=PerverseMetaType):
1601 pass
1602 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1603 self.assertEqual(X().f(), "A")
1604
1605 try:
1606 class _metaclass(type):
1607 def mro(self):
1608 return [self, dict, object]
1609 class X(object, metaclass=_metaclass):
1610 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001611 # In CPython, the class creation above already raises
1612 # TypeError, as a protection against the fact that
1613 # instances of X would segfault it. In other Python
1614 # implementations it would be ok to let the class X
1615 # be created, but instead get a clean TypeError on the
1616 # __setitem__ below.
1617 x = object.__new__(X)
1618 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001619 except TypeError:
1620 pass
1621 else:
1622 self.fail("devious mro() return not caught")
1623
1624 try:
1625 class _metaclass(type):
1626 def mro(self):
1627 return [1]
1628 class X(object, metaclass=_metaclass):
1629 pass
1630 except TypeError:
1631 pass
1632 else:
1633 self.fail("non-class mro() return not caught")
1634
1635 try:
1636 class _metaclass(type):
1637 def mro(self):
1638 return 1
1639 class X(object, metaclass=_metaclass):
1640 pass
1641 except TypeError:
1642 pass
1643 else:
1644 self.fail("non-sequence mro() return not caught")
1645
1646 def test_overloading(self):
1647 # Testing operator overloading...
1648
1649 class B(object):
1650 "Intermediate class because object doesn't have a __setattr__"
1651
1652 class C(B):
1653 def __getattr__(self, name):
1654 if name == "foo":
1655 return ("getattr", name)
1656 else:
1657 raise AttributeError
1658 def __setattr__(self, name, value):
1659 if name == "foo":
1660 self.setattr = (name, value)
1661 else:
1662 return B.__setattr__(self, name, value)
1663 def __delattr__(self, name):
1664 if name == "foo":
1665 self.delattr = name
1666 else:
1667 return B.__delattr__(self, name)
1668
1669 def __getitem__(self, key):
1670 return ("getitem", key)
1671 def __setitem__(self, key, value):
1672 self.setitem = (key, value)
1673 def __delitem__(self, key):
1674 self.delitem = key
1675
1676 a = C()
1677 self.assertEqual(a.foo, ("getattr", "foo"))
1678 a.foo = 12
1679 self.assertEqual(a.setattr, ("foo", 12))
1680 del a.foo
1681 self.assertEqual(a.delattr, "foo")
1682
1683 self.assertEqual(a[12], ("getitem", 12))
1684 a[12] = 21
1685 self.assertEqual(a.setitem, (12, 21))
1686 del a[12]
1687 self.assertEqual(a.delitem, 12)
1688
1689 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1690 a[0:10] = "foo"
1691 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1692 del a[0:10]
1693 self.assertEqual(a.delitem, (slice(0, 10)))
1694
1695 def test_methods(self):
1696 # Testing methods...
1697 class C(object):
1698 def __init__(self, x):
1699 self.x = x
1700 def foo(self):
1701 return self.x
1702 c1 = C(1)
1703 self.assertEqual(c1.foo(), 1)
1704 class D(C):
1705 boo = C.foo
1706 goo = c1.foo
1707 d2 = D(2)
1708 self.assertEqual(d2.foo(), 2)
1709 self.assertEqual(d2.boo(), 2)
1710 self.assertEqual(d2.goo(), 1)
1711 class E(object):
1712 foo = C.foo
1713 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001714 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001715
Benjamin Peterson224205f2009-05-08 03:25:19 +00001716 def test_special_method_lookup(self):
1717 # The lookup of special methods bypasses __getattr__ and
1718 # __getattribute__, but they still can be descriptors.
1719
1720 def run_context(manager):
1721 with manager:
1722 pass
1723 def iden(self):
1724 return self
1725 def hello(self):
1726 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001727 def empty_seq(self):
1728 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001729 def zero(self):
1730 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001731 def complex_num(self):
1732 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001733 def stop(self):
1734 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001735 def return_true(self, thing=None):
1736 return True
1737 def do_isinstance(obj):
1738 return isinstance(int, obj)
1739 def do_issubclass(obj):
1740 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001741 def do_dict_missing(checker):
1742 class DictSub(checker.__class__, dict):
1743 pass
1744 self.assertEqual(DictSub()["hi"], 4)
1745 def some_number(self_, key):
1746 self.assertEqual(key, "hi")
1747 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001748 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001749 def format_impl(self, spec):
1750 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001751
1752 # It would be nice to have every special method tested here, but I'm
1753 # only listing the ones I can remember outside of typeobject.c, since it
1754 # does it right.
1755 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001756 ("__bytes__", bytes, hello, set(), {}),
1757 ("__reversed__", reversed, empty_seq, set(), {}),
1758 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001759 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001760 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1761 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001762 ("__missing__", do_dict_missing, some_number,
1763 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001764 ("__subclasscheck__", do_issubclass, return_true,
1765 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001766 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1767 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001768 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001769 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001770 ("__floor__", math.floor, zero, set(), {}),
1771 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001772 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001773 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001774 ]
1775
1776 class Checker(object):
1777 def __getattr__(self, attr, test=self):
1778 test.fail("__getattr__ called with {0}".format(attr))
1779 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001780 if attr not in ok:
1781 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001782 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001783 class SpecialDescr(object):
1784 def __init__(self, impl):
1785 self.impl = impl
1786 def __get__(self, obj, owner):
1787 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001788 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001789 class MyException(Exception):
1790 pass
1791 class ErrDescr(object):
1792 def __get__(self, obj, owner):
1793 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001794
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001795 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001796 class X(Checker):
1797 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001798 for attr, obj in env.items():
1799 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001800 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001801 runner(X())
1802
1803 record = []
1804 class X(Checker):
1805 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001806 for attr, obj in env.items():
1807 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001808 setattr(X, name, SpecialDescr(meth_impl))
1809 runner(X())
1810 self.assertEqual(record, [1], name)
1811
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001812 class X(Checker):
1813 pass
1814 for attr, obj in env.items():
1815 setattr(X, attr, obj)
1816 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001817 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001818
Georg Brandl479a7e72008-02-05 18:13:15 +00001819 def test_specials(self):
1820 # Testing special operators...
1821 # Test operators like __hash__ for which a built-in default exists
1822
1823 # Test the default behavior for static classes
1824 class C(object):
1825 def __getitem__(self, i):
1826 if 0 <= i < 10: return i
1827 raise IndexError
1828 c1 = C()
1829 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001830 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001831 self.assertNotEqual(id(c1), id(c2))
1832 hash(c1)
1833 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001834 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001835 self.assertTrue(c1 != c2)
1836 self.assertTrue(not c1 != c1)
1837 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001838 # Note that the module name appears in str/repr, and that varies
1839 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001840 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001841 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001842 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001843 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001844 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001845 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001846 # Test the default behavior for dynamic classes
1847 class D(object):
1848 def __getitem__(self, i):
1849 if 0 <= i < 10: return i
1850 raise IndexError
1851 d1 = D()
1852 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001853 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001854 self.assertNotEqual(id(d1), id(d2))
1855 hash(d1)
1856 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001857 self.assertEqual(d1, d1)
1858 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001859 self.assertTrue(not d1 != d1)
1860 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001861 # Note that the module name appears in str/repr, and that varies
1862 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001863 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001864 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001865 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001866 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001867 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001868 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001869 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001870 class Proxy(object):
1871 def __init__(self, x):
1872 self.x = x
1873 def __bool__(self):
1874 return not not self.x
1875 def __hash__(self):
1876 return hash(self.x)
1877 def __eq__(self, other):
1878 return self.x == other
1879 def __ne__(self, other):
1880 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001881 def __ge__(self, other):
1882 return self.x >= other
1883 def __gt__(self, other):
1884 return self.x > other
1885 def __le__(self, other):
1886 return self.x <= other
1887 def __lt__(self, other):
1888 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001889 def __str__(self):
1890 return "Proxy:%s" % self.x
1891 def __repr__(self):
1892 return "Proxy(%r)" % self.x
1893 def __contains__(self, value):
1894 return value in self.x
1895 p0 = Proxy(0)
1896 p1 = Proxy(1)
1897 p_1 = Proxy(-1)
1898 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001899 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001900 self.assertEqual(hash(p0), hash(0))
1901 self.assertEqual(p0, p0)
1902 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001903 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001904 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001905 self.assertTrue(p0 < p1)
1906 self.assertTrue(p0 <= p1)
1907 self.assertTrue(p1 > p0)
1908 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001909 self.assertEqual(str(p0), "Proxy:0")
1910 self.assertEqual(repr(p0), "Proxy(0)")
1911 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001912 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001913 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001914 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001915 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001916
Georg Brandl479a7e72008-02-05 18:13:15 +00001917 def test_weakrefs(self):
1918 # Testing weak references...
1919 import weakref
1920 class C(object):
1921 pass
1922 c = C()
1923 r = weakref.ref(c)
1924 self.assertEqual(r(), c)
1925 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001926 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001927 self.assertEqual(r(), None)
1928 del r
1929 class NoWeak(object):
1930 __slots__ = ['foo']
1931 no = NoWeak()
1932 try:
1933 weakref.ref(no)
1934 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001935 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001936 else:
1937 self.fail("weakref.ref(no) should be illegal")
1938 class Weak(object):
1939 __slots__ = ['foo', '__weakref__']
1940 yes = Weak()
1941 r = weakref.ref(yes)
1942 self.assertEqual(r(), yes)
1943 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001944 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001945 self.assertEqual(r(), None)
1946 del r
1947
1948 def test_properties(self):
1949 # Testing property...
1950 class C(object):
1951 def getx(self):
1952 return self.__x
1953 def setx(self, value):
1954 self.__x = value
1955 def delx(self):
1956 del self.__x
1957 x = property(getx, setx, delx, doc="I'm the x property.")
1958 a = C()
1959 self.assertFalse(hasattr(a, "x"))
1960 a.x = 42
1961 self.assertEqual(a._C__x, 42)
1962 self.assertEqual(a.x, 42)
1963 del a.x
1964 self.assertFalse(hasattr(a, "x"))
1965 self.assertFalse(hasattr(a, "_C__x"))
1966 C.x.__set__(a, 100)
1967 self.assertEqual(C.x.__get__(a), 100)
1968 C.x.__delete__(a)
1969 self.assertFalse(hasattr(a, "x"))
1970
1971 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001972 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001973
1974 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001975 self.assertIn("__doc__", attrs)
1976 self.assertIn("fget", attrs)
1977 self.assertIn("fset", attrs)
1978 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001979
1980 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001981 self.assertTrue(raw.fget is C.__dict__['getx'])
1982 self.assertTrue(raw.fset is C.__dict__['setx'])
1983 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001984
1985 for attr in "__doc__", "fget", "fset", "fdel":
1986 try:
1987 setattr(raw, attr, 42)
1988 except AttributeError as msg:
1989 if str(msg).find('readonly') < 0:
1990 self.fail("when setting readonly attr %r on a property, "
1991 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1992 else:
1993 self.fail("expected AttributeError from trying to set readonly %r "
1994 "attr on a property" % attr)
1995
1996 class D(object):
1997 __getitem__ = property(lambda s: 1/0)
1998
1999 d = D()
2000 try:
2001 for i in d:
2002 str(i)
2003 except ZeroDivisionError:
2004 pass
2005 else:
2006 self.fail("expected ZeroDivisionError from bad property")
2007
R. David Murray378c0cf2010-02-24 01:46:21 +00002008 @unittest.skipIf(sys.flags.optimize >= 2,
2009 "Docstrings are omitted with -O2 and above")
2010 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002011 class E(object):
2012 def getter(self):
2013 "getter method"
2014 return 0
2015 def setter(self_, value):
2016 "setter method"
2017 pass
2018 prop = property(getter)
2019 self.assertEqual(prop.__doc__, "getter method")
2020 prop2 = property(fset=setter)
2021 self.assertEqual(prop2.__doc__, None)
2022
R. David Murray378c0cf2010-02-24 01:46:21 +00002023 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002024 # this segfaulted in 2.5b2
2025 try:
2026 import _testcapi
2027 except ImportError:
2028 pass
2029 else:
2030 class X(object):
2031 p = property(_testcapi.test_with_docstring)
2032
2033 def test_properties_plus(self):
2034 class C(object):
2035 foo = property(doc="hello")
2036 @foo.getter
2037 def foo(self):
2038 return self._foo
2039 @foo.setter
2040 def foo(self, value):
2041 self._foo = abs(value)
2042 @foo.deleter
2043 def foo(self):
2044 del self._foo
2045 c = C()
2046 self.assertEqual(C.foo.__doc__, "hello")
2047 self.assertFalse(hasattr(c, "foo"))
2048 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002049 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00002050 self.assertEqual(c._foo, 42)
2051 self.assertEqual(c.foo, 42)
2052 del c.foo
2053 self.assertFalse(hasattr(c, '_foo'))
2054 self.assertFalse(hasattr(c, "foo"))
2055
2056 class D(C):
2057 @C.foo.deleter
2058 def foo(self):
2059 try:
2060 del self._foo
2061 except AttributeError:
2062 pass
2063 d = D()
2064 d.foo = 24
2065 self.assertEqual(d.foo, 24)
2066 del d.foo
2067 del d.foo
2068
2069 class E(object):
2070 @property
2071 def foo(self):
2072 return self._foo
2073 @foo.setter
2074 def foo(self, value):
2075 raise RuntimeError
2076 @foo.setter
2077 def foo(self, value):
2078 self._foo = abs(value)
2079 @foo.deleter
2080 def foo(self, value=None):
2081 del self._foo
2082
2083 e = E()
2084 e.foo = -42
2085 self.assertEqual(e.foo, 42)
2086 del e.foo
2087
2088 class F(E):
2089 @E.foo.deleter
2090 def foo(self):
2091 del self._foo
2092 @foo.setter
2093 def foo(self, value):
2094 self._foo = max(0, value)
2095 f = F()
2096 f.foo = -10
2097 self.assertEqual(f.foo, 0)
2098 del f.foo
2099
2100 def test_dict_constructors(self):
2101 # Testing dict constructor ...
2102 d = dict()
2103 self.assertEqual(d, {})
2104 d = dict({})
2105 self.assertEqual(d, {})
2106 d = dict({1: 2, 'a': 'b'})
2107 self.assertEqual(d, {1: 2, 'a': 'b'})
2108 self.assertEqual(d, dict(list(d.items())))
2109 self.assertEqual(d, dict(iter(d.items())))
2110 d = dict({'one':1, 'two':2})
2111 self.assertEqual(d, dict(one=1, two=2))
2112 self.assertEqual(d, dict(**d))
2113 self.assertEqual(d, dict({"one": 1}, two=2))
2114 self.assertEqual(d, dict([("two", 2)], one=1))
2115 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2116 self.assertEqual(d, dict(**d))
2117
2118 for badarg in 0, 0, 0j, "0", [0], (0,):
2119 try:
2120 dict(badarg)
2121 except TypeError:
2122 pass
2123 except ValueError:
2124 if badarg == "0":
2125 # It's a sequence, and its elements are also sequences (gotta
2126 # love strings <wink>), but they aren't of length 2, so this
2127 # one seemed better as a ValueError than a TypeError.
2128 pass
2129 else:
2130 self.fail("no TypeError from dict(%r)" % badarg)
2131 else:
2132 self.fail("no TypeError from dict(%r)" % badarg)
2133
2134 try:
2135 dict({}, {})
2136 except TypeError:
2137 pass
2138 else:
2139 self.fail("no TypeError from dict({}, {})")
2140
2141 class Mapping:
2142 # Lacks a .keys() method; will be added later.
2143 dict = {1:2, 3:4, 'a':1j}
2144
2145 try:
2146 dict(Mapping())
2147 except TypeError:
2148 pass
2149 else:
2150 self.fail("no TypeError from dict(incomplete mapping)")
2151
2152 Mapping.keys = lambda self: list(self.dict.keys())
2153 Mapping.__getitem__ = lambda self, i: self.dict[i]
2154 d = dict(Mapping())
2155 self.assertEqual(d, Mapping.dict)
2156
2157 # Init from sequence of iterable objects, each producing a 2-sequence.
2158 class AddressBookEntry:
2159 def __init__(self, first, last):
2160 self.first = first
2161 self.last = last
2162 def __iter__(self):
2163 return iter([self.first, self.last])
2164
2165 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2166 AddressBookEntry('Barry', 'Peters'),
2167 AddressBookEntry('Tim', 'Peters'),
2168 AddressBookEntry('Barry', 'Warsaw')])
2169 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2170
2171 d = dict(zip(range(4), range(1, 5)))
2172 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2173
2174 # Bad sequence lengths.
2175 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2176 try:
2177 dict(bad)
2178 except ValueError:
2179 pass
2180 else:
2181 self.fail("no ValueError from dict(%r)" % bad)
2182
2183 def test_dir(self):
2184 # Testing dir() ...
2185 junk = 12
2186 self.assertEqual(dir(), ['junk', 'self'])
2187 del junk
2188
2189 # Just make sure these don't blow up!
2190 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2191 dir(arg)
2192
2193 # Test dir on new-style classes. Since these have object as a
2194 # base class, a lot more gets sucked in.
2195 def interesting(strings):
2196 return [s for s in strings if not s.startswith('_')]
2197
2198 class C(object):
2199 Cdata = 1
2200 def Cmethod(self): pass
2201
2202 cstuff = ['Cdata', 'Cmethod']
2203 self.assertEqual(interesting(dir(C)), cstuff)
2204
2205 c = C()
2206 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002207 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002208
2209 c.cdata = 2
2210 c.cmethod = lambda self: 0
2211 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002212 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002213
2214 class A(C):
2215 Adata = 1
2216 def Amethod(self): pass
2217
2218 astuff = ['Adata', 'Amethod'] + cstuff
2219 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002220 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002221 a = A()
2222 self.assertEqual(interesting(dir(a)), astuff)
2223 a.adata = 42
2224 a.amethod = lambda self: 3
2225 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002226 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002227
2228 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002229 class M(type(sys)):
2230 pass
2231 minstance = M("m")
2232 minstance.b = 2
2233 minstance.a = 1
2234 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2235 self.assertEqual(names, ['a', 'b'])
2236
2237 class M2(M):
2238 def getdict(self):
2239 return "Not a dict!"
2240 __dict__ = property(getdict)
2241
2242 m2instance = M2("m2")
2243 m2instance.b = 2
2244 m2instance.a = 1
2245 self.assertEqual(m2instance.__dict__, "Not a dict!")
2246 try:
2247 dir(m2instance)
2248 except TypeError:
2249 pass
2250
2251 # Two essentially featureless objects, just inheriting stuff from
2252 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002253 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002254
2255 # Nasty test case for proxied objects
2256 class Wrapper(object):
2257 def __init__(self, obj):
2258 self.__obj = obj
2259 def __repr__(self):
2260 return "Wrapper(%s)" % repr(self.__obj)
2261 def __getitem__(self, key):
2262 return Wrapper(self.__obj[key])
2263 def __len__(self):
2264 return len(self.__obj)
2265 def __getattr__(self, name):
2266 return Wrapper(getattr(self.__obj, name))
2267
2268 class C(object):
2269 def __getclass(self):
2270 return Wrapper(type(self))
2271 __class__ = property(__getclass)
2272
2273 dir(C()) # This used to segfault
2274
2275 def test_supers(self):
2276 # Testing super...
2277
2278 class A(object):
2279 def meth(self, a):
2280 return "A(%r)" % a
2281
2282 self.assertEqual(A().meth(1), "A(1)")
2283
2284 class B(A):
2285 def __init__(self):
2286 self.__super = super(B, self)
2287 def meth(self, a):
2288 return "B(%r)" % a + self.__super.meth(a)
2289
2290 self.assertEqual(B().meth(2), "B(2)A(2)")
2291
2292 class C(A):
2293 def meth(self, a):
2294 return "C(%r)" % a + self.__super.meth(a)
2295 C._C__super = super(C)
2296
2297 self.assertEqual(C().meth(3), "C(3)A(3)")
2298
2299 class D(C, B):
2300 def meth(self, a):
2301 return "D(%r)" % a + super(D, self).meth(a)
2302
2303 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2304
2305 # Test for subclassing super
2306
2307 class mysuper(super):
2308 def __init__(self, *args):
2309 return super(mysuper, self).__init__(*args)
2310
2311 class E(D):
2312 def meth(self, a):
2313 return "E(%r)" % a + mysuper(E, self).meth(a)
2314
2315 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2316
2317 class F(E):
2318 def meth(self, a):
2319 s = self.__super # == mysuper(F, self)
2320 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2321 F._F__super = mysuper(F)
2322
2323 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2324
2325 # Make sure certain errors are raised
2326
2327 try:
2328 super(D, 42)
2329 except TypeError:
2330 pass
2331 else:
2332 self.fail("shouldn't allow super(D, 42)")
2333
2334 try:
2335 super(D, C())
2336 except TypeError:
2337 pass
2338 else:
2339 self.fail("shouldn't allow super(D, C())")
2340
2341 try:
2342 super(D).__get__(12)
2343 except TypeError:
2344 pass
2345 else:
2346 self.fail("shouldn't allow super(D).__get__(12)")
2347
2348 try:
2349 super(D).__get__(C())
2350 except TypeError:
2351 pass
2352 else:
2353 self.fail("shouldn't allow super(D).__get__(C())")
2354
2355 # Make sure data descriptors can be overridden and accessed via super
2356 # (new feature in Python 2.3)
2357
2358 class DDbase(object):
2359 def getx(self): return 42
2360 x = property(getx)
2361
2362 class DDsub(DDbase):
2363 def getx(self): return "hello"
2364 x = property(getx)
2365
2366 dd = DDsub()
2367 self.assertEqual(dd.x, "hello")
2368 self.assertEqual(super(DDsub, dd).x, 42)
2369
2370 # Ensure that super() lookup of descriptor from classmethod
2371 # works (SF ID# 743627)
2372
2373 class Base(object):
2374 aProp = property(lambda self: "foo")
2375
2376 class Sub(Base):
2377 @classmethod
2378 def test(klass):
2379 return super(Sub,klass).aProp
2380
2381 self.assertEqual(Sub.test(), Base.aProp)
2382
2383 # Verify that super() doesn't allow keyword args
2384 try:
2385 super(Base, kw=1)
2386 except TypeError:
2387 pass
2388 else:
2389 self.assertEqual("super shouldn't accept keyword args")
2390
2391 def test_basic_inheritance(self):
2392 # Testing inheritance from basic types...
2393
2394 class hexint(int):
2395 def __repr__(self):
2396 return hex(self)
2397 def __add__(self, other):
2398 return hexint(int.__add__(self, other))
2399 # (Note that overriding __radd__ doesn't work,
2400 # because the int type gets first dibs.)
2401 self.assertEqual(repr(hexint(7) + 9), "0x10")
2402 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2403 a = hexint(12345)
2404 self.assertEqual(a, 12345)
2405 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002406 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002407 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002408 self.assertTrue((+a).__class__ is int)
2409 self.assertTrue((a >> 0).__class__ is int)
2410 self.assertTrue((a << 0).__class__ is int)
2411 self.assertTrue((hexint(0) << 12).__class__ is int)
2412 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002413
2414 class octlong(int):
2415 __slots__ = []
2416 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002417 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002418 def __add__(self, other):
2419 return self.__class__(super(octlong, self).__add__(other))
2420 __radd__ = __add__
2421 self.assertEqual(str(octlong(3) + 5), "0o10")
2422 # (Note that overriding __radd__ here only seems to work
2423 # because the example uses a short int left argument.)
2424 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2425 a = octlong(12345)
2426 self.assertEqual(a, 12345)
2427 self.assertEqual(int(a), 12345)
2428 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002429 self.assertTrue(int(a).__class__ is int)
2430 self.assertTrue((+a).__class__ is int)
2431 self.assertTrue((-a).__class__ is int)
2432 self.assertTrue((-octlong(0)).__class__ is int)
2433 self.assertTrue((a >> 0).__class__ is int)
2434 self.assertTrue((a << 0).__class__ is int)
2435 self.assertTrue((a - 0).__class__ is int)
2436 self.assertTrue((a * 1).__class__ is int)
2437 self.assertTrue((a ** 1).__class__ is int)
2438 self.assertTrue((a // 1).__class__ is int)
2439 self.assertTrue((1 * a).__class__ is int)
2440 self.assertTrue((a | 0).__class__ is int)
2441 self.assertTrue((a ^ 0).__class__ is int)
2442 self.assertTrue((a & -1).__class__ is int)
2443 self.assertTrue((octlong(0) << 12).__class__ is int)
2444 self.assertTrue((octlong(0) >> 12).__class__ is int)
2445 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002446
2447 # Because octlong overrides __add__, we can't check the absence of +0
2448 # optimizations using octlong.
2449 class longclone(int):
2450 pass
2451 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002452 self.assertTrue((a + 0).__class__ is int)
2453 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002454
2455 # Check that negative clones don't segfault
2456 a = longclone(-1)
2457 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002458 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002459
2460 class precfloat(float):
2461 __slots__ = ['prec']
2462 def __init__(self, value=0.0, prec=12):
2463 self.prec = int(prec)
2464 def __repr__(self):
2465 return "%.*g" % (self.prec, self)
2466 self.assertEqual(repr(precfloat(1.1)), "1.1")
2467 a = precfloat(12345)
2468 self.assertEqual(a, 12345.0)
2469 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002470 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002471 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002472 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002473
2474 class madcomplex(complex):
2475 def __repr__(self):
2476 return "%.17gj%+.17g" % (self.imag, self.real)
2477 a = madcomplex(-3, 4)
2478 self.assertEqual(repr(a), "4j-3")
2479 base = complex(-3, 4)
2480 self.assertEqual(base.__class__, complex)
2481 self.assertEqual(a, base)
2482 self.assertEqual(complex(a), base)
2483 self.assertEqual(complex(a).__class__, complex)
2484 a = madcomplex(a) # just trying another form of the constructor
2485 self.assertEqual(repr(a), "4j-3")
2486 self.assertEqual(a, base)
2487 self.assertEqual(complex(a), base)
2488 self.assertEqual(complex(a).__class__, complex)
2489 self.assertEqual(hash(a), hash(base))
2490 self.assertEqual((+a).__class__, complex)
2491 self.assertEqual((a + 0).__class__, complex)
2492 self.assertEqual(a + 0, base)
2493 self.assertEqual((a - 0).__class__, complex)
2494 self.assertEqual(a - 0, base)
2495 self.assertEqual((a * 1).__class__, complex)
2496 self.assertEqual(a * 1, base)
2497 self.assertEqual((a / 1).__class__, complex)
2498 self.assertEqual(a / 1, base)
2499
2500 class madtuple(tuple):
2501 _rev = None
2502 def rev(self):
2503 if self._rev is not None:
2504 return self._rev
2505 L = list(self)
2506 L.reverse()
2507 self._rev = self.__class__(L)
2508 return self._rev
2509 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2510 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2511 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2512 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2513 for i in range(512):
2514 t = madtuple(range(i))
2515 u = t.rev()
2516 v = u.rev()
2517 self.assertEqual(v, t)
2518 a = madtuple((1,2,3,4,5))
2519 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002520 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002521 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002522 self.assertTrue(a[:].__class__ is tuple)
2523 self.assertTrue((a * 1).__class__ is tuple)
2524 self.assertTrue((a * 0).__class__ is tuple)
2525 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002526 a = madtuple(())
2527 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002528 self.assertTrue(tuple(a).__class__ is tuple)
2529 self.assertTrue((a + a).__class__ is tuple)
2530 self.assertTrue((a * 0).__class__ is tuple)
2531 self.assertTrue((a * 1).__class__ is tuple)
2532 self.assertTrue((a * 2).__class__ is tuple)
2533 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002534
2535 class madstring(str):
2536 _rev = None
2537 def rev(self):
2538 if self._rev is not None:
2539 return self._rev
2540 L = list(self)
2541 L.reverse()
2542 self._rev = self.__class__("".join(L))
2543 return self._rev
2544 s = madstring("abcdefghijklmnopqrstuvwxyz")
2545 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2546 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2547 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2548 for i in range(256):
2549 s = madstring("".join(map(chr, range(i))))
2550 t = s.rev()
2551 u = t.rev()
2552 self.assertEqual(u, s)
2553 s = madstring("12345")
2554 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002555 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002556
2557 base = "\x00" * 5
2558 s = madstring(base)
2559 self.assertEqual(s, base)
2560 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002561 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002562 self.assertEqual(hash(s), hash(base))
2563 self.assertEqual({s: 1}[base], 1)
2564 self.assertEqual({base: 1}[s], 1)
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).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002568 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002569 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002570 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002571 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002572 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002573 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002574 self.assertEqual(s * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002575 self.assertTrue(s[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002576 self.assertEqual(s[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002577 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002578 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002579 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002580 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002581 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002582 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002583 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002584 self.assertEqual(s.rstrip(), base)
2585 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002586 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002587 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002588 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002589 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002590 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002591 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002592 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002593 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002594 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002595 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002596 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002597 self.assertEqual(s.lower(), base)
2598
2599 class madunicode(str):
2600 _rev = None
2601 def rev(self):
2602 if self._rev is not None:
2603 return self._rev
2604 L = list(self)
2605 L.reverse()
2606 self._rev = self.__class__("".join(L))
2607 return self._rev
2608 u = madunicode("ABCDEF")
2609 self.assertEqual(u, "ABCDEF")
2610 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2611 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2612 base = "12345"
2613 u = madunicode(base)
2614 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002615 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002616 self.assertEqual(hash(u), hash(base))
2617 self.assertEqual({u: 1}[base], 1)
2618 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002619 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002620 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002621 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002622 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002623 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002624 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002625 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002626 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002627 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002628 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002629 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002630 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002631 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002632 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002633 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002634 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002635 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002636 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002637 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002638 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002639 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002640 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002641 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002642 self.assertEqual(u.title(), 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).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002646 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002647 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002648 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002649 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002650 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002651 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002652 self.assertEqual(u * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002653 self.assertTrue(u[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002654 self.assertEqual(u[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002655 self.assertTrue(u[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002656 self.assertEqual(u[0:0], "")
2657
2658 class sublist(list):
2659 pass
2660 a = sublist(range(5))
2661 self.assertEqual(a, list(range(5)))
2662 a.append("hello")
2663 self.assertEqual(a, list(range(5)) + ["hello"])
2664 a[5] = 5
2665 self.assertEqual(a, list(range(6)))
2666 a.extend(range(6, 20))
2667 self.assertEqual(a, list(range(20)))
2668 a[-5:] = []
2669 self.assertEqual(a, list(range(15)))
2670 del a[10:15]
2671 self.assertEqual(len(a), 10)
2672 self.assertEqual(a, list(range(10)))
2673 self.assertEqual(list(a), list(range(10)))
2674 self.assertEqual(a[0], 0)
2675 self.assertEqual(a[9], 9)
2676 self.assertEqual(a[-10], 0)
2677 self.assertEqual(a[-1], 9)
2678 self.assertEqual(a[:5], list(range(5)))
2679
2680 ## class CountedInput(file):
2681 ## """Counts lines read by self.readline().
2682 ##
2683 ## self.lineno is the 0-based ordinal of the last line read, up to
2684 ## a maximum of one greater than the number of lines in the file.
2685 ##
2686 ## self.ateof is true if and only if the final "" line has been read,
2687 ## at which point self.lineno stops incrementing, and further calls
2688 ## to readline() continue to return "".
2689 ## """
2690 ##
2691 ## lineno = 0
2692 ## ateof = 0
2693 ## def readline(self):
2694 ## if self.ateof:
2695 ## return ""
2696 ## s = file.readline(self)
2697 ## # Next line works too.
2698 ## # s = super(CountedInput, self).readline()
2699 ## self.lineno += 1
2700 ## if s == "":
2701 ## self.ateof = 1
2702 ## return s
2703 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002704 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002705 ## lines = ['a\n', 'b\n', 'c\n']
2706 ## try:
2707 ## f.writelines(lines)
2708 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002709 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002710 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2711 ## got = f.readline()
2712 ## self.assertEqual(expected, got)
2713 ## self.assertEqual(f.lineno, i)
2714 ## self.assertEqual(f.ateof, (i > len(lines)))
2715 ## f.close()
2716 ## finally:
2717 ## try:
2718 ## f.close()
2719 ## except:
2720 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002721 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002722
2723 def test_keywords(self):
2724 # Testing keyword args to basic type constructors ...
2725 self.assertEqual(int(x=1), 1)
2726 self.assertEqual(float(x=2), 2.0)
2727 self.assertEqual(int(x=3), 3)
2728 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2729 self.assertEqual(str(object=500), '500')
2730 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2731 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2732 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2733 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2734
2735 for constructor in (int, float, int, complex, str, str,
2736 tuple, list):
2737 try:
2738 constructor(bogus_keyword_arg=1)
2739 except TypeError:
2740 pass
2741 else:
2742 self.fail("expected TypeError from bogus keyword argument to %r"
2743 % constructor)
2744
2745 def test_str_subclass_as_dict_key(self):
2746 # Testing a str subclass used as dict key ..
2747
2748 class cistr(str):
2749 """Sublcass of str that computes __eq__ case-insensitively.
2750
2751 Also computes a hash code of the string in canonical form.
2752 """
2753
2754 def __init__(self, value):
2755 self.canonical = value.lower()
2756 self.hashcode = hash(self.canonical)
2757
2758 def __eq__(self, other):
2759 if not isinstance(other, cistr):
2760 other = cistr(other)
2761 return self.canonical == other.canonical
2762
2763 def __hash__(self):
2764 return self.hashcode
2765
2766 self.assertEqual(cistr('ABC'), 'abc')
2767 self.assertEqual('aBc', cistr('ABC'))
2768 self.assertEqual(str(cistr('ABC')), 'ABC')
2769
2770 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2771 self.assertEqual(d[cistr('one')], 1)
2772 self.assertEqual(d[cistr('tWo')], 2)
2773 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002774 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002775 self.assertEqual(d.get(cistr('thrEE')), 3)
2776
2777 def test_classic_comparisons(self):
2778 # Testing classic comparisons...
2779 class classic:
2780 pass
2781
2782 for base in (classic, int, object):
2783 class C(base):
2784 def __init__(self, value):
2785 self.value = int(value)
2786 def __eq__(self, other):
2787 if isinstance(other, C):
2788 return self.value == other.value
2789 if isinstance(other, int) or isinstance(other, int):
2790 return self.value == other
2791 return NotImplemented
2792 def __ne__(self, other):
2793 if isinstance(other, C):
2794 return self.value != other.value
2795 if isinstance(other, int) or isinstance(other, int):
2796 return self.value != other
2797 return NotImplemented
2798 def __lt__(self, other):
2799 if isinstance(other, C):
2800 return self.value < other.value
2801 if isinstance(other, int) or isinstance(other, int):
2802 return self.value < other
2803 return NotImplemented
2804 def __le__(self, other):
2805 if isinstance(other, C):
2806 return self.value <= other.value
2807 if isinstance(other, int) or isinstance(other, int):
2808 return self.value <= other
2809 return NotImplemented
2810 def __gt__(self, other):
2811 if isinstance(other, C):
2812 return self.value > other.value
2813 if isinstance(other, int) or isinstance(other, int):
2814 return self.value > other
2815 return NotImplemented
2816 def __ge__(self, other):
2817 if isinstance(other, C):
2818 return self.value >= other.value
2819 if isinstance(other, int) or isinstance(other, int):
2820 return self.value >= other
2821 return NotImplemented
2822
2823 c1 = C(1)
2824 c2 = C(2)
2825 c3 = C(3)
2826 self.assertEqual(c1, 1)
2827 c = {1: c1, 2: c2, 3: c3}
2828 for x in 1, 2, 3:
2829 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002830 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002831 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002832 eval("x %s y" % op),
2833 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002834 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002835 eval("x %s y" % op),
2836 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002837 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002838 eval("x %s y" % op),
2839 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002840
2841 def test_rich_comparisons(self):
2842 # Testing rich comparisons...
2843 class Z(complex):
2844 pass
2845 z = Z(1)
2846 self.assertEqual(z, 1+0j)
2847 self.assertEqual(1+0j, z)
2848 class ZZ(complex):
2849 def __eq__(self, other):
2850 try:
2851 return abs(self - other) <= 1e-6
2852 except:
2853 return NotImplemented
2854 zz = ZZ(1.0000003)
2855 self.assertEqual(zz, 1+0j)
2856 self.assertEqual(1+0j, zz)
2857
2858 class classic:
2859 pass
2860 for base in (classic, int, object, list):
2861 class C(base):
2862 def __init__(self, value):
2863 self.value = int(value)
2864 def __cmp__(self_, other):
2865 self.fail("shouldn't call __cmp__")
2866 def __eq__(self, other):
2867 if isinstance(other, C):
2868 return self.value == other.value
2869 if isinstance(other, int) or isinstance(other, int):
2870 return self.value == other
2871 return NotImplemented
2872 def __ne__(self, other):
2873 if isinstance(other, C):
2874 return self.value != other.value
2875 if isinstance(other, int) or isinstance(other, int):
2876 return self.value != other
2877 return NotImplemented
2878 def __lt__(self, other):
2879 if isinstance(other, C):
2880 return self.value < other.value
2881 if isinstance(other, int) or isinstance(other, int):
2882 return self.value < other
2883 return NotImplemented
2884 def __le__(self, other):
2885 if isinstance(other, C):
2886 return self.value <= other.value
2887 if isinstance(other, int) or isinstance(other, int):
2888 return self.value <= other
2889 return NotImplemented
2890 def __gt__(self, other):
2891 if isinstance(other, C):
2892 return self.value > other.value
2893 if isinstance(other, int) or isinstance(other, int):
2894 return self.value > other
2895 return NotImplemented
2896 def __ge__(self, other):
2897 if isinstance(other, C):
2898 return self.value >= other.value
2899 if isinstance(other, int) or isinstance(other, int):
2900 return self.value >= other
2901 return NotImplemented
2902 c1 = C(1)
2903 c2 = C(2)
2904 c3 = C(3)
2905 self.assertEqual(c1, 1)
2906 c = {1: c1, 2: c2, 3: c3}
2907 for x in 1, 2, 3:
2908 for y in 1, 2, 3:
2909 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002910 self.assertTrue(eval("c[x] %s c[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("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002913 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002914 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002915 "x=%d, y=%d" % (x, y))
2916
2917 def test_descrdoc(self):
2918 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002919 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002920 def check(descr, what):
2921 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002922 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002923 check(complex.real, "the real part of a complex number") # member descriptor
2924
2925 def test_doc_descriptor(self):
2926 # Testing __doc__ descriptor...
2927 # SF bug 542984
2928 class DocDescr(object):
2929 def __get__(self, object, otype):
2930 if object:
2931 object = object.__class__.__name__ + ' instance'
2932 if otype:
2933 otype = otype.__name__
2934 return 'object=%s; type=%s' % (object, otype)
2935 class OldClass:
2936 __doc__ = DocDescr()
2937 class NewClass(object):
2938 __doc__ = DocDescr()
2939 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2940 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2941 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2942 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2943
2944 def test_set_class(self):
2945 # Testing __class__ assignment...
2946 class C(object): pass
2947 class D(object): pass
2948 class E(object): pass
2949 class F(D, E): pass
2950 for cls in C, D, E, F:
2951 for cls2 in C, D, E, F:
2952 x = cls()
2953 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002954 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002955 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002956 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002957 def cant(x, C):
2958 try:
2959 x.__class__ = C
2960 except TypeError:
2961 pass
2962 else:
2963 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2964 try:
2965 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002966 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002967 pass
2968 else:
2969 self.fail("shouldn't allow del %r.__class__" % x)
2970 cant(C(), list)
2971 cant(list(), C)
2972 cant(C(), 1)
2973 cant(C(), object)
2974 cant(object(), list)
2975 cant(list(), object)
2976 class Int(int): __slots__ = []
2977 cant(2, Int)
2978 cant(Int(), int)
2979 cant(True, int)
2980 cant(2, bool)
2981 o = object()
2982 cant(o, type(1))
2983 cant(o, type(None))
2984 del o
2985 class G(object):
2986 __slots__ = ["a", "b"]
2987 class H(object):
2988 __slots__ = ["b", "a"]
2989 class I(object):
2990 __slots__ = ["a", "b"]
2991 class J(object):
2992 __slots__ = ["c", "b"]
2993 class K(object):
2994 __slots__ = ["a", "b", "d"]
2995 class L(H):
2996 __slots__ = ["e"]
2997 class M(I):
2998 __slots__ = ["e"]
2999 class N(J):
3000 __slots__ = ["__weakref__"]
3001 class P(J):
3002 __slots__ = ["__dict__"]
3003 class Q(J):
3004 pass
3005 class R(J):
3006 __slots__ = ["__dict__", "__weakref__"]
3007
3008 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3009 x = cls()
3010 x.a = 1
3011 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003012 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003013 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3014 self.assertEqual(x.a, 1)
3015 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003016 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003017 "assigning %r as __class__ for %r silently failed" % (cls, x))
3018 self.assertEqual(x.a, 1)
3019 for cls in G, J, K, L, M, N, P, R, list, Int:
3020 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3021 if cls is cls2:
3022 continue
3023 cant(cls(), cls2)
3024
Benjamin Peterson193152c2009-04-25 01:08:45 +00003025 # Issue5283: when __class__ changes in __del__, the wrong
3026 # type gets DECREF'd.
3027 class O(object):
3028 pass
3029 class A(object):
3030 def __del__(self):
3031 self.__class__ = O
3032 l = [A() for x in range(100)]
3033 del l
3034
Georg Brandl479a7e72008-02-05 18:13:15 +00003035 def test_set_dict(self):
3036 # Testing __dict__ assignment...
3037 class C(object): pass
3038 a = C()
3039 a.__dict__ = {'b': 1}
3040 self.assertEqual(a.b, 1)
3041 def cant(x, dict):
3042 try:
3043 x.__dict__ = dict
3044 except (AttributeError, TypeError):
3045 pass
3046 else:
3047 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3048 cant(a, None)
3049 cant(a, [])
3050 cant(a, 1)
3051 del a.__dict__ # Deleting __dict__ is allowed
3052
3053 class Base(object):
3054 pass
3055 def verify_dict_readonly(x):
3056 """
3057 x has to be an instance of a class inheriting from Base.
3058 """
3059 cant(x, {})
3060 try:
3061 del x.__dict__
3062 except (AttributeError, TypeError):
3063 pass
3064 else:
3065 self.fail("shouldn't allow del %r.__dict__" % x)
3066 dict_descr = Base.__dict__["__dict__"]
3067 try:
3068 dict_descr.__set__(x, {})
3069 except (AttributeError, TypeError):
3070 pass
3071 else:
3072 self.fail("dict_descr allowed access to %r's dict" % x)
3073
3074 # Classes don't allow __dict__ assignment and have readonly dicts
3075 class Meta1(type, Base):
3076 pass
3077 class Meta2(Base, type):
3078 pass
3079 class D(object, metaclass=Meta1):
3080 pass
3081 class E(object, metaclass=Meta2):
3082 pass
3083 for cls in C, D, E:
3084 verify_dict_readonly(cls)
3085 class_dict = cls.__dict__
3086 try:
3087 class_dict["spam"] = "eggs"
3088 except TypeError:
3089 pass
3090 else:
3091 self.fail("%r's __dict__ can be modified" % cls)
3092
3093 # Modules also disallow __dict__ assignment
3094 class Module1(types.ModuleType, Base):
3095 pass
3096 class Module2(Base, types.ModuleType):
3097 pass
3098 for ModuleType in Module1, Module2:
3099 mod = ModuleType("spam")
3100 verify_dict_readonly(mod)
3101 mod.__dict__["spam"] = "eggs"
3102
3103 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003104 # (at least not any more than regular exception's __dict__ can
3105 # be deleted; on CPython it is not the case, whereas on PyPy they
3106 # can, just like any other new-style instance's __dict__.)
3107 def can_delete_dict(e):
3108 try:
3109 del e.__dict__
3110 except (TypeError, AttributeError):
3111 return False
3112 else:
3113 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003114 class Exception1(Exception, Base):
3115 pass
3116 class Exception2(Base, Exception):
3117 pass
3118 for ExceptionType in Exception, Exception1, Exception2:
3119 e = ExceptionType()
3120 e.__dict__ = {"a": 1}
3121 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003122 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003123
3124 def test_pickles(self):
3125 # Testing pickling and copying new-style classes and objects...
3126 import pickle
3127
3128 def sorteditems(d):
3129 L = list(d.items())
3130 L.sort()
3131 return L
3132
3133 global C
3134 class C(object):
3135 def __init__(self, a, b):
3136 super(C, self).__init__()
3137 self.a = a
3138 self.b = b
3139 def __repr__(self):
3140 return "C(%r, %r)" % (self.a, self.b)
3141
3142 global C1
3143 class C1(list):
3144 def __new__(cls, a, b):
3145 return super(C1, cls).__new__(cls)
3146 def __getnewargs__(self):
3147 return (self.a, self.b)
3148 def __init__(self, a, b):
3149 self.a = a
3150 self.b = b
3151 def __repr__(self):
3152 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3153
3154 global C2
3155 class C2(int):
3156 def __new__(cls, a, b, val=0):
3157 return super(C2, cls).__new__(cls, val)
3158 def __getnewargs__(self):
3159 return (self.a, self.b, int(self))
3160 def __init__(self, a, b, val=0):
3161 self.a = a
3162 self.b = b
3163 def __repr__(self):
3164 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3165
3166 global C3
3167 class C3(object):
3168 def __init__(self, foo):
3169 self.foo = foo
3170 def __getstate__(self):
3171 return self.foo
3172 def __setstate__(self, foo):
3173 self.foo = foo
3174
3175 global C4classic, C4
3176 class C4classic: # classic
3177 pass
3178 class C4(C4classic, object): # mixed inheritance
3179 pass
3180
Guido van Rossum3926a632001-09-25 16:25:58 +00003181 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003182 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003183 s = pickle.dumps(cls, bin)
3184 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003185 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003186
3187 a = C1(1, 2); a.append(42); a.append(24)
3188 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003189 s = pickle.dumps((a, b), bin)
3190 x, y = pickle.loads(s)
3191 self.assertEqual(x.__class__, a.__class__)
3192 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3193 self.assertEqual(y.__class__, b.__class__)
3194 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3195 self.assertEqual(repr(x), repr(a))
3196 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003197 # Test for __getstate__ and __setstate__ on new style class
3198 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003199 s = pickle.dumps(u, bin)
3200 v = pickle.loads(s)
3201 self.assertEqual(u.__class__, v.__class__)
3202 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003203 # Test for picklability of hybrid class
3204 u = C4()
3205 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003206 s = pickle.dumps(u, bin)
3207 v = pickle.loads(s)
3208 self.assertEqual(u.__class__, v.__class__)
3209 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003210
Georg Brandl479a7e72008-02-05 18:13:15 +00003211 # Testing copy.deepcopy()
3212 import copy
3213 for cls in C, C1, C2:
3214 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003215 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003216
Georg Brandl479a7e72008-02-05 18:13:15 +00003217 a = C1(1, 2); a.append(42); a.append(24)
3218 b = C2("hello", "world", 42)
3219 x, y = copy.deepcopy((a, b))
3220 self.assertEqual(x.__class__, a.__class__)
3221 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3222 self.assertEqual(y.__class__, b.__class__)
3223 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3224 self.assertEqual(repr(x), repr(a))
3225 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003226
Georg Brandl479a7e72008-02-05 18:13:15 +00003227 def test_pickle_slots(self):
3228 # Testing pickling of classes with __slots__ ...
3229 import pickle
3230 # Pickling of classes with __slots__ but without __getstate__ should fail
3231 # (if using protocol 0 or 1)
3232 global B, C, D, E
3233 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003234 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003235 for base in [object, B]:
3236 class C(base):
3237 __slots__ = ['a']
3238 class D(C):
3239 pass
3240 try:
3241 pickle.dumps(C(), 0)
3242 except TypeError:
3243 pass
3244 else:
3245 self.fail("should fail: pickle C instance - %s" % base)
3246 try:
3247 pickle.dumps(C(), 0)
3248 except TypeError:
3249 pass
3250 else:
3251 self.fail("should fail: pickle D instance - %s" % base)
3252 # Give C a nice generic __getstate__ and __setstate__
3253 class C(base):
3254 __slots__ = ['a']
3255 def __getstate__(self):
3256 try:
3257 d = self.__dict__.copy()
3258 except AttributeError:
3259 d = {}
3260 for cls in self.__class__.__mro__:
3261 for sn in cls.__dict__.get('__slots__', ()):
3262 try:
3263 d[sn] = getattr(self, sn)
3264 except AttributeError:
3265 pass
3266 return d
3267 def __setstate__(self, d):
3268 for k, v in list(d.items()):
3269 setattr(self, k, v)
3270 class D(C):
3271 pass
3272 # Now it should work
3273 x = C()
3274 y = pickle.loads(pickle.dumps(x))
3275 self.assertEqual(hasattr(y, 'a'), 0)
3276 x.a = 42
3277 y = pickle.loads(pickle.dumps(x))
3278 self.assertEqual(y.a, 42)
3279 x = D()
3280 x.a = 42
3281 x.b = 100
3282 y = pickle.loads(pickle.dumps(x))
3283 self.assertEqual(y.a + y.b, 142)
3284 # A subclass that adds a slot should also work
3285 class E(C):
3286 __slots__ = ['b']
3287 x = E()
3288 x.a = 42
3289 x.b = "foo"
3290 y = pickle.loads(pickle.dumps(x))
3291 self.assertEqual(y.a, x.a)
3292 self.assertEqual(y.b, x.b)
3293
3294 def test_binary_operator_override(self):
3295 # Testing overrides of binary operations...
3296 class I(int):
3297 def __repr__(self):
3298 return "I(%r)" % int(self)
3299 def __add__(self, other):
3300 return I(int(self) + int(other))
3301 __radd__ = __add__
3302 def __pow__(self, other, mod=None):
3303 if mod is None:
3304 return I(pow(int(self), int(other)))
3305 else:
3306 return I(pow(int(self), int(other), int(mod)))
3307 def __rpow__(self, other, mod=None):
3308 if mod is None:
3309 return I(pow(int(other), int(self), mod))
3310 else:
3311 return I(pow(int(other), int(self), int(mod)))
3312
3313 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3314 self.assertEqual(repr(I(1) + 2), "I(3)")
3315 self.assertEqual(repr(1 + I(2)), "I(3)")
3316 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3317 self.assertEqual(repr(2 ** I(3)), "I(8)")
3318 self.assertEqual(repr(I(2) ** 3), "I(8)")
3319 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3320 class S(str):
3321 def __eq__(self, other):
3322 return self.lower() == other.lower()
3323
3324 def test_subclass_propagation(self):
3325 # Testing propagation of slot functions to subclasses...
3326 class A(object):
3327 pass
3328 class B(A):
3329 pass
3330 class C(A):
3331 pass
3332 class D(B, C):
3333 pass
3334 d = D()
3335 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3336 A.__hash__ = lambda self: 42
3337 self.assertEqual(hash(d), 42)
3338 C.__hash__ = lambda self: 314
3339 self.assertEqual(hash(d), 314)
3340 B.__hash__ = lambda self: 144
3341 self.assertEqual(hash(d), 144)
3342 D.__hash__ = lambda self: 100
3343 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003344 D.__hash__ = None
3345 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003346 del D.__hash__
3347 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003348 B.__hash__ = None
3349 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003350 del B.__hash__
3351 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003352 C.__hash__ = None
3353 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003354 del C.__hash__
3355 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003356 A.__hash__ = None
3357 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003358 del A.__hash__
3359 self.assertEqual(hash(d), orig_hash)
3360 d.foo = 42
3361 d.bar = 42
3362 self.assertEqual(d.foo, 42)
3363 self.assertEqual(d.bar, 42)
3364 def __getattribute__(self, name):
3365 if name == "foo":
3366 return 24
3367 return object.__getattribute__(self, name)
3368 A.__getattribute__ = __getattribute__
3369 self.assertEqual(d.foo, 24)
3370 self.assertEqual(d.bar, 42)
3371 def __getattr__(self, name):
3372 if name in ("spam", "foo", "bar"):
3373 return "hello"
3374 raise AttributeError(name)
3375 B.__getattr__ = __getattr__
3376 self.assertEqual(d.spam, "hello")
3377 self.assertEqual(d.foo, 24)
3378 self.assertEqual(d.bar, 42)
3379 del A.__getattribute__
3380 self.assertEqual(d.foo, 42)
3381 del d.foo
3382 self.assertEqual(d.foo, "hello")
3383 self.assertEqual(d.bar, 42)
3384 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003385 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003386 d.foo
3387 except AttributeError:
3388 pass
3389 else:
3390 self.fail("d.foo should be undefined now")
3391
3392 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003393 class A(object):
3394 pass
3395 class B(A):
3396 pass
3397 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003398 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003399 A.__setitem__ = lambda *a: None # crash
3400
3401 def test_buffer_inheritance(self):
3402 # Testing that buffer interface is inherited ...
3403
3404 import binascii
3405 # SF bug [#470040] ParseTuple t# vs subclasses.
3406
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003407 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003408 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003409 base = b'abc'
3410 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003411 # b2a_hex uses the buffer interface to get its argument's value, via
3412 # PyArg_ParseTuple 't#' code.
3413 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3414
Georg Brandl479a7e72008-02-05 18:13:15 +00003415 class MyInt(int):
3416 pass
3417 m = MyInt(42)
3418 try:
3419 binascii.b2a_hex(m)
3420 self.fail('subclass of int should not have a buffer interface')
3421 except TypeError:
3422 pass
3423
3424 def test_str_of_str_subclass(self):
3425 # Testing __str__ defined in subclass of str ...
3426 import binascii
3427 import io
3428
3429 class octetstring(str):
3430 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003431 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003432 def __repr__(self):
3433 return self + " repr"
3434
3435 o = octetstring('A')
3436 self.assertEqual(type(o), octetstring)
3437 self.assertEqual(type(str(o)), str)
3438 self.assertEqual(type(repr(o)), str)
3439 self.assertEqual(ord(o), 0x41)
3440 self.assertEqual(str(o), '41')
3441 self.assertEqual(repr(o), 'A repr')
3442 self.assertEqual(o.__str__(), '41')
3443 self.assertEqual(o.__repr__(), 'A repr')
3444
3445 capture = io.StringIO()
3446 # Calling str() or not exercises different internal paths.
3447 print(o, file=capture)
3448 print(str(o), file=capture)
3449 self.assertEqual(capture.getvalue(), '41\n41\n')
3450 capture.close()
3451
3452 def test_keyword_arguments(self):
3453 # Testing keyword arguments to __init__, __call__...
3454 def f(a): return a
3455 self.assertEqual(f.__call__(a=42), 42)
3456 a = []
3457 list.__init__(a, sequence=[0, 1, 2])
3458 self.assertEqual(a, [0, 1, 2])
3459
3460 def test_recursive_call(self):
3461 # Testing recursive __call__() by setting to instance of class...
3462 class A(object):
3463 pass
3464
3465 A.__call__ = A()
3466 try:
3467 A()()
3468 except RuntimeError:
3469 pass
3470 else:
3471 self.fail("Recursion limit should have been reached for __call__()")
3472
3473 def test_delete_hook(self):
3474 # Testing __del__ hook...
3475 log = []
3476 class C(object):
3477 def __del__(self):
3478 log.append(1)
3479 c = C()
3480 self.assertEqual(log, [])
3481 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003482 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003483 self.assertEqual(log, [1])
3484
3485 class D(object): pass
3486 d = D()
3487 try: del d[0]
3488 except TypeError: pass
3489 else: self.fail("invalid del() didn't raise TypeError")
3490
3491 def test_hash_inheritance(self):
3492 # Testing hash of mutable subclasses...
3493
3494 class mydict(dict):
3495 pass
3496 d = mydict()
3497 try:
3498 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003499 except TypeError:
3500 pass
3501 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003502 self.fail("hash() of dict subclass should fail")
3503
3504 class mylist(list):
3505 pass
3506 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003507 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003508 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003509 except TypeError:
3510 pass
3511 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003512 self.fail("hash() of list subclass should fail")
3513
3514 def test_str_operations(self):
3515 try: 'a' + 5
3516 except TypeError: pass
3517 else: self.fail("'' + 5 doesn't raise TypeError")
3518
3519 try: ''.split('')
3520 except ValueError: pass
3521 else: self.fail("''.split('') doesn't raise ValueError")
3522
3523 try: ''.join([0])
3524 except TypeError: pass
3525 else: self.fail("''.join([0]) doesn't raise TypeError")
3526
3527 try: ''.rindex('5')
3528 except ValueError: pass
3529 else: self.fail("''.rindex('5') doesn't raise ValueError")
3530
3531 try: '%(n)s' % None
3532 except TypeError: pass
3533 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3534
3535 try: '%(n' % {}
3536 except ValueError: pass
3537 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3538
3539 try: '%*s' % ('abc')
3540 except TypeError: pass
3541 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3542
3543 try: '%*.*s' % ('abc', 5)
3544 except TypeError: pass
3545 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3546
3547 try: '%s' % (1, 2)
3548 except TypeError: pass
3549 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3550
3551 try: '%' % None
3552 except ValueError: pass
3553 else: self.fail("'%' % None doesn't raise ValueError")
3554
3555 self.assertEqual('534253'.isdigit(), 1)
3556 self.assertEqual('534253x'.isdigit(), 0)
3557 self.assertEqual('%c' % 5, '\x05')
3558 self.assertEqual('%c' % '5', '5')
3559
3560 def test_deepcopy_recursive(self):
3561 # Testing deepcopy of recursive objects...
3562 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003563 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003564 a = Node()
3565 b = Node()
3566 a.b = b
3567 b.a = a
3568 z = deepcopy(a) # This blew up before
3569
3570 def test_unintialized_modules(self):
3571 # Testing uninitialized module objects...
3572 from types import ModuleType as M
3573 m = M.__new__(M)
3574 str(m)
3575 self.assertEqual(hasattr(m, "__name__"), 0)
3576 self.assertEqual(hasattr(m, "__file__"), 0)
3577 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003578 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003579 m.foo = 1
3580 self.assertEqual(m.__dict__, {"foo": 1})
3581
3582 def test_funny_new(self):
3583 # Testing __new__ returning something unexpected...
3584 class C(object):
3585 def __new__(cls, arg):
3586 if isinstance(arg, str): return [1, 2, 3]
3587 elif isinstance(arg, int): return object.__new__(D)
3588 else: return object.__new__(cls)
3589 class D(C):
3590 def __init__(self, arg):
3591 self.foo = arg
3592 self.assertEqual(C("1"), [1, 2, 3])
3593 self.assertEqual(D("1"), [1, 2, 3])
3594 d = D(None)
3595 self.assertEqual(d.foo, None)
3596 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003597 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003598 self.assertEqual(d.foo, 1)
3599 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003600 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003601 self.assertEqual(d.foo, 1)
3602
3603 def test_imul_bug(self):
3604 # Testing for __imul__ problems...
3605 # SF bug 544647
3606 class C(object):
3607 def __imul__(self, other):
3608 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003609 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003610 y = x
3611 y *= 1.0
3612 self.assertEqual(y, (x, 1.0))
3613 y = x
3614 y *= 2
3615 self.assertEqual(y, (x, 2))
3616 y = x
3617 y *= 3
3618 self.assertEqual(y, (x, 3))
3619 y = x
3620 y *= 1<<100
3621 self.assertEqual(y, (x, 1<<100))
3622 y = x
3623 y *= None
3624 self.assertEqual(y, (x, None))
3625 y = x
3626 y *= "foo"
3627 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003628
Georg Brandl479a7e72008-02-05 18:13:15 +00003629 def test_copy_setstate(self):
3630 # Testing that copy.*copy() correctly uses __setstate__...
3631 import copy
3632 class C(object):
3633 def __init__(self, foo=None):
3634 self.foo = foo
3635 self.__foo = foo
3636 def setfoo(self, foo=None):
3637 self.foo = foo
3638 def getfoo(self):
3639 return self.__foo
3640 def __getstate__(self):
3641 return [self.foo]
3642 def __setstate__(self_, lst):
3643 self.assertEqual(len(lst), 1)
3644 self_.__foo = self_.foo = lst[0]
3645 a = C(42)
3646 a.setfoo(24)
3647 self.assertEqual(a.foo, 24)
3648 self.assertEqual(a.getfoo(), 42)
3649 b = copy.copy(a)
3650 self.assertEqual(b.foo, 24)
3651 self.assertEqual(b.getfoo(), 24)
3652 b = copy.deepcopy(a)
3653 self.assertEqual(b.foo, 24)
3654 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003655
Georg Brandl479a7e72008-02-05 18:13:15 +00003656 def test_slices(self):
3657 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003658
Georg Brandl479a7e72008-02-05 18:13:15 +00003659 # Strings
3660 self.assertEqual("hello"[:4], "hell")
3661 self.assertEqual("hello"[slice(4)], "hell")
3662 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3663 class S(str):
3664 def __getitem__(self, x):
3665 return str.__getitem__(self, x)
3666 self.assertEqual(S("hello")[:4], "hell")
3667 self.assertEqual(S("hello")[slice(4)], "hell")
3668 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3669 # Tuples
3670 self.assertEqual((1,2,3)[:2], (1,2))
3671 self.assertEqual((1,2,3)[slice(2)], (1,2))
3672 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3673 class T(tuple):
3674 def __getitem__(self, x):
3675 return tuple.__getitem__(self, x)
3676 self.assertEqual(T((1,2,3))[:2], (1,2))
3677 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3678 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3679 # Lists
3680 self.assertEqual([1,2,3][:2], [1,2])
3681 self.assertEqual([1,2,3][slice(2)], [1,2])
3682 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3683 class L(list):
3684 def __getitem__(self, x):
3685 return list.__getitem__(self, x)
3686 self.assertEqual(L([1,2,3])[:2], [1,2])
3687 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3688 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3689 # Now do lists and __setitem__
3690 a = L([1,2,3])
3691 a[slice(1, 3)] = [3,2]
3692 self.assertEqual(a, [1,3,2])
3693 a[slice(0, 2, 1)] = [3,1]
3694 self.assertEqual(a, [3,1,2])
3695 a.__setitem__(slice(1, 3), [2,1])
3696 self.assertEqual(a, [3,2,1])
3697 a.__setitem__(slice(0, 2, 1), [2,3])
3698 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003699
Georg Brandl479a7e72008-02-05 18:13:15 +00003700 def test_subtype_resurrection(self):
3701 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003702
Georg Brandl479a7e72008-02-05 18:13:15 +00003703 class C(object):
3704 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003705
Georg Brandl479a7e72008-02-05 18:13:15 +00003706 def __del__(self):
3707 # resurrect the instance
3708 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003709
Georg Brandl479a7e72008-02-05 18:13:15 +00003710 c = C()
3711 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003712
Benjamin Petersone549ead2009-03-28 21:42:05 +00003713 # The most interesting thing here is whether this blows up, due to
3714 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3715 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003716 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003717
Georg Brandl479a7e72008-02-05 18:13:15 +00003718 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003719 # the last container slot works: that will attempt to delete c again,
3720 # which will cause c to get appended back to the container again
3721 # "during" the del. (On non-CPython implementations, however, __del__
3722 # is typically not called again.)
3723 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003724 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003725 del C.container[-1]
3726 if support.check_impl_detail():
3727 support.gc_collect()
3728 self.assertEqual(len(C.container), 1)
3729 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003730
Georg Brandl479a7e72008-02-05 18:13:15 +00003731 # Make c mortal again, so that the test framework with -l doesn't report
3732 # it as a leak.
3733 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003734
Georg Brandl479a7e72008-02-05 18:13:15 +00003735 def test_slots_trash(self):
3736 # Testing slot trash...
3737 # Deallocating deeply nested slotted trash caused stack overflows
3738 class trash(object):
3739 __slots__ = ['x']
3740 def __init__(self, x):
3741 self.x = x
3742 o = None
3743 for i in range(50000):
3744 o = trash(o)
3745 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003746
Georg Brandl479a7e72008-02-05 18:13:15 +00003747 def test_slots_multiple_inheritance(self):
3748 # SF bug 575229, multiple inheritance w/ slots dumps core
3749 class A(object):
3750 __slots__=()
3751 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003752 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003753 class C(A,B) :
3754 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003755 if support.check_impl_detail():
3756 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003757 self.assertTrue(hasattr(C, '__dict__'))
3758 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003759 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003760
Georg Brandl479a7e72008-02-05 18:13:15 +00003761 def test_rmul(self):
3762 # Testing correct invocation of __rmul__...
3763 # SF patch 592646
3764 class C(object):
3765 def __mul__(self, other):
3766 return "mul"
3767 def __rmul__(self, other):
3768 return "rmul"
3769 a = C()
3770 self.assertEqual(a*2, "mul")
3771 self.assertEqual(a*2.2, "mul")
3772 self.assertEqual(2*a, "rmul")
3773 self.assertEqual(2.2*a, "rmul")
3774
3775 def test_ipow(self):
3776 # Testing correct invocation of __ipow__...
3777 # [SF bug 620179]
3778 class C(object):
3779 def __ipow__(self, other):
3780 pass
3781 a = C()
3782 a **= 2
3783
3784 def test_mutable_bases(self):
3785 # Testing mutable bases...
3786
3787 # stuff that should work:
3788 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003789 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003790 class C2(object):
3791 def __getattribute__(self, attr):
3792 if attr == 'a':
3793 return 2
3794 else:
3795 return super(C2, self).__getattribute__(attr)
3796 def meth(self):
3797 return 1
3798 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003799 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003800 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003801 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003802 d = D()
3803 e = E()
3804 D.__bases__ = (C,)
3805 D.__bases__ = (C2,)
3806 self.assertEqual(d.meth(), 1)
3807 self.assertEqual(e.meth(), 1)
3808 self.assertEqual(d.a, 2)
3809 self.assertEqual(e.a, 2)
3810 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003811
Georg Brandl479a7e72008-02-05 18:13:15 +00003812 try:
3813 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003814 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003815 pass
3816 else:
3817 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003818
Georg Brandl479a7e72008-02-05 18:13:15 +00003819 try:
3820 D.__bases__ = ()
3821 except TypeError as msg:
3822 if str(msg) == "a new-style class can't have only classic bases":
3823 self.fail("wrong error message for .__bases__ = ()")
3824 else:
3825 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003826
Georg Brandl479a7e72008-02-05 18:13:15 +00003827 try:
3828 D.__bases__ = (D,)
3829 except TypeError:
3830 pass
3831 else:
3832 # actually, we'll have crashed by here...
3833 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003834
Georg Brandl479a7e72008-02-05 18:13:15 +00003835 try:
3836 D.__bases__ = (C, C)
3837 except TypeError:
3838 pass
3839 else:
3840 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003841
Georg Brandl479a7e72008-02-05 18:13:15 +00003842 try:
3843 D.__bases__ = (E,)
3844 except TypeError:
3845 pass
3846 else:
3847 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003848
Benjamin Petersonae937c02009-04-18 20:54:08 +00003849 def test_builtin_bases(self):
3850 # Make sure all the builtin types can have their base queried without
3851 # segfaulting. See issue #5787.
3852 builtin_types = [tp for tp in builtins.__dict__.values()
3853 if isinstance(tp, type)]
3854 for tp in builtin_types:
3855 object.__getattribute__(tp, "__bases__")
3856 if tp is not object:
3857 self.assertEqual(len(tp.__bases__), 1, tp)
3858
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003859 class L(list):
3860 pass
3861
3862 class C(object):
3863 pass
3864
3865 class D(C):
3866 pass
3867
3868 try:
3869 L.__bases__ = (dict,)
3870 except TypeError:
3871 pass
3872 else:
3873 self.fail("shouldn't turn list subclass into dict subclass")
3874
3875 try:
3876 list.__bases__ = (dict,)
3877 except TypeError:
3878 pass
3879 else:
3880 self.fail("shouldn't be able to assign to list.__bases__")
3881
3882 try:
3883 D.__bases__ = (C, list)
3884 except TypeError:
3885 pass
3886 else:
3887 assert 0, "best_base calculation found wanting"
3888
Benjamin Petersonae937c02009-04-18 20:54:08 +00003889
Georg Brandl479a7e72008-02-05 18:13:15 +00003890 def test_mutable_bases_with_failing_mro(self):
3891 # Testing mutable bases with failing mro...
3892 class WorkOnce(type):
3893 def __new__(self, name, bases, ns):
3894 self.flag = 0
3895 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3896 def mro(self):
3897 if self.flag > 0:
3898 raise RuntimeError("bozo")
3899 else:
3900 self.flag += 1
3901 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003902
Georg Brandl479a7e72008-02-05 18:13:15 +00003903 class WorkAlways(type):
3904 def mro(self):
3905 # this is here to make sure that .mro()s aren't called
3906 # with an exception set (which was possible at one point).
3907 # An error message will be printed in a debug build.
3908 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003909 return type.mro(self)
3910
Georg Brandl479a7e72008-02-05 18:13:15 +00003911 class C(object):
3912 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003913
Georg Brandl479a7e72008-02-05 18:13:15 +00003914 class C2(object):
3915 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003916
Georg Brandl479a7e72008-02-05 18:13:15 +00003917 class D(C):
3918 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003919
Georg Brandl479a7e72008-02-05 18:13:15 +00003920 class E(D):
3921 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003922
Georg Brandl479a7e72008-02-05 18:13:15 +00003923 class F(D, metaclass=WorkOnce):
3924 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003925
Georg Brandl479a7e72008-02-05 18:13:15 +00003926 class G(D, metaclass=WorkAlways):
3927 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003928
Georg Brandl479a7e72008-02-05 18:13:15 +00003929 # Immediate subclasses have their mro's adjusted in alphabetical
3930 # order, so E's will get adjusted before adjusting F's fails. We
3931 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003932
Georg Brandl479a7e72008-02-05 18:13:15 +00003933 E_mro_before = E.__mro__
3934 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003935
Armin Rigofd163f92005-12-29 15:59:19 +00003936 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003937 D.__bases__ = (C2,)
3938 except RuntimeError:
3939 self.assertEqual(E.__mro__, E_mro_before)
3940 self.assertEqual(D.__mro__, D_mro_before)
3941 else:
3942 self.fail("exception not propagated")
3943
3944 def test_mutable_bases_catch_mro_conflict(self):
3945 # Testing mutable bases catch mro conflict...
3946 class A(object):
3947 pass
3948
3949 class B(object):
3950 pass
3951
3952 class C(A, B):
3953 pass
3954
3955 class D(A, B):
3956 pass
3957
3958 class E(C, D):
3959 pass
3960
3961 try:
3962 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003963 except TypeError:
3964 pass
3965 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003966 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003967
Georg Brandl479a7e72008-02-05 18:13:15 +00003968 def test_mutable_names(self):
3969 # Testing mutable names...
3970 class C(object):
3971 pass
3972
3973 # C.__module__ could be 'test_descr' or '__main__'
3974 mod = C.__module__
3975
3976 C.__name__ = 'D'
3977 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3978
3979 C.__name__ = 'D.E'
3980 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3981
3982 def test_subclass_right_op(self):
3983 # Testing correct dispatch of subclass overloading __r<op>__...
3984
3985 # This code tests various cases where right-dispatch of a subclass
3986 # should be preferred over left-dispatch of a base class.
3987
3988 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3989
3990 class B(int):
3991 def __floordiv__(self, other):
3992 return "B.__floordiv__"
3993 def __rfloordiv__(self, other):
3994 return "B.__rfloordiv__"
3995
3996 self.assertEqual(B(1) // 1, "B.__floordiv__")
3997 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3998
3999 # Case 2: subclass of object; this is just the baseline for case 3
4000
4001 class C(object):
4002 def __floordiv__(self, other):
4003 return "C.__floordiv__"
4004 def __rfloordiv__(self, other):
4005 return "C.__rfloordiv__"
4006
4007 self.assertEqual(C() // 1, "C.__floordiv__")
4008 self.assertEqual(1 // C(), "C.__rfloordiv__")
4009
4010 # Case 3: subclass of new-style class; here it gets interesting
4011
4012 class D(C):
4013 def __floordiv__(self, other):
4014 return "D.__floordiv__"
4015 def __rfloordiv__(self, other):
4016 return "D.__rfloordiv__"
4017
4018 self.assertEqual(D() // C(), "D.__floordiv__")
4019 self.assertEqual(C() // D(), "D.__rfloordiv__")
4020
4021 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4022
4023 class E(C):
4024 pass
4025
4026 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4027
4028 self.assertEqual(E() // 1, "C.__floordiv__")
4029 self.assertEqual(1 // E(), "C.__rfloordiv__")
4030 self.assertEqual(E() // C(), "C.__floordiv__")
4031 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4032
Benjamin Petersone549ead2009-03-28 21:42:05 +00004033 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004034 def test_meth_class_get(self):
4035 # Testing __get__ method of METH_CLASS C methods...
4036 # Full coverage of descrobject.c::classmethod_get()
4037
4038 # Baseline
4039 arg = [1, 2, 3]
4040 res = {1: None, 2: None, 3: None}
4041 self.assertEqual(dict.fromkeys(arg), res)
4042 self.assertEqual({}.fromkeys(arg), res)
4043
4044 # Now get the descriptor
4045 descr = dict.__dict__["fromkeys"]
4046
4047 # More baseline using the descriptor directly
4048 self.assertEqual(descr.__get__(None, dict)(arg), res)
4049 self.assertEqual(descr.__get__({})(arg), res)
4050
4051 # Now check various error cases
4052 try:
4053 descr.__get__(None, None)
4054 except TypeError:
4055 pass
4056 else:
4057 self.fail("shouldn't have allowed descr.__get__(None, None)")
4058 try:
4059 descr.__get__(42)
4060 except TypeError:
4061 pass
4062 else:
4063 self.fail("shouldn't have allowed descr.__get__(42)")
4064 try:
4065 descr.__get__(None, 42)
4066 except TypeError:
4067 pass
4068 else:
4069 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4070 try:
4071 descr.__get__(None, int)
4072 except TypeError:
4073 pass
4074 else:
4075 self.fail("shouldn't have allowed descr.__get__(None, int)")
4076
4077 def test_isinst_isclass(self):
4078 # Testing proxy isinstance() and isclass()...
4079 class Proxy(object):
4080 def __init__(self, obj):
4081 self.__obj = obj
4082 def __getattribute__(self, name):
4083 if name.startswith("_Proxy__"):
4084 return object.__getattribute__(self, name)
4085 else:
4086 return getattr(self.__obj, name)
4087 # Test with a classic class
4088 class C:
4089 pass
4090 a = C()
4091 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004092 self.assertIsInstance(a, C) # Baseline
4093 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004094 # Test with a classic subclass
4095 class D(C):
4096 pass
4097 a = D()
4098 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004099 self.assertIsInstance(a, C) # Baseline
4100 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004101 # Test with a new-style class
4102 class C(object):
4103 pass
4104 a = C()
4105 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004106 self.assertIsInstance(a, C) # Baseline
4107 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004108 # Test with a new-style subclass
4109 class D(C):
4110 pass
4111 a = D()
4112 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004113 self.assertIsInstance(a, C) # Baseline
4114 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004115
4116 def test_proxy_super(self):
4117 # Testing super() for a proxy object...
4118 class Proxy(object):
4119 def __init__(self, obj):
4120 self.__obj = obj
4121 def __getattribute__(self, name):
4122 if name.startswith("_Proxy__"):
4123 return object.__getattribute__(self, name)
4124 else:
4125 return getattr(self.__obj, name)
4126
4127 class B(object):
4128 def f(self):
4129 return "B.f"
4130
4131 class C(B):
4132 def f(self):
4133 return super(C, self).f() + "->C.f"
4134
4135 obj = C()
4136 p = Proxy(obj)
4137 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4138
4139 def test_carloverre(self):
4140 # Testing prohibition of Carlo Verre's hack...
4141 try:
4142 object.__setattr__(str, "foo", 42)
4143 except TypeError:
4144 pass
4145 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004146 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004147 try:
4148 object.__delattr__(str, "lower")
4149 except TypeError:
4150 pass
4151 else:
4152 self.fail("Carlo Verre __delattr__ succeeded!")
4153
4154 def test_weakref_segfault(self):
4155 # Testing weakref segfault...
4156 # SF 742911
4157 import weakref
4158
4159 class Provoker:
4160 def __init__(self, referrent):
4161 self.ref = weakref.ref(referrent)
4162
4163 def __del__(self):
4164 x = self.ref()
4165
4166 class Oops(object):
4167 pass
4168
4169 o = Oops()
4170 o.whatever = Provoker(o)
4171 del o
4172
4173 def test_wrapper_segfault(self):
4174 # SF 927248: deeply nested wrappers could cause stack overflow
4175 f = lambda:None
4176 for i in range(1000000):
4177 f = f.__call__
4178 f = None
4179
4180 def test_file_fault(self):
4181 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004182 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004183 class StdoutGuard:
4184 def __getattr__(self, attr):
4185 sys.stdout = sys.__stdout__
4186 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4187 sys.stdout = StdoutGuard()
4188 try:
4189 print("Oops!")
4190 except RuntimeError:
4191 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004192 finally:
4193 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004194
4195 def test_vicious_descriptor_nonsense(self):
4196 # Testing vicious_descriptor_nonsense...
4197
4198 # A potential segfault spotted by Thomas Wouters in mail to
4199 # python-dev 2003-04-17, turned into an example & fixed by Michael
4200 # Hudson just less than four months later...
4201
4202 class Evil(object):
4203 def __hash__(self):
4204 return hash('attr')
4205 def __eq__(self, other):
4206 del C.attr
4207 return 0
4208
4209 class Descr(object):
4210 def __get__(self, ob, type=None):
4211 return 1
4212
4213 class C(object):
4214 attr = Descr()
4215
4216 c = C()
4217 c.__dict__[Evil()] = 0
4218
4219 self.assertEqual(c.attr, 1)
4220 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004221 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004222 self.assertEqual(hasattr(c, 'attr'), False)
4223
4224 def test_init(self):
4225 # SF 1155938
4226 class Foo(object):
4227 def __init__(self):
4228 return 10
4229 try:
4230 Foo()
4231 except TypeError:
4232 pass
4233 else:
4234 self.fail("did not test __init__() for None return")
4235
4236 def test_method_wrapper(self):
4237 # Testing method-wrapper objects...
4238 # <type 'method-wrapper'> did not support any reflection before 2.5
4239
Mark Dickinson211c6252009-02-01 10:28:51 +00004240 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004241
4242 l = []
4243 self.assertEqual(l.__add__, l.__add__)
4244 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004245 self.assertTrue(l.__add__ != [5].__add__)
4246 self.assertTrue(l.__add__ != l.__mul__)
4247 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004248 if hasattr(l.__add__, '__self__'):
4249 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004250 self.assertTrue(l.__add__.__self__ is l)
4251 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004252 else:
4253 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004254 self.assertTrue(l.__add__.im_self is l)
4255 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004256 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4257 try:
4258 hash(l.__add__)
4259 except TypeError:
4260 pass
4261 else:
4262 self.fail("no TypeError from hash([].__add__)")
4263
4264 t = ()
4265 t += (7,)
4266 self.assertEqual(t.__add__, (7,).__add__)
4267 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4268
4269 def test_not_implemented(self):
4270 # Testing NotImplemented...
4271 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004272 import operator
4273
4274 def specialmethod(self, other):
4275 return NotImplemented
4276
4277 def check(expr, x, y):
4278 try:
4279 exec(expr, {'x': x, 'y': y, 'operator': operator})
4280 except TypeError:
4281 pass
4282 else:
4283 self.fail("no TypeError from %r" % (expr,))
4284
4285 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4286 # TypeErrors
4287 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4288 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004289 for name, expr, iexpr in [
4290 ('__add__', 'x + y', 'x += y'),
4291 ('__sub__', 'x - y', 'x -= y'),
4292 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004293 ('__truediv__', 'operator.truediv(x, y)', None),
4294 ('__floordiv__', 'operator.floordiv(x, y)', None),
4295 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004296 ('__mod__', 'x % y', 'x %= y'),
4297 ('__divmod__', 'divmod(x, y)', None),
4298 ('__pow__', 'x ** y', 'x **= y'),
4299 ('__lshift__', 'x << y', 'x <<= y'),
4300 ('__rshift__', 'x >> y', 'x >>= y'),
4301 ('__and__', 'x & y', 'x &= y'),
4302 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004303 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004304 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004305 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004306 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004307 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004308 check(expr, a, N1)
4309 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004310 if iexpr:
4311 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004312 check(iexpr, a, N1)
4313 check(iexpr, a, N2)
4314 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004315 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004316 c = C()
4317 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004318 check(iexpr, c, N1)
4319 check(iexpr, c, N2)
4320
Georg Brandl479a7e72008-02-05 18:13:15 +00004321 def test_assign_slice(self):
4322 # ceval.c's assign_slice used to check for
4323 # tp->tp_as_sequence->sq_slice instead of
4324 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004325
Georg Brandl479a7e72008-02-05 18:13:15 +00004326 class C(object):
4327 def __setitem__(self, idx, value):
4328 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004329
Georg Brandl479a7e72008-02-05 18:13:15 +00004330 c = C()
4331 c[1:2] = 3
4332 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004333
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004334 def test_set_and_no_get(self):
4335 # See
4336 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4337 class Descr(object):
4338
4339 def __init__(self, name):
4340 self.name = name
4341
4342 def __set__(self, obj, value):
4343 obj.__dict__[self.name] = value
4344 descr = Descr("a")
4345
4346 class X(object):
4347 a = descr
4348
4349 x = X()
4350 self.assertIs(x.a, descr)
4351 x.a = 42
4352 self.assertEqual(x.a, 42)
4353
Benjamin Peterson21896a32010-03-21 22:03:03 +00004354 # Also check type_getattro for correctness.
4355 class Meta(type):
4356 pass
4357 class X(object):
4358 __metaclass__ = Meta
4359 X.a = 42
4360 Meta.a = Descr("a")
4361 self.assertEqual(X.a, 42)
4362
Benjamin Peterson9262b842008-11-17 22:45:50 +00004363 def test_getattr_hooks(self):
4364 # issue 4230
4365
4366 class Descriptor(object):
4367 counter = 0
4368 def __get__(self, obj, objtype=None):
4369 def getter(name):
4370 self.counter += 1
4371 raise AttributeError(name)
4372 return getter
4373
4374 descr = Descriptor()
4375 class A(object):
4376 __getattribute__ = descr
4377 class B(object):
4378 __getattr__ = descr
4379 class C(object):
4380 __getattribute__ = descr
4381 __getattr__ = descr
4382
4383 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004384 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004385 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004386 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004387 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004388 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004389
4390 import gc
4391 class EvilGetattribute(object):
4392 # This used to segfault
4393 def __getattr__(self, name):
4394 raise AttributeError(name)
4395 def __getattribute__(self, name):
4396 del EvilGetattribute.__getattr__
4397 for i in range(5):
4398 gc.collect()
4399 raise AttributeError(name)
4400
4401 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4402
Benjamin Peterson477ba912011-01-12 15:34:01 +00004403 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004404 # type pretends not to have __abstractmethods__.
4405 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4406 class meta(type):
4407 pass
4408 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004409 class X(object):
4410 pass
4411 with self.assertRaises(AttributeError):
4412 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004413
Victor Stinner3249dec2011-05-01 23:19:15 +02004414 def test_proxy_call(self):
4415 class FakeStr:
4416 __class__ = str
4417
4418 fake_str = FakeStr()
4419 # isinstance() reads __class__
4420 self.assertTrue(isinstance(fake_str, str))
4421
4422 # call a method descriptor
4423 with self.assertRaises(TypeError):
4424 str.split(fake_str)
4425
4426 # call a slot wrapper descriptor
4427 with self.assertRaises(TypeError):
4428 str.__add__(fake_str, "abc")
4429
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004430 def test_repr_as_str(self):
4431 # Issue #11603: crash or infinite loop when rebinding __str__ as
4432 # __repr__.
4433 class Foo:
4434 pass
4435 Foo.__repr__ = Foo.__str__
4436 foo = Foo()
4437 str(foo)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004438
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004439 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004440 with self.assertRaises(ValueError) as cm:
4441 class X:
4442 __slots__ = ["foo"]
4443 foo = None
4444 m = str(cm.exception)
4445 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4446
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004447 def test_set_doc(self):
4448 class X:
4449 "elephant"
4450 X.__doc__ = "banana"
4451 self.assertEqual(X.__doc__, "banana")
4452 with self.assertRaises(TypeError) as cm:
4453 type(list).__dict__["__doc__"].__set__(list, "blah")
4454 self.assertIn("can't set list.__doc__", str(cm.exception))
4455 with self.assertRaises(TypeError) as cm:
4456 type(X).__dict__["__doc__"].__delete__(X)
4457 self.assertIn("can't delete X.__doc__", str(cm.exception))
4458 self.assertEqual(X.__doc__, "banana")
4459
Antoine Pitrou9d574812011-12-12 13:47:25 +01004460 def test_qualname(self):
4461 descriptors = [str.lower, complex.real, float.real, int.__add__]
4462 types = ['method', 'member', 'getset', 'wrapper']
4463
4464 # make sure we have an example of each type of descriptor
4465 for d, n in zip(descriptors, types):
4466 self.assertEqual(type(d).__name__, n + '_descriptor')
4467
4468 for d in descriptors:
4469 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4470 self.assertEqual(d.__qualname__, qualname)
4471
4472 self.assertEqual(str.lower.__qualname__, 'str.lower')
4473 self.assertEqual(complex.real.__qualname__, 'complex.real')
4474 self.assertEqual(float.real.__qualname__, 'float.real')
4475 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4476
Victor Stinner6f738742012-02-25 01:22:36 +01004477 def test_qualname_dict(self):
4478 ns = {'__qualname__': 'some.name'}
4479 tp = type('Foo', (), ns)
4480 self.assertEqual(tp.__qualname__, 'some.name')
4481 self.assertEqual(tp.__dict__['__qualname__'], 'some.name')
4482 self.assertEqual(ns, {'__qualname__': 'some.name'})
4483
4484 ns = {'__qualname__': 1}
4485 self.assertRaises(TypeError, type, 'Foo', (), ns)
4486
Antoine Pitrou9d574812011-12-12 13:47:25 +01004487
Georg Brandl479a7e72008-02-05 18:13:15 +00004488class DictProxyTests(unittest.TestCase):
4489 def setUp(self):
4490 class C(object):
4491 def meth(self):
4492 pass
4493 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004494
Brett Cannon7a540732011-02-22 03:04:06 +00004495 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4496 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004497 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004498 # Testing dict-proxy keys...
4499 it = self.C.__dict__.keys()
4500 self.assertNotIsInstance(it, list)
4501 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004502 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004503 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Victor Stinner6f738742012-02-25 01:22:36 +01004504 '__qualname__', '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004505
Brett Cannon7a540732011-02-22 03:04:06 +00004506 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4507 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004508 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004509 # Testing dict-proxy values...
4510 it = self.C.__dict__.values()
4511 self.assertNotIsInstance(it, list)
4512 values = list(it)
Victor Stinner6f738742012-02-25 01:22:36 +01004513 self.assertEqual(len(values), 6)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004514
Brett Cannon7a540732011-02-22 03:04:06 +00004515 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4516 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004517 def test_iter_items(self):
4518 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004519 it = self.C.__dict__.items()
4520 self.assertNotIsInstance(it, list)
4521 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004522 keys.sort()
4523 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Victor Stinner6f738742012-02-25 01:22:36 +01004524 '__qualname__', '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004525
Georg Brandl479a7e72008-02-05 18:13:15 +00004526 def test_dict_type_with_metaclass(self):
4527 # Testing type of __dict__ when metaclass set...
4528 class B(object):
4529 pass
4530 class M(type):
4531 pass
4532 class C(metaclass=M):
4533 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4534 pass
4535 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004536
Ezio Melottiac53ab62010-12-18 14:59:43 +00004537 def test_repr(self):
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004538 # Testing dict_proxy.__repr__.
4539 # We can't blindly compare with the repr of another dict as ordering
4540 # of keys and values is arbitrary and may differ.
4541 r = repr(self.C.__dict__)
4542 self.assertTrue(r.startswith('dict_proxy('), r)
4543 self.assertTrue(r.endswith(')'), r)
4544 for k, v in self.C.__dict__.items():
4545 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004546
Christian Heimesbbffeb62008-01-24 09:42:52 +00004547
Georg Brandl479a7e72008-02-05 18:13:15 +00004548class PTypesLongInitTest(unittest.TestCase):
4549 # This is in its own TestCase so that it can be run before any other tests.
4550 def test_pytype_long_ready(self):
4551 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004552
Georg Brandl479a7e72008-02-05 18:13:15 +00004553 # This dumps core when SF bug 551412 isn't fixed --
4554 # but only when test_descr.py is run separately.
4555 # (That can't be helped -- as soon as PyType_Ready()
4556 # is called for PyLong_Type, the bug is gone.)
4557 class UserLong(object):
4558 def __pow__(self, *args):
4559 pass
4560 try:
4561 pow(0, UserLong(), 0)
4562 except:
4563 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004564
Georg Brandl479a7e72008-02-05 18:13:15 +00004565 # Another segfault only when run early
4566 # (before PyType_Ready(tuple) is called)
4567 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004568
4569
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004570def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004571 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004572 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004573 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004574
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004575if __name__ == "__main__":
4576 test_main()