blob: b214996aa9f0816a57860440d5c2d22fdd86eda1 [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)
655 new_calls[:] = []
656
657 class B(metaclass=BMeta):
658 pass
659 # BMeta.__new__ calls AMeta.__new__ with super:
660 self.assertEqual(['BMeta', 'AMeta'], new_calls)
661 new_calls[:] = []
662
663 class C(A, B):
664 pass
665 # The most derived metaclass is BMeta:
666 self.assertEqual(['BMeta', 'AMeta'], new_calls)
667 new_calls[:] = []
668 # 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)
675 new_calls[:] = []
676 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)
682 new_calls[:] = []
683 self.assertIn('BMeta_was_here', D.__dict__)
684
685 class E(C, metaclass=AMeta):
686 pass
687 self.assertEqual(['BMeta', 'AMeta'], new_calls)
688 new_calls[:] = []
689 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)
730 prepare_calls[:] = []
731 self.assertEqual(['ANotMeta'], new_calls)
732 new_calls[:] = []
733
734 class B(metaclass=BNotMeta):
735 pass
736 self.assertIs(BNotMeta, type(B))
737 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
738 prepare_calls[:] = []
739 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
740 new_calls[:] = []
741
742 class C(A, B):
743 pass
744 self.assertIs(BNotMeta, type(C))
745 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
746 new_calls[:] = []
747 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
748 prepare_calls[:] = []
749
750 class C2(B, A):
751 pass
752 self.assertIs(BNotMeta, type(C2))
753 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
754 new_calls[:] = []
755 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
756 prepare_calls[:] = []
757
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)
768 new_calls[:] = []
769 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
770 prepare_calls[:] = []
771
772 class F(object(), C):
773 pass
774 self.assertIs(BNotMeta, type(F))
775 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
776 new_calls[:] = []
777 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
778 prepare_calls[:] = []
779
780 class F2(C, object()):
781 pass
782 self.assertIs(BNotMeta, type(F2))
783 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
784 new_calls[:] = []
785 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
786 prepare_calls[:] = []
787
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 Petersone549ead2009-03-28 21:42:05 +00001446 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001447 def test_classmethods_in_c(self):
1448 # Testing C-based class methods...
1449 import xxsubtype as spam
1450 a = (1, 2, 3)
1451 d = {'abc': 123}
1452 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1453 self.assertEqual(x, spam.spamlist)
1454 self.assertEqual(a, a1)
1455 self.assertEqual(d, d1)
1456 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1457 self.assertEqual(x, spam.spamlist)
1458 self.assertEqual(a, a1)
1459 self.assertEqual(d, d1)
1460
1461 def test_staticmethods(self):
1462 # Testing static methods...
1463 class C(object):
1464 def foo(*a): return a
1465 goo = staticmethod(foo)
1466 c = C()
1467 self.assertEqual(C.goo(1), (1,))
1468 self.assertEqual(c.goo(1), (1,))
1469 self.assertEqual(c.foo(1), (c, 1,))
1470 class D(C):
1471 pass
1472 d = D()
1473 self.assertEqual(D.goo(1), (1,))
1474 self.assertEqual(d.goo(1), (1,))
1475 self.assertEqual(d.foo(1), (d, 1))
1476 self.assertEqual(D.foo(d, 1), (d, 1))
1477
Benjamin Petersone549ead2009-03-28 21:42:05 +00001478 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001479 def test_staticmethods_in_c(self):
1480 # Testing C-based static methods...
1481 import xxsubtype as spam
1482 a = (1, 2, 3)
1483 d = {"abc": 123}
1484 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1485 self.assertEqual(x, None)
1486 self.assertEqual(a, a1)
1487 self.assertEqual(d, d1)
1488 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1489 self.assertEqual(x, None)
1490 self.assertEqual(a, a1)
1491 self.assertEqual(d, d1)
1492
1493 def test_classic(self):
1494 # Testing classic classes...
1495 class C:
1496 def foo(*a): return a
1497 goo = classmethod(foo)
1498 c = C()
1499 self.assertEqual(C.goo(1), (C, 1))
1500 self.assertEqual(c.goo(1), (C, 1))
1501 self.assertEqual(c.foo(1), (c, 1))
1502 class D(C):
1503 pass
1504 d = D()
1505 self.assertEqual(D.goo(1), (D, 1))
1506 self.assertEqual(d.goo(1), (D, 1))
1507 self.assertEqual(d.foo(1), (d, 1))
1508 self.assertEqual(D.foo(d, 1), (d, 1))
1509 class E: # *not* subclassing from C
1510 foo = C.foo
1511 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001512 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001513
1514 def test_compattr(self):
1515 # Testing computed attributes...
1516 class C(object):
1517 class computed_attribute(object):
1518 def __init__(self, get, set=None, delete=None):
1519 self.__get = get
1520 self.__set = set
1521 self.__delete = delete
1522 def __get__(self, obj, type=None):
1523 return self.__get(obj)
1524 def __set__(self, obj, value):
1525 return self.__set(obj, value)
1526 def __delete__(self, obj):
1527 return self.__delete(obj)
1528 def __init__(self):
1529 self.__x = 0
1530 def __get_x(self):
1531 x = self.__x
1532 self.__x = x+1
1533 return x
1534 def __set_x(self, x):
1535 self.__x = x
1536 def __delete_x(self):
1537 del self.__x
1538 x = computed_attribute(__get_x, __set_x, __delete_x)
1539 a = C()
1540 self.assertEqual(a.x, 0)
1541 self.assertEqual(a.x, 1)
1542 a.x = 10
1543 self.assertEqual(a.x, 10)
1544 self.assertEqual(a.x, 11)
1545 del a.x
1546 self.assertEqual(hasattr(a, 'x'), 0)
1547
1548 def test_newslots(self):
1549 # Testing __new__ slot override...
1550 class C(list):
1551 def __new__(cls):
1552 self = list.__new__(cls)
1553 self.foo = 1
1554 return self
1555 def __init__(self):
1556 self.foo = self.foo + 2
1557 a = C()
1558 self.assertEqual(a.foo, 3)
1559 self.assertEqual(a.__class__, C)
1560 class D(C):
1561 pass
1562 b = D()
1563 self.assertEqual(b.foo, 3)
1564 self.assertEqual(b.__class__, D)
1565
1566 def test_altmro(self):
1567 # Testing mro() and overriding it...
1568 class A(object):
1569 def f(self): return "A"
1570 class B(A):
1571 pass
1572 class C(A):
1573 def f(self): return "C"
1574 class D(B, C):
1575 pass
1576 self.assertEqual(D.mro(), [D, B, C, A, object])
1577 self.assertEqual(D.__mro__, (D, B, C, A, object))
1578 self.assertEqual(D().f(), "C")
1579
1580 class PerverseMetaType(type):
1581 def mro(cls):
1582 L = type.mro(cls)
1583 L.reverse()
1584 return L
1585 class X(D,B,C,A, metaclass=PerverseMetaType):
1586 pass
1587 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1588 self.assertEqual(X().f(), "A")
1589
1590 try:
1591 class _metaclass(type):
1592 def mro(self):
1593 return [self, dict, object]
1594 class X(object, metaclass=_metaclass):
1595 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001596 # In CPython, the class creation above already raises
1597 # TypeError, as a protection against the fact that
1598 # instances of X would segfault it. In other Python
1599 # implementations it would be ok to let the class X
1600 # be created, but instead get a clean TypeError on the
1601 # __setitem__ below.
1602 x = object.__new__(X)
1603 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001604 except TypeError:
1605 pass
1606 else:
1607 self.fail("devious mro() return not caught")
1608
1609 try:
1610 class _metaclass(type):
1611 def mro(self):
1612 return [1]
1613 class X(object, metaclass=_metaclass):
1614 pass
1615 except TypeError:
1616 pass
1617 else:
1618 self.fail("non-class mro() return not caught")
1619
1620 try:
1621 class _metaclass(type):
1622 def mro(self):
1623 return 1
1624 class X(object, metaclass=_metaclass):
1625 pass
1626 except TypeError:
1627 pass
1628 else:
1629 self.fail("non-sequence mro() return not caught")
1630
1631 def test_overloading(self):
1632 # Testing operator overloading...
1633
1634 class B(object):
1635 "Intermediate class because object doesn't have a __setattr__"
1636
1637 class C(B):
1638 def __getattr__(self, name):
1639 if name == "foo":
1640 return ("getattr", name)
1641 else:
1642 raise AttributeError
1643 def __setattr__(self, name, value):
1644 if name == "foo":
1645 self.setattr = (name, value)
1646 else:
1647 return B.__setattr__(self, name, value)
1648 def __delattr__(self, name):
1649 if name == "foo":
1650 self.delattr = name
1651 else:
1652 return B.__delattr__(self, name)
1653
1654 def __getitem__(self, key):
1655 return ("getitem", key)
1656 def __setitem__(self, key, value):
1657 self.setitem = (key, value)
1658 def __delitem__(self, key):
1659 self.delitem = key
1660
1661 a = C()
1662 self.assertEqual(a.foo, ("getattr", "foo"))
1663 a.foo = 12
1664 self.assertEqual(a.setattr, ("foo", 12))
1665 del a.foo
1666 self.assertEqual(a.delattr, "foo")
1667
1668 self.assertEqual(a[12], ("getitem", 12))
1669 a[12] = 21
1670 self.assertEqual(a.setitem, (12, 21))
1671 del a[12]
1672 self.assertEqual(a.delitem, 12)
1673
1674 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1675 a[0:10] = "foo"
1676 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1677 del a[0:10]
1678 self.assertEqual(a.delitem, (slice(0, 10)))
1679
1680 def test_methods(self):
1681 # Testing methods...
1682 class C(object):
1683 def __init__(self, x):
1684 self.x = x
1685 def foo(self):
1686 return self.x
1687 c1 = C(1)
1688 self.assertEqual(c1.foo(), 1)
1689 class D(C):
1690 boo = C.foo
1691 goo = c1.foo
1692 d2 = D(2)
1693 self.assertEqual(d2.foo(), 2)
1694 self.assertEqual(d2.boo(), 2)
1695 self.assertEqual(d2.goo(), 1)
1696 class E(object):
1697 foo = C.foo
1698 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001699 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001700
Benjamin Peterson224205f2009-05-08 03:25:19 +00001701 def test_special_method_lookup(self):
1702 # The lookup of special methods bypasses __getattr__ and
1703 # __getattribute__, but they still can be descriptors.
1704
1705 def run_context(manager):
1706 with manager:
1707 pass
1708 def iden(self):
1709 return self
1710 def hello(self):
1711 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001712 def empty_seq(self):
1713 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001714 def zero(self):
1715 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001716 def complex_num(self):
1717 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001718 def stop(self):
1719 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001720 def return_true(self, thing=None):
1721 return True
1722 def do_isinstance(obj):
1723 return isinstance(int, obj)
1724 def do_issubclass(obj):
1725 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001726 def do_dict_missing(checker):
1727 class DictSub(checker.__class__, dict):
1728 pass
1729 self.assertEqual(DictSub()["hi"], 4)
1730 def some_number(self_, key):
1731 self.assertEqual(key, "hi")
1732 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001733 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001734 def format_impl(self, spec):
1735 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001736
1737 # It would be nice to have every special method tested here, but I'm
1738 # only listing the ones I can remember outside of typeobject.c, since it
1739 # does it right.
1740 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001741 ("__bytes__", bytes, hello, set(), {}),
1742 ("__reversed__", reversed, empty_seq, set(), {}),
1743 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001744 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001745 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1746 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001747 ("__missing__", do_dict_missing, some_number,
1748 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001749 ("__subclasscheck__", do_issubclass, return_true,
1750 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001751 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1752 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001753 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001754 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001755 ("__floor__", math.floor, zero, set(), {}),
1756 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001757 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001758 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001759 ]
1760
1761 class Checker(object):
1762 def __getattr__(self, attr, test=self):
1763 test.fail("__getattr__ called with {0}".format(attr))
1764 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001765 if attr not in ok:
1766 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001767 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001768 class SpecialDescr(object):
1769 def __init__(self, impl):
1770 self.impl = impl
1771 def __get__(self, obj, owner):
1772 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001773 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001774 class MyException(Exception):
1775 pass
1776 class ErrDescr(object):
1777 def __get__(self, obj, owner):
1778 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001779
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001780 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001781 class X(Checker):
1782 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001783 for attr, obj in env.items():
1784 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001785 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001786 runner(X())
1787
1788 record = []
1789 class X(Checker):
1790 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001791 for attr, obj in env.items():
1792 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001793 setattr(X, name, SpecialDescr(meth_impl))
1794 runner(X())
1795 self.assertEqual(record, [1], name)
1796
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001797 class X(Checker):
1798 pass
1799 for attr, obj in env.items():
1800 setattr(X, attr, obj)
1801 setattr(X, name, ErrDescr())
1802 try:
1803 runner(X())
1804 except MyException:
1805 pass
1806 else:
1807 self.fail("{0!r} didn't raise".format(name))
1808
Georg Brandl479a7e72008-02-05 18:13:15 +00001809 def test_specials(self):
1810 # Testing special operators...
1811 # Test operators like __hash__ for which a built-in default exists
1812
1813 # Test the default behavior for static classes
1814 class C(object):
1815 def __getitem__(self, i):
1816 if 0 <= i < 10: return i
1817 raise IndexError
1818 c1 = C()
1819 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001820 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001821 self.assertNotEqual(id(c1), id(c2))
1822 hash(c1)
1823 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001824 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001825 self.assertTrue(c1 != c2)
1826 self.assertTrue(not c1 != c1)
1827 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001828 # Note that the module name appears in str/repr, and that varies
1829 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001830 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001831 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001832 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001833 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001834 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001835 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001836 # Test the default behavior for dynamic classes
1837 class D(object):
1838 def __getitem__(self, i):
1839 if 0 <= i < 10: return i
1840 raise IndexError
1841 d1 = D()
1842 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001843 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001844 self.assertNotEqual(id(d1), id(d2))
1845 hash(d1)
1846 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001847 self.assertEqual(d1, d1)
1848 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001849 self.assertTrue(not d1 != d1)
1850 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001851 # Note that the module name appears in str/repr, and that varies
1852 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001853 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001854 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001855 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001856 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001857 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001858 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001859 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001860 class Proxy(object):
1861 def __init__(self, x):
1862 self.x = x
1863 def __bool__(self):
1864 return not not self.x
1865 def __hash__(self):
1866 return hash(self.x)
1867 def __eq__(self, other):
1868 return self.x == other
1869 def __ne__(self, other):
1870 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001871 def __ge__(self, other):
1872 return self.x >= other
1873 def __gt__(self, other):
1874 return self.x > other
1875 def __le__(self, other):
1876 return self.x <= other
1877 def __lt__(self, other):
1878 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001879 def __str__(self):
1880 return "Proxy:%s" % self.x
1881 def __repr__(self):
1882 return "Proxy(%r)" % self.x
1883 def __contains__(self, value):
1884 return value in self.x
1885 p0 = Proxy(0)
1886 p1 = Proxy(1)
1887 p_1 = Proxy(-1)
1888 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001889 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001890 self.assertEqual(hash(p0), hash(0))
1891 self.assertEqual(p0, p0)
1892 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001893 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001894 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001895 self.assertTrue(p0 < p1)
1896 self.assertTrue(p0 <= p1)
1897 self.assertTrue(p1 > p0)
1898 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001899 self.assertEqual(str(p0), "Proxy:0")
1900 self.assertEqual(repr(p0), "Proxy(0)")
1901 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001902 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001903 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001904 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001905 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001906
Georg Brandl479a7e72008-02-05 18:13:15 +00001907 def test_weakrefs(self):
1908 # Testing weak references...
1909 import weakref
1910 class C(object):
1911 pass
1912 c = C()
1913 r = weakref.ref(c)
1914 self.assertEqual(r(), c)
1915 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001916 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001917 self.assertEqual(r(), None)
1918 del r
1919 class NoWeak(object):
1920 __slots__ = ['foo']
1921 no = NoWeak()
1922 try:
1923 weakref.ref(no)
1924 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001925 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001926 else:
1927 self.fail("weakref.ref(no) should be illegal")
1928 class Weak(object):
1929 __slots__ = ['foo', '__weakref__']
1930 yes = Weak()
1931 r = weakref.ref(yes)
1932 self.assertEqual(r(), yes)
1933 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001934 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001935 self.assertEqual(r(), None)
1936 del r
1937
1938 def test_properties(self):
1939 # Testing property...
1940 class C(object):
1941 def getx(self):
1942 return self.__x
1943 def setx(self, value):
1944 self.__x = value
1945 def delx(self):
1946 del self.__x
1947 x = property(getx, setx, delx, doc="I'm the x property.")
1948 a = C()
1949 self.assertFalse(hasattr(a, "x"))
1950 a.x = 42
1951 self.assertEqual(a._C__x, 42)
1952 self.assertEqual(a.x, 42)
1953 del a.x
1954 self.assertFalse(hasattr(a, "x"))
1955 self.assertFalse(hasattr(a, "_C__x"))
1956 C.x.__set__(a, 100)
1957 self.assertEqual(C.x.__get__(a), 100)
1958 C.x.__delete__(a)
1959 self.assertFalse(hasattr(a, "x"))
1960
1961 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001962 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001963
1964 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001965 self.assertIn("__doc__", attrs)
1966 self.assertIn("fget", attrs)
1967 self.assertIn("fset", attrs)
1968 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001969
1970 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001971 self.assertTrue(raw.fget is C.__dict__['getx'])
1972 self.assertTrue(raw.fset is C.__dict__['setx'])
1973 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001974
1975 for attr in "__doc__", "fget", "fset", "fdel":
1976 try:
1977 setattr(raw, attr, 42)
1978 except AttributeError as msg:
1979 if str(msg).find('readonly') < 0:
1980 self.fail("when setting readonly attr %r on a property, "
1981 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1982 else:
1983 self.fail("expected AttributeError from trying to set readonly %r "
1984 "attr on a property" % attr)
1985
1986 class D(object):
1987 __getitem__ = property(lambda s: 1/0)
1988
1989 d = D()
1990 try:
1991 for i in d:
1992 str(i)
1993 except ZeroDivisionError:
1994 pass
1995 else:
1996 self.fail("expected ZeroDivisionError from bad property")
1997
R. David Murray378c0cf2010-02-24 01:46:21 +00001998 @unittest.skipIf(sys.flags.optimize >= 2,
1999 "Docstrings are omitted with -O2 and above")
2000 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002001 class E(object):
2002 def getter(self):
2003 "getter method"
2004 return 0
2005 def setter(self_, value):
2006 "setter method"
2007 pass
2008 prop = property(getter)
2009 self.assertEqual(prop.__doc__, "getter method")
2010 prop2 = property(fset=setter)
2011 self.assertEqual(prop2.__doc__, None)
2012
R. David Murray378c0cf2010-02-24 01:46:21 +00002013 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002014 # this segfaulted in 2.5b2
2015 try:
2016 import _testcapi
2017 except ImportError:
2018 pass
2019 else:
2020 class X(object):
2021 p = property(_testcapi.test_with_docstring)
2022
2023 def test_properties_plus(self):
2024 class C(object):
2025 foo = property(doc="hello")
2026 @foo.getter
2027 def foo(self):
2028 return self._foo
2029 @foo.setter
2030 def foo(self, value):
2031 self._foo = abs(value)
2032 @foo.deleter
2033 def foo(self):
2034 del self._foo
2035 c = C()
2036 self.assertEqual(C.foo.__doc__, "hello")
2037 self.assertFalse(hasattr(c, "foo"))
2038 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002039 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00002040 self.assertEqual(c._foo, 42)
2041 self.assertEqual(c.foo, 42)
2042 del c.foo
2043 self.assertFalse(hasattr(c, '_foo'))
2044 self.assertFalse(hasattr(c, "foo"))
2045
2046 class D(C):
2047 @C.foo.deleter
2048 def foo(self):
2049 try:
2050 del self._foo
2051 except AttributeError:
2052 pass
2053 d = D()
2054 d.foo = 24
2055 self.assertEqual(d.foo, 24)
2056 del d.foo
2057 del d.foo
2058
2059 class E(object):
2060 @property
2061 def foo(self):
2062 return self._foo
2063 @foo.setter
2064 def foo(self, value):
2065 raise RuntimeError
2066 @foo.setter
2067 def foo(self, value):
2068 self._foo = abs(value)
2069 @foo.deleter
2070 def foo(self, value=None):
2071 del self._foo
2072
2073 e = E()
2074 e.foo = -42
2075 self.assertEqual(e.foo, 42)
2076 del e.foo
2077
2078 class F(E):
2079 @E.foo.deleter
2080 def foo(self):
2081 del self._foo
2082 @foo.setter
2083 def foo(self, value):
2084 self._foo = max(0, value)
2085 f = F()
2086 f.foo = -10
2087 self.assertEqual(f.foo, 0)
2088 del f.foo
2089
2090 def test_dict_constructors(self):
2091 # Testing dict constructor ...
2092 d = dict()
2093 self.assertEqual(d, {})
2094 d = dict({})
2095 self.assertEqual(d, {})
2096 d = dict({1: 2, 'a': 'b'})
2097 self.assertEqual(d, {1: 2, 'a': 'b'})
2098 self.assertEqual(d, dict(list(d.items())))
2099 self.assertEqual(d, dict(iter(d.items())))
2100 d = dict({'one':1, 'two':2})
2101 self.assertEqual(d, dict(one=1, two=2))
2102 self.assertEqual(d, dict(**d))
2103 self.assertEqual(d, dict({"one": 1}, two=2))
2104 self.assertEqual(d, dict([("two", 2)], one=1))
2105 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2106 self.assertEqual(d, dict(**d))
2107
2108 for badarg in 0, 0, 0j, "0", [0], (0,):
2109 try:
2110 dict(badarg)
2111 except TypeError:
2112 pass
2113 except ValueError:
2114 if badarg == "0":
2115 # It's a sequence, and its elements are also sequences (gotta
2116 # love strings <wink>), but they aren't of length 2, so this
2117 # one seemed better as a ValueError than a TypeError.
2118 pass
2119 else:
2120 self.fail("no TypeError from dict(%r)" % badarg)
2121 else:
2122 self.fail("no TypeError from dict(%r)" % badarg)
2123
2124 try:
2125 dict({}, {})
2126 except TypeError:
2127 pass
2128 else:
2129 self.fail("no TypeError from dict({}, {})")
2130
2131 class Mapping:
2132 # Lacks a .keys() method; will be added later.
2133 dict = {1:2, 3:4, 'a':1j}
2134
2135 try:
2136 dict(Mapping())
2137 except TypeError:
2138 pass
2139 else:
2140 self.fail("no TypeError from dict(incomplete mapping)")
2141
2142 Mapping.keys = lambda self: list(self.dict.keys())
2143 Mapping.__getitem__ = lambda self, i: self.dict[i]
2144 d = dict(Mapping())
2145 self.assertEqual(d, Mapping.dict)
2146
2147 # Init from sequence of iterable objects, each producing a 2-sequence.
2148 class AddressBookEntry:
2149 def __init__(self, first, last):
2150 self.first = first
2151 self.last = last
2152 def __iter__(self):
2153 return iter([self.first, self.last])
2154
2155 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2156 AddressBookEntry('Barry', 'Peters'),
2157 AddressBookEntry('Tim', 'Peters'),
2158 AddressBookEntry('Barry', 'Warsaw')])
2159 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2160
2161 d = dict(zip(range(4), range(1, 5)))
2162 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2163
2164 # Bad sequence lengths.
2165 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2166 try:
2167 dict(bad)
2168 except ValueError:
2169 pass
2170 else:
2171 self.fail("no ValueError from dict(%r)" % bad)
2172
2173 def test_dir(self):
2174 # Testing dir() ...
2175 junk = 12
2176 self.assertEqual(dir(), ['junk', 'self'])
2177 del junk
2178
2179 # Just make sure these don't blow up!
2180 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2181 dir(arg)
2182
2183 # Test dir on new-style classes. Since these have object as a
2184 # base class, a lot more gets sucked in.
2185 def interesting(strings):
2186 return [s for s in strings if not s.startswith('_')]
2187
2188 class C(object):
2189 Cdata = 1
2190 def Cmethod(self): pass
2191
2192 cstuff = ['Cdata', 'Cmethod']
2193 self.assertEqual(interesting(dir(C)), cstuff)
2194
2195 c = C()
2196 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002197 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002198
2199 c.cdata = 2
2200 c.cmethod = lambda self: 0
2201 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002202 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002203
2204 class A(C):
2205 Adata = 1
2206 def Amethod(self): pass
2207
2208 astuff = ['Adata', 'Amethod'] + cstuff
2209 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002210 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002211 a = A()
2212 self.assertEqual(interesting(dir(a)), astuff)
2213 a.adata = 42
2214 a.amethod = lambda self: 3
2215 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002216 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002217
2218 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002219 class M(type(sys)):
2220 pass
2221 minstance = M("m")
2222 minstance.b = 2
2223 minstance.a = 1
2224 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2225 self.assertEqual(names, ['a', 'b'])
2226
2227 class M2(M):
2228 def getdict(self):
2229 return "Not a dict!"
2230 __dict__ = property(getdict)
2231
2232 m2instance = M2("m2")
2233 m2instance.b = 2
2234 m2instance.a = 1
2235 self.assertEqual(m2instance.__dict__, "Not a dict!")
2236 try:
2237 dir(m2instance)
2238 except TypeError:
2239 pass
2240
2241 # Two essentially featureless objects, just inheriting stuff from
2242 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002243 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2244 if support.check_impl_detail():
2245 # None differs in PyPy: it has a __nonzero__
2246 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002247
2248 # Nasty test case for proxied objects
2249 class Wrapper(object):
2250 def __init__(self, obj):
2251 self.__obj = obj
2252 def __repr__(self):
2253 return "Wrapper(%s)" % repr(self.__obj)
2254 def __getitem__(self, key):
2255 return Wrapper(self.__obj[key])
2256 def __len__(self):
2257 return len(self.__obj)
2258 def __getattr__(self, name):
2259 return Wrapper(getattr(self.__obj, name))
2260
2261 class C(object):
2262 def __getclass(self):
2263 return Wrapper(type(self))
2264 __class__ = property(__getclass)
2265
2266 dir(C()) # This used to segfault
2267
2268 def test_supers(self):
2269 # Testing super...
2270
2271 class A(object):
2272 def meth(self, a):
2273 return "A(%r)" % a
2274
2275 self.assertEqual(A().meth(1), "A(1)")
2276
2277 class B(A):
2278 def __init__(self):
2279 self.__super = super(B, self)
2280 def meth(self, a):
2281 return "B(%r)" % a + self.__super.meth(a)
2282
2283 self.assertEqual(B().meth(2), "B(2)A(2)")
2284
2285 class C(A):
2286 def meth(self, a):
2287 return "C(%r)" % a + self.__super.meth(a)
2288 C._C__super = super(C)
2289
2290 self.assertEqual(C().meth(3), "C(3)A(3)")
2291
2292 class D(C, B):
2293 def meth(self, a):
2294 return "D(%r)" % a + super(D, self).meth(a)
2295
2296 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2297
2298 # Test for subclassing super
2299
2300 class mysuper(super):
2301 def __init__(self, *args):
2302 return super(mysuper, self).__init__(*args)
2303
2304 class E(D):
2305 def meth(self, a):
2306 return "E(%r)" % a + mysuper(E, self).meth(a)
2307
2308 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2309
2310 class F(E):
2311 def meth(self, a):
2312 s = self.__super # == mysuper(F, self)
2313 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2314 F._F__super = mysuper(F)
2315
2316 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2317
2318 # Make sure certain errors are raised
2319
2320 try:
2321 super(D, 42)
2322 except TypeError:
2323 pass
2324 else:
2325 self.fail("shouldn't allow super(D, 42)")
2326
2327 try:
2328 super(D, C())
2329 except TypeError:
2330 pass
2331 else:
2332 self.fail("shouldn't allow super(D, C())")
2333
2334 try:
2335 super(D).__get__(12)
2336 except TypeError:
2337 pass
2338 else:
2339 self.fail("shouldn't allow super(D).__get__(12)")
2340
2341 try:
2342 super(D).__get__(C())
2343 except TypeError:
2344 pass
2345 else:
2346 self.fail("shouldn't allow super(D).__get__(C())")
2347
2348 # Make sure data descriptors can be overridden and accessed via super
2349 # (new feature in Python 2.3)
2350
2351 class DDbase(object):
2352 def getx(self): return 42
2353 x = property(getx)
2354
2355 class DDsub(DDbase):
2356 def getx(self): return "hello"
2357 x = property(getx)
2358
2359 dd = DDsub()
2360 self.assertEqual(dd.x, "hello")
2361 self.assertEqual(super(DDsub, dd).x, 42)
2362
2363 # Ensure that super() lookup of descriptor from classmethod
2364 # works (SF ID# 743627)
2365
2366 class Base(object):
2367 aProp = property(lambda self: "foo")
2368
2369 class Sub(Base):
2370 @classmethod
2371 def test(klass):
2372 return super(Sub,klass).aProp
2373
2374 self.assertEqual(Sub.test(), Base.aProp)
2375
2376 # Verify that super() doesn't allow keyword args
2377 try:
2378 super(Base, kw=1)
2379 except TypeError:
2380 pass
2381 else:
2382 self.assertEqual("super shouldn't accept keyword args")
2383
2384 def test_basic_inheritance(self):
2385 # Testing inheritance from basic types...
2386
2387 class hexint(int):
2388 def __repr__(self):
2389 return hex(self)
2390 def __add__(self, other):
2391 return hexint(int.__add__(self, other))
2392 # (Note that overriding __radd__ doesn't work,
2393 # because the int type gets first dibs.)
2394 self.assertEqual(repr(hexint(7) + 9), "0x10")
2395 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2396 a = hexint(12345)
2397 self.assertEqual(a, 12345)
2398 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002399 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002400 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002401 self.assertTrue((+a).__class__ is int)
2402 self.assertTrue((a >> 0).__class__ is int)
2403 self.assertTrue((a << 0).__class__ is int)
2404 self.assertTrue((hexint(0) << 12).__class__ is int)
2405 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002406
2407 class octlong(int):
2408 __slots__ = []
2409 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002410 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002411 def __add__(self, other):
2412 return self.__class__(super(octlong, self).__add__(other))
2413 __radd__ = __add__
2414 self.assertEqual(str(octlong(3) + 5), "0o10")
2415 # (Note that overriding __radd__ here only seems to work
2416 # because the example uses a short int left argument.)
2417 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2418 a = octlong(12345)
2419 self.assertEqual(a, 12345)
2420 self.assertEqual(int(a), 12345)
2421 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002422 self.assertTrue(int(a).__class__ is int)
2423 self.assertTrue((+a).__class__ is int)
2424 self.assertTrue((-a).__class__ is int)
2425 self.assertTrue((-octlong(0)).__class__ is int)
2426 self.assertTrue((a >> 0).__class__ is int)
2427 self.assertTrue((a << 0).__class__ is int)
2428 self.assertTrue((a - 0).__class__ is int)
2429 self.assertTrue((a * 1).__class__ is int)
2430 self.assertTrue((a ** 1).__class__ is int)
2431 self.assertTrue((a // 1).__class__ is int)
2432 self.assertTrue((1 * a).__class__ is int)
2433 self.assertTrue((a | 0).__class__ is int)
2434 self.assertTrue((a ^ 0).__class__ is int)
2435 self.assertTrue((a & -1).__class__ is int)
2436 self.assertTrue((octlong(0) << 12).__class__ is int)
2437 self.assertTrue((octlong(0) >> 12).__class__ is int)
2438 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002439
2440 # Because octlong overrides __add__, we can't check the absence of +0
2441 # optimizations using octlong.
2442 class longclone(int):
2443 pass
2444 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002445 self.assertTrue((a + 0).__class__ is int)
2446 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002447
2448 # Check that negative clones don't segfault
2449 a = longclone(-1)
2450 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002451 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002452
2453 class precfloat(float):
2454 __slots__ = ['prec']
2455 def __init__(self, value=0.0, prec=12):
2456 self.prec = int(prec)
2457 def __repr__(self):
2458 return "%.*g" % (self.prec, self)
2459 self.assertEqual(repr(precfloat(1.1)), "1.1")
2460 a = precfloat(12345)
2461 self.assertEqual(a, 12345.0)
2462 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002463 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002464 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002465 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002466
2467 class madcomplex(complex):
2468 def __repr__(self):
2469 return "%.17gj%+.17g" % (self.imag, self.real)
2470 a = madcomplex(-3, 4)
2471 self.assertEqual(repr(a), "4j-3")
2472 base = complex(-3, 4)
2473 self.assertEqual(base.__class__, complex)
2474 self.assertEqual(a, base)
2475 self.assertEqual(complex(a), base)
2476 self.assertEqual(complex(a).__class__, complex)
2477 a = madcomplex(a) # just trying another form of the constructor
2478 self.assertEqual(repr(a), "4j-3")
2479 self.assertEqual(a, base)
2480 self.assertEqual(complex(a), base)
2481 self.assertEqual(complex(a).__class__, complex)
2482 self.assertEqual(hash(a), hash(base))
2483 self.assertEqual((+a).__class__, complex)
2484 self.assertEqual((a + 0).__class__, complex)
2485 self.assertEqual(a + 0, base)
2486 self.assertEqual((a - 0).__class__, complex)
2487 self.assertEqual(a - 0, base)
2488 self.assertEqual((a * 1).__class__, complex)
2489 self.assertEqual(a * 1, base)
2490 self.assertEqual((a / 1).__class__, complex)
2491 self.assertEqual(a / 1, base)
2492
2493 class madtuple(tuple):
2494 _rev = None
2495 def rev(self):
2496 if self._rev is not None:
2497 return self._rev
2498 L = list(self)
2499 L.reverse()
2500 self._rev = self.__class__(L)
2501 return self._rev
2502 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2503 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2504 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2505 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2506 for i in range(512):
2507 t = madtuple(range(i))
2508 u = t.rev()
2509 v = u.rev()
2510 self.assertEqual(v, t)
2511 a = madtuple((1,2,3,4,5))
2512 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002513 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002514 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002515 self.assertTrue(a[:].__class__ is tuple)
2516 self.assertTrue((a * 1).__class__ is tuple)
2517 self.assertTrue((a * 0).__class__ is tuple)
2518 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002519 a = madtuple(())
2520 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002521 self.assertTrue(tuple(a).__class__ is tuple)
2522 self.assertTrue((a + a).__class__ is tuple)
2523 self.assertTrue((a * 0).__class__ is tuple)
2524 self.assertTrue((a * 1).__class__ is tuple)
2525 self.assertTrue((a * 2).__class__ is tuple)
2526 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002527
2528 class madstring(str):
2529 _rev = None
2530 def rev(self):
2531 if self._rev is not None:
2532 return self._rev
2533 L = list(self)
2534 L.reverse()
2535 self._rev = self.__class__("".join(L))
2536 return self._rev
2537 s = madstring("abcdefghijklmnopqrstuvwxyz")
2538 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2539 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2540 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2541 for i in range(256):
2542 s = madstring("".join(map(chr, range(i))))
2543 t = s.rev()
2544 u = t.rev()
2545 self.assertEqual(u, s)
2546 s = madstring("12345")
2547 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002548 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002549
2550 base = "\x00" * 5
2551 s = madstring(base)
2552 self.assertEqual(s, base)
2553 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002554 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002555 self.assertEqual(hash(s), hash(base))
2556 self.assertEqual({s: 1}[base], 1)
2557 self.assertEqual({base: 1}[s], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002558 self.assertTrue((s + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002559 self.assertEqual(s + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002560 self.assertTrue(("" + s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002561 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002562 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002563 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002564 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002565 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002566 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002567 self.assertEqual(s * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002568 self.assertTrue(s[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002569 self.assertEqual(s[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002570 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002571 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002572 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002573 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002574 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002575 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002576 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002577 self.assertEqual(s.rstrip(), base)
2578 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002579 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002580 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002581 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002582 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002583 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002584 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002585 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002586 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002587 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002588 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002589 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002590 self.assertEqual(s.lower(), base)
2591
2592 class madunicode(str):
2593 _rev = None
2594 def rev(self):
2595 if self._rev is not None:
2596 return self._rev
2597 L = list(self)
2598 L.reverse()
2599 self._rev = self.__class__("".join(L))
2600 return self._rev
2601 u = madunicode("ABCDEF")
2602 self.assertEqual(u, "ABCDEF")
2603 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2604 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2605 base = "12345"
2606 u = madunicode(base)
2607 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002608 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002609 self.assertEqual(hash(u), hash(base))
2610 self.assertEqual({u: 1}[base], 1)
2611 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002612 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002613 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002614 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002615 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002616 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002618 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002619 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002620 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002621 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002622 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002623 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002624 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002625 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002626 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002627 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002628 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002629 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002630 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002631 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002632 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002633 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002634 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002635 self.assertEqual(u.title(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002636 self.assertTrue((u + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002637 self.assertEqual(u + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002638 self.assertTrue(("" + u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002639 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002640 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002641 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002642 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002643 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002644 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002645 self.assertEqual(u * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002646 self.assertTrue(u[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002647 self.assertEqual(u[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002648 self.assertTrue(u[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002649 self.assertEqual(u[0:0], "")
2650
2651 class sublist(list):
2652 pass
2653 a = sublist(range(5))
2654 self.assertEqual(a, list(range(5)))
2655 a.append("hello")
2656 self.assertEqual(a, list(range(5)) + ["hello"])
2657 a[5] = 5
2658 self.assertEqual(a, list(range(6)))
2659 a.extend(range(6, 20))
2660 self.assertEqual(a, list(range(20)))
2661 a[-5:] = []
2662 self.assertEqual(a, list(range(15)))
2663 del a[10:15]
2664 self.assertEqual(len(a), 10)
2665 self.assertEqual(a, list(range(10)))
2666 self.assertEqual(list(a), list(range(10)))
2667 self.assertEqual(a[0], 0)
2668 self.assertEqual(a[9], 9)
2669 self.assertEqual(a[-10], 0)
2670 self.assertEqual(a[-1], 9)
2671 self.assertEqual(a[:5], list(range(5)))
2672
2673 ## class CountedInput(file):
2674 ## """Counts lines read by self.readline().
2675 ##
2676 ## self.lineno is the 0-based ordinal of the last line read, up to
2677 ## a maximum of one greater than the number of lines in the file.
2678 ##
2679 ## self.ateof is true if and only if the final "" line has been read,
2680 ## at which point self.lineno stops incrementing, and further calls
2681 ## to readline() continue to return "".
2682 ## """
2683 ##
2684 ## lineno = 0
2685 ## ateof = 0
2686 ## def readline(self):
2687 ## if self.ateof:
2688 ## return ""
2689 ## s = file.readline(self)
2690 ## # Next line works too.
2691 ## # s = super(CountedInput, self).readline()
2692 ## self.lineno += 1
2693 ## if s == "":
2694 ## self.ateof = 1
2695 ## return s
2696 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002697 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002698 ## lines = ['a\n', 'b\n', 'c\n']
2699 ## try:
2700 ## f.writelines(lines)
2701 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002702 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002703 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2704 ## got = f.readline()
2705 ## self.assertEqual(expected, got)
2706 ## self.assertEqual(f.lineno, i)
2707 ## self.assertEqual(f.ateof, (i > len(lines)))
2708 ## f.close()
2709 ## finally:
2710 ## try:
2711 ## f.close()
2712 ## except:
2713 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002714 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002715
2716 def test_keywords(self):
2717 # Testing keyword args to basic type constructors ...
2718 self.assertEqual(int(x=1), 1)
2719 self.assertEqual(float(x=2), 2.0)
2720 self.assertEqual(int(x=3), 3)
2721 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2722 self.assertEqual(str(object=500), '500')
2723 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2724 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2725 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2726 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2727
2728 for constructor in (int, float, int, complex, str, str,
2729 tuple, list):
2730 try:
2731 constructor(bogus_keyword_arg=1)
2732 except TypeError:
2733 pass
2734 else:
2735 self.fail("expected TypeError from bogus keyword argument to %r"
2736 % constructor)
2737
2738 def test_str_subclass_as_dict_key(self):
2739 # Testing a str subclass used as dict key ..
2740
2741 class cistr(str):
2742 """Sublcass of str that computes __eq__ case-insensitively.
2743
2744 Also computes a hash code of the string in canonical form.
2745 """
2746
2747 def __init__(self, value):
2748 self.canonical = value.lower()
2749 self.hashcode = hash(self.canonical)
2750
2751 def __eq__(self, other):
2752 if not isinstance(other, cistr):
2753 other = cistr(other)
2754 return self.canonical == other.canonical
2755
2756 def __hash__(self):
2757 return self.hashcode
2758
2759 self.assertEqual(cistr('ABC'), 'abc')
2760 self.assertEqual('aBc', cistr('ABC'))
2761 self.assertEqual(str(cistr('ABC')), 'ABC')
2762
2763 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2764 self.assertEqual(d[cistr('one')], 1)
2765 self.assertEqual(d[cistr('tWo')], 2)
2766 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002767 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002768 self.assertEqual(d.get(cistr('thrEE')), 3)
2769
2770 def test_classic_comparisons(self):
2771 # Testing classic comparisons...
2772 class classic:
2773 pass
2774
2775 for base in (classic, int, object):
2776 class C(base):
2777 def __init__(self, value):
2778 self.value = int(value)
2779 def __eq__(self, other):
2780 if isinstance(other, C):
2781 return self.value == other.value
2782 if isinstance(other, int) or isinstance(other, int):
2783 return self.value == other
2784 return NotImplemented
2785 def __ne__(self, other):
2786 if isinstance(other, C):
2787 return self.value != other.value
2788 if isinstance(other, int) or isinstance(other, int):
2789 return self.value != other
2790 return NotImplemented
2791 def __lt__(self, other):
2792 if isinstance(other, C):
2793 return self.value < other.value
2794 if isinstance(other, int) or isinstance(other, int):
2795 return self.value < other
2796 return NotImplemented
2797 def __le__(self, other):
2798 if isinstance(other, C):
2799 return self.value <= other.value
2800 if isinstance(other, int) or isinstance(other, int):
2801 return self.value <= other
2802 return NotImplemented
2803 def __gt__(self, other):
2804 if isinstance(other, C):
2805 return self.value > other.value
2806 if isinstance(other, int) or isinstance(other, int):
2807 return self.value > other
2808 return NotImplemented
2809 def __ge__(self, other):
2810 if isinstance(other, C):
2811 return self.value >= other.value
2812 if isinstance(other, int) or isinstance(other, int):
2813 return self.value >= other
2814 return NotImplemented
2815
2816 c1 = C(1)
2817 c2 = C(2)
2818 c3 = C(3)
2819 self.assertEqual(c1, 1)
2820 c = {1: c1, 2: c2, 3: c3}
2821 for x in 1, 2, 3:
2822 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002823 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002824 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002825 eval("x %s y" % op),
2826 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002827 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002828 eval("x %s y" % op),
2829 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002830 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002831 eval("x %s y" % op),
2832 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002833
2834 def test_rich_comparisons(self):
2835 # Testing rich comparisons...
2836 class Z(complex):
2837 pass
2838 z = Z(1)
2839 self.assertEqual(z, 1+0j)
2840 self.assertEqual(1+0j, z)
2841 class ZZ(complex):
2842 def __eq__(self, other):
2843 try:
2844 return abs(self - other) <= 1e-6
2845 except:
2846 return NotImplemented
2847 zz = ZZ(1.0000003)
2848 self.assertEqual(zz, 1+0j)
2849 self.assertEqual(1+0j, zz)
2850
2851 class classic:
2852 pass
2853 for base in (classic, int, object, list):
2854 class C(base):
2855 def __init__(self, value):
2856 self.value = int(value)
2857 def __cmp__(self_, other):
2858 self.fail("shouldn't call __cmp__")
2859 def __eq__(self, other):
2860 if isinstance(other, C):
2861 return self.value == other.value
2862 if isinstance(other, int) or isinstance(other, int):
2863 return self.value == other
2864 return NotImplemented
2865 def __ne__(self, other):
2866 if isinstance(other, C):
2867 return self.value != other.value
2868 if isinstance(other, int) or isinstance(other, int):
2869 return self.value != other
2870 return NotImplemented
2871 def __lt__(self, other):
2872 if isinstance(other, C):
2873 return self.value < other.value
2874 if isinstance(other, int) or isinstance(other, int):
2875 return self.value < other
2876 return NotImplemented
2877 def __le__(self, other):
2878 if isinstance(other, C):
2879 return self.value <= other.value
2880 if isinstance(other, int) or isinstance(other, int):
2881 return self.value <= other
2882 return NotImplemented
2883 def __gt__(self, other):
2884 if isinstance(other, C):
2885 return self.value > other.value
2886 if isinstance(other, int) or isinstance(other, int):
2887 return self.value > other
2888 return NotImplemented
2889 def __ge__(self, other):
2890 if isinstance(other, C):
2891 return self.value >= other.value
2892 if isinstance(other, int) or isinstance(other, int):
2893 return self.value >= other
2894 return NotImplemented
2895 c1 = C(1)
2896 c2 = C(2)
2897 c3 = C(3)
2898 self.assertEqual(c1, 1)
2899 c = {1: c1, 2: c2, 3: c3}
2900 for x in 1, 2, 3:
2901 for y in 1, 2, 3:
2902 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002903 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002904 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002905 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002906 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002907 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 "x=%d, y=%d" % (x, y))
2909
2910 def test_descrdoc(self):
2911 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002912 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002913 def check(descr, what):
2914 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002915 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002916 check(complex.real, "the real part of a complex number") # member descriptor
2917
2918 def test_doc_descriptor(self):
2919 # Testing __doc__ descriptor...
2920 # SF bug 542984
2921 class DocDescr(object):
2922 def __get__(self, object, otype):
2923 if object:
2924 object = object.__class__.__name__ + ' instance'
2925 if otype:
2926 otype = otype.__name__
2927 return 'object=%s; type=%s' % (object, otype)
2928 class OldClass:
2929 __doc__ = DocDescr()
2930 class NewClass(object):
2931 __doc__ = DocDescr()
2932 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2933 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2934 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2935 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2936
2937 def test_set_class(self):
2938 # Testing __class__ assignment...
2939 class C(object): pass
2940 class D(object): pass
2941 class E(object): pass
2942 class F(D, E): pass
2943 for cls in C, D, E, F:
2944 for cls2 in C, D, E, F:
2945 x = cls()
2946 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002947 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002948 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002949 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002950 def cant(x, C):
2951 try:
2952 x.__class__ = C
2953 except TypeError:
2954 pass
2955 else:
2956 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2957 try:
2958 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002959 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002960 pass
2961 else:
2962 self.fail("shouldn't allow del %r.__class__" % x)
2963 cant(C(), list)
2964 cant(list(), C)
2965 cant(C(), 1)
2966 cant(C(), object)
2967 cant(object(), list)
2968 cant(list(), object)
2969 class Int(int): __slots__ = []
2970 cant(2, Int)
2971 cant(Int(), int)
2972 cant(True, int)
2973 cant(2, bool)
2974 o = object()
2975 cant(o, type(1))
2976 cant(o, type(None))
2977 del o
2978 class G(object):
2979 __slots__ = ["a", "b"]
2980 class H(object):
2981 __slots__ = ["b", "a"]
2982 class I(object):
2983 __slots__ = ["a", "b"]
2984 class J(object):
2985 __slots__ = ["c", "b"]
2986 class K(object):
2987 __slots__ = ["a", "b", "d"]
2988 class L(H):
2989 __slots__ = ["e"]
2990 class M(I):
2991 __slots__ = ["e"]
2992 class N(J):
2993 __slots__ = ["__weakref__"]
2994 class P(J):
2995 __slots__ = ["__dict__"]
2996 class Q(J):
2997 pass
2998 class R(J):
2999 __slots__ = ["__dict__", "__weakref__"]
3000
3001 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3002 x = cls()
3003 x.a = 1
3004 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003005 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00003006 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3007 self.assertEqual(x.a, 1)
3008 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003009 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003010 "assigning %r as __class__ for %r silently failed" % (cls, x))
3011 self.assertEqual(x.a, 1)
3012 for cls in G, J, K, L, M, N, P, R, list, Int:
3013 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3014 if cls is cls2:
3015 continue
3016 cant(cls(), cls2)
3017
Benjamin Peterson193152c2009-04-25 01:08:45 +00003018 # Issue5283: when __class__ changes in __del__, the wrong
3019 # type gets DECREF'd.
3020 class O(object):
3021 pass
3022 class A(object):
3023 def __del__(self):
3024 self.__class__ = O
3025 l = [A() for x in range(100)]
3026 del l
3027
Georg Brandl479a7e72008-02-05 18:13:15 +00003028 def test_set_dict(self):
3029 # Testing __dict__ assignment...
3030 class C(object): pass
3031 a = C()
3032 a.__dict__ = {'b': 1}
3033 self.assertEqual(a.b, 1)
3034 def cant(x, dict):
3035 try:
3036 x.__dict__ = dict
3037 except (AttributeError, TypeError):
3038 pass
3039 else:
3040 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3041 cant(a, None)
3042 cant(a, [])
3043 cant(a, 1)
3044 del a.__dict__ # Deleting __dict__ is allowed
3045
3046 class Base(object):
3047 pass
3048 def verify_dict_readonly(x):
3049 """
3050 x has to be an instance of a class inheriting from Base.
3051 """
3052 cant(x, {})
3053 try:
3054 del x.__dict__
3055 except (AttributeError, TypeError):
3056 pass
3057 else:
3058 self.fail("shouldn't allow del %r.__dict__" % x)
3059 dict_descr = Base.__dict__["__dict__"]
3060 try:
3061 dict_descr.__set__(x, {})
3062 except (AttributeError, TypeError):
3063 pass
3064 else:
3065 self.fail("dict_descr allowed access to %r's dict" % x)
3066
3067 # Classes don't allow __dict__ assignment and have readonly dicts
3068 class Meta1(type, Base):
3069 pass
3070 class Meta2(Base, type):
3071 pass
3072 class D(object, metaclass=Meta1):
3073 pass
3074 class E(object, metaclass=Meta2):
3075 pass
3076 for cls in C, D, E:
3077 verify_dict_readonly(cls)
3078 class_dict = cls.__dict__
3079 try:
3080 class_dict["spam"] = "eggs"
3081 except TypeError:
3082 pass
3083 else:
3084 self.fail("%r's __dict__ can be modified" % cls)
3085
3086 # Modules also disallow __dict__ assignment
3087 class Module1(types.ModuleType, Base):
3088 pass
3089 class Module2(Base, types.ModuleType):
3090 pass
3091 for ModuleType in Module1, Module2:
3092 mod = ModuleType("spam")
3093 verify_dict_readonly(mod)
3094 mod.__dict__["spam"] = "eggs"
3095
3096 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003097 # (at least not any more than regular exception's __dict__ can
3098 # be deleted; on CPython it is not the case, whereas on PyPy they
3099 # can, just like any other new-style instance's __dict__.)
3100 def can_delete_dict(e):
3101 try:
3102 del e.__dict__
3103 except (TypeError, AttributeError):
3104 return False
3105 else:
3106 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003107 class Exception1(Exception, Base):
3108 pass
3109 class Exception2(Base, Exception):
3110 pass
3111 for ExceptionType in Exception, Exception1, Exception2:
3112 e = ExceptionType()
3113 e.__dict__ = {"a": 1}
3114 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003115 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003116
3117 def test_pickles(self):
3118 # Testing pickling and copying new-style classes and objects...
3119 import pickle
3120
3121 def sorteditems(d):
3122 L = list(d.items())
3123 L.sort()
3124 return L
3125
3126 global C
3127 class C(object):
3128 def __init__(self, a, b):
3129 super(C, self).__init__()
3130 self.a = a
3131 self.b = b
3132 def __repr__(self):
3133 return "C(%r, %r)" % (self.a, self.b)
3134
3135 global C1
3136 class C1(list):
3137 def __new__(cls, a, b):
3138 return super(C1, cls).__new__(cls)
3139 def __getnewargs__(self):
3140 return (self.a, self.b)
3141 def __init__(self, a, b):
3142 self.a = a
3143 self.b = b
3144 def __repr__(self):
3145 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3146
3147 global C2
3148 class C2(int):
3149 def __new__(cls, a, b, val=0):
3150 return super(C2, cls).__new__(cls, val)
3151 def __getnewargs__(self):
3152 return (self.a, self.b, int(self))
3153 def __init__(self, a, b, val=0):
3154 self.a = a
3155 self.b = b
3156 def __repr__(self):
3157 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3158
3159 global C3
3160 class C3(object):
3161 def __init__(self, foo):
3162 self.foo = foo
3163 def __getstate__(self):
3164 return self.foo
3165 def __setstate__(self, foo):
3166 self.foo = foo
3167
3168 global C4classic, C4
3169 class C4classic: # classic
3170 pass
3171 class C4(C4classic, object): # mixed inheritance
3172 pass
3173
Guido van Rossum3926a632001-09-25 16:25:58 +00003174 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003175 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003176 s = pickle.dumps(cls, bin)
3177 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003178 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003179
3180 a = C1(1, 2); a.append(42); a.append(24)
3181 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003182 s = pickle.dumps((a, b), bin)
3183 x, y = pickle.loads(s)
3184 self.assertEqual(x.__class__, a.__class__)
3185 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3186 self.assertEqual(y.__class__, b.__class__)
3187 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3188 self.assertEqual(repr(x), repr(a))
3189 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003190 # Test for __getstate__ and __setstate__ on new style class
3191 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003192 s = pickle.dumps(u, bin)
3193 v = pickle.loads(s)
3194 self.assertEqual(u.__class__, v.__class__)
3195 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003196 # Test for picklability of hybrid class
3197 u = C4()
3198 u.foo = 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 Rossum3926a632001-09-25 16:25:58 +00003203
Georg Brandl479a7e72008-02-05 18:13:15 +00003204 # Testing copy.deepcopy()
3205 import copy
3206 for cls in C, C1, C2:
3207 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003208 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003209
Georg Brandl479a7e72008-02-05 18:13:15 +00003210 a = C1(1, 2); a.append(42); a.append(24)
3211 b = C2("hello", "world", 42)
3212 x, y = copy.deepcopy((a, b))
3213 self.assertEqual(x.__class__, a.__class__)
3214 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3215 self.assertEqual(y.__class__, b.__class__)
3216 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3217 self.assertEqual(repr(x), repr(a))
3218 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003219
Georg Brandl479a7e72008-02-05 18:13:15 +00003220 def test_pickle_slots(self):
3221 # Testing pickling of classes with __slots__ ...
3222 import pickle
3223 # Pickling of classes with __slots__ but without __getstate__ should fail
3224 # (if using protocol 0 or 1)
3225 global B, C, D, E
3226 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003227 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003228 for base in [object, B]:
3229 class C(base):
3230 __slots__ = ['a']
3231 class D(C):
3232 pass
3233 try:
3234 pickle.dumps(C(), 0)
3235 except TypeError:
3236 pass
3237 else:
3238 self.fail("should fail: pickle C instance - %s" % base)
3239 try:
3240 pickle.dumps(C(), 0)
3241 except TypeError:
3242 pass
3243 else:
3244 self.fail("should fail: pickle D instance - %s" % base)
3245 # Give C a nice generic __getstate__ and __setstate__
3246 class C(base):
3247 __slots__ = ['a']
3248 def __getstate__(self):
3249 try:
3250 d = self.__dict__.copy()
3251 except AttributeError:
3252 d = {}
3253 for cls in self.__class__.__mro__:
3254 for sn in cls.__dict__.get('__slots__', ()):
3255 try:
3256 d[sn] = getattr(self, sn)
3257 except AttributeError:
3258 pass
3259 return d
3260 def __setstate__(self, d):
3261 for k, v in list(d.items()):
3262 setattr(self, k, v)
3263 class D(C):
3264 pass
3265 # Now it should work
3266 x = C()
3267 y = pickle.loads(pickle.dumps(x))
3268 self.assertEqual(hasattr(y, 'a'), 0)
3269 x.a = 42
3270 y = pickle.loads(pickle.dumps(x))
3271 self.assertEqual(y.a, 42)
3272 x = D()
3273 x.a = 42
3274 x.b = 100
3275 y = pickle.loads(pickle.dumps(x))
3276 self.assertEqual(y.a + y.b, 142)
3277 # A subclass that adds a slot should also work
3278 class E(C):
3279 __slots__ = ['b']
3280 x = E()
3281 x.a = 42
3282 x.b = "foo"
3283 y = pickle.loads(pickle.dumps(x))
3284 self.assertEqual(y.a, x.a)
3285 self.assertEqual(y.b, x.b)
3286
3287 def test_binary_operator_override(self):
3288 # Testing overrides of binary operations...
3289 class I(int):
3290 def __repr__(self):
3291 return "I(%r)" % int(self)
3292 def __add__(self, other):
3293 return I(int(self) + int(other))
3294 __radd__ = __add__
3295 def __pow__(self, other, mod=None):
3296 if mod is None:
3297 return I(pow(int(self), int(other)))
3298 else:
3299 return I(pow(int(self), int(other), int(mod)))
3300 def __rpow__(self, other, mod=None):
3301 if mod is None:
3302 return I(pow(int(other), int(self), mod))
3303 else:
3304 return I(pow(int(other), int(self), int(mod)))
3305
3306 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3307 self.assertEqual(repr(I(1) + 2), "I(3)")
3308 self.assertEqual(repr(1 + I(2)), "I(3)")
3309 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3310 self.assertEqual(repr(2 ** I(3)), "I(8)")
3311 self.assertEqual(repr(I(2) ** 3), "I(8)")
3312 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3313 class S(str):
3314 def __eq__(self, other):
3315 return self.lower() == other.lower()
3316
3317 def test_subclass_propagation(self):
3318 # Testing propagation of slot functions to subclasses...
3319 class A(object):
3320 pass
3321 class B(A):
3322 pass
3323 class C(A):
3324 pass
3325 class D(B, C):
3326 pass
3327 d = D()
3328 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3329 A.__hash__ = lambda self: 42
3330 self.assertEqual(hash(d), 42)
3331 C.__hash__ = lambda self: 314
3332 self.assertEqual(hash(d), 314)
3333 B.__hash__ = lambda self: 144
3334 self.assertEqual(hash(d), 144)
3335 D.__hash__ = lambda self: 100
3336 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003337 D.__hash__ = None
3338 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003339 del D.__hash__
3340 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003341 B.__hash__ = None
3342 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003343 del B.__hash__
3344 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003345 C.__hash__ = None
3346 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003347 del C.__hash__
3348 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003349 A.__hash__ = None
3350 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003351 del A.__hash__
3352 self.assertEqual(hash(d), orig_hash)
3353 d.foo = 42
3354 d.bar = 42
3355 self.assertEqual(d.foo, 42)
3356 self.assertEqual(d.bar, 42)
3357 def __getattribute__(self, name):
3358 if name == "foo":
3359 return 24
3360 return object.__getattribute__(self, name)
3361 A.__getattribute__ = __getattribute__
3362 self.assertEqual(d.foo, 24)
3363 self.assertEqual(d.bar, 42)
3364 def __getattr__(self, name):
3365 if name in ("spam", "foo", "bar"):
3366 return "hello"
3367 raise AttributeError(name)
3368 B.__getattr__ = __getattr__
3369 self.assertEqual(d.spam, "hello")
3370 self.assertEqual(d.foo, 24)
3371 self.assertEqual(d.bar, 42)
3372 del A.__getattribute__
3373 self.assertEqual(d.foo, 42)
3374 del d.foo
3375 self.assertEqual(d.foo, "hello")
3376 self.assertEqual(d.bar, 42)
3377 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003378 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003379 d.foo
3380 except AttributeError:
3381 pass
3382 else:
3383 self.fail("d.foo should be undefined now")
3384
3385 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003386 class A(object):
3387 pass
3388 class B(A):
3389 pass
3390 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003391 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003392 A.__setitem__ = lambda *a: None # crash
3393
3394 def test_buffer_inheritance(self):
3395 # Testing that buffer interface is inherited ...
3396
3397 import binascii
3398 # SF bug [#470040] ParseTuple t# vs subclasses.
3399
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003400 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003401 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003402 base = b'abc'
3403 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003404 # b2a_hex uses the buffer interface to get its argument's value, via
3405 # PyArg_ParseTuple 't#' code.
3406 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3407
Georg Brandl479a7e72008-02-05 18:13:15 +00003408 class MyInt(int):
3409 pass
3410 m = MyInt(42)
3411 try:
3412 binascii.b2a_hex(m)
3413 self.fail('subclass of int should not have a buffer interface')
3414 except TypeError:
3415 pass
3416
3417 def test_str_of_str_subclass(self):
3418 # Testing __str__ defined in subclass of str ...
3419 import binascii
3420 import io
3421
3422 class octetstring(str):
3423 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003424 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003425 def __repr__(self):
3426 return self + " repr"
3427
3428 o = octetstring('A')
3429 self.assertEqual(type(o), octetstring)
3430 self.assertEqual(type(str(o)), str)
3431 self.assertEqual(type(repr(o)), str)
3432 self.assertEqual(ord(o), 0x41)
3433 self.assertEqual(str(o), '41')
3434 self.assertEqual(repr(o), 'A repr')
3435 self.assertEqual(o.__str__(), '41')
3436 self.assertEqual(o.__repr__(), 'A repr')
3437
3438 capture = io.StringIO()
3439 # Calling str() or not exercises different internal paths.
3440 print(o, file=capture)
3441 print(str(o), file=capture)
3442 self.assertEqual(capture.getvalue(), '41\n41\n')
3443 capture.close()
3444
3445 def test_keyword_arguments(self):
3446 # Testing keyword arguments to __init__, __call__...
3447 def f(a): return a
3448 self.assertEqual(f.__call__(a=42), 42)
3449 a = []
3450 list.__init__(a, sequence=[0, 1, 2])
3451 self.assertEqual(a, [0, 1, 2])
3452
3453 def test_recursive_call(self):
3454 # Testing recursive __call__() by setting to instance of class...
3455 class A(object):
3456 pass
3457
3458 A.__call__ = A()
3459 try:
3460 A()()
3461 except RuntimeError:
3462 pass
3463 else:
3464 self.fail("Recursion limit should have been reached for __call__()")
3465
3466 def test_delete_hook(self):
3467 # Testing __del__ hook...
3468 log = []
3469 class C(object):
3470 def __del__(self):
3471 log.append(1)
3472 c = C()
3473 self.assertEqual(log, [])
3474 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003475 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003476 self.assertEqual(log, [1])
3477
3478 class D(object): pass
3479 d = D()
3480 try: del d[0]
3481 except TypeError: pass
3482 else: self.fail("invalid del() didn't raise TypeError")
3483
3484 def test_hash_inheritance(self):
3485 # Testing hash of mutable subclasses...
3486
3487 class mydict(dict):
3488 pass
3489 d = mydict()
3490 try:
3491 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003492 except TypeError:
3493 pass
3494 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003495 self.fail("hash() of dict subclass should fail")
3496
3497 class mylist(list):
3498 pass
3499 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003500 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003501 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003502 except TypeError:
3503 pass
3504 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003505 self.fail("hash() of list subclass should fail")
3506
3507 def test_str_operations(self):
3508 try: 'a' + 5
3509 except TypeError: pass
3510 else: self.fail("'' + 5 doesn't raise TypeError")
3511
3512 try: ''.split('')
3513 except ValueError: pass
3514 else: self.fail("''.split('') doesn't raise ValueError")
3515
3516 try: ''.join([0])
3517 except TypeError: pass
3518 else: self.fail("''.join([0]) doesn't raise TypeError")
3519
3520 try: ''.rindex('5')
3521 except ValueError: pass
3522 else: self.fail("''.rindex('5') doesn't raise ValueError")
3523
3524 try: '%(n)s' % None
3525 except TypeError: pass
3526 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3527
3528 try: '%(n' % {}
3529 except ValueError: pass
3530 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3531
3532 try: '%*s' % ('abc')
3533 except TypeError: pass
3534 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3535
3536 try: '%*.*s' % ('abc', 5)
3537 except TypeError: pass
3538 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3539
3540 try: '%s' % (1, 2)
3541 except TypeError: pass
3542 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3543
3544 try: '%' % None
3545 except ValueError: pass
3546 else: self.fail("'%' % None doesn't raise ValueError")
3547
3548 self.assertEqual('534253'.isdigit(), 1)
3549 self.assertEqual('534253x'.isdigit(), 0)
3550 self.assertEqual('%c' % 5, '\x05')
3551 self.assertEqual('%c' % '5', '5')
3552
3553 def test_deepcopy_recursive(self):
3554 # Testing deepcopy of recursive objects...
3555 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003556 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003557 a = Node()
3558 b = Node()
3559 a.b = b
3560 b.a = a
3561 z = deepcopy(a) # This blew up before
3562
3563 def test_unintialized_modules(self):
3564 # Testing uninitialized module objects...
3565 from types import ModuleType as M
3566 m = M.__new__(M)
3567 str(m)
3568 self.assertEqual(hasattr(m, "__name__"), 0)
3569 self.assertEqual(hasattr(m, "__file__"), 0)
3570 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003571 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003572 m.foo = 1
3573 self.assertEqual(m.__dict__, {"foo": 1})
3574
3575 def test_funny_new(self):
3576 # Testing __new__ returning something unexpected...
3577 class C(object):
3578 def __new__(cls, arg):
3579 if isinstance(arg, str): return [1, 2, 3]
3580 elif isinstance(arg, int): return object.__new__(D)
3581 else: return object.__new__(cls)
3582 class D(C):
3583 def __init__(self, arg):
3584 self.foo = arg
3585 self.assertEqual(C("1"), [1, 2, 3])
3586 self.assertEqual(D("1"), [1, 2, 3])
3587 d = D(None)
3588 self.assertEqual(d.foo, None)
3589 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003590 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003591 self.assertEqual(d.foo, 1)
3592 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003593 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003594 self.assertEqual(d.foo, 1)
3595
3596 def test_imul_bug(self):
3597 # Testing for __imul__ problems...
3598 # SF bug 544647
3599 class C(object):
3600 def __imul__(self, other):
3601 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003602 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003603 y = x
3604 y *= 1.0
3605 self.assertEqual(y, (x, 1.0))
3606 y = x
3607 y *= 2
3608 self.assertEqual(y, (x, 2))
3609 y = x
3610 y *= 3
3611 self.assertEqual(y, (x, 3))
3612 y = x
3613 y *= 1<<100
3614 self.assertEqual(y, (x, 1<<100))
3615 y = x
3616 y *= None
3617 self.assertEqual(y, (x, None))
3618 y = x
3619 y *= "foo"
3620 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003621
Georg Brandl479a7e72008-02-05 18:13:15 +00003622 def test_copy_setstate(self):
3623 # Testing that copy.*copy() correctly uses __setstate__...
3624 import copy
3625 class C(object):
3626 def __init__(self, foo=None):
3627 self.foo = foo
3628 self.__foo = foo
3629 def setfoo(self, foo=None):
3630 self.foo = foo
3631 def getfoo(self):
3632 return self.__foo
3633 def __getstate__(self):
3634 return [self.foo]
3635 def __setstate__(self_, lst):
3636 self.assertEqual(len(lst), 1)
3637 self_.__foo = self_.foo = lst[0]
3638 a = C(42)
3639 a.setfoo(24)
3640 self.assertEqual(a.foo, 24)
3641 self.assertEqual(a.getfoo(), 42)
3642 b = copy.copy(a)
3643 self.assertEqual(b.foo, 24)
3644 self.assertEqual(b.getfoo(), 24)
3645 b = copy.deepcopy(a)
3646 self.assertEqual(b.foo, 24)
3647 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003648
Georg Brandl479a7e72008-02-05 18:13:15 +00003649 def test_slices(self):
3650 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003651
Georg Brandl479a7e72008-02-05 18:13:15 +00003652 # Strings
3653 self.assertEqual("hello"[:4], "hell")
3654 self.assertEqual("hello"[slice(4)], "hell")
3655 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3656 class S(str):
3657 def __getitem__(self, x):
3658 return str.__getitem__(self, x)
3659 self.assertEqual(S("hello")[:4], "hell")
3660 self.assertEqual(S("hello")[slice(4)], "hell")
3661 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3662 # Tuples
3663 self.assertEqual((1,2,3)[:2], (1,2))
3664 self.assertEqual((1,2,3)[slice(2)], (1,2))
3665 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3666 class T(tuple):
3667 def __getitem__(self, x):
3668 return tuple.__getitem__(self, x)
3669 self.assertEqual(T((1,2,3))[:2], (1,2))
3670 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3671 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3672 # Lists
3673 self.assertEqual([1,2,3][:2], [1,2])
3674 self.assertEqual([1,2,3][slice(2)], [1,2])
3675 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3676 class L(list):
3677 def __getitem__(self, x):
3678 return list.__getitem__(self, x)
3679 self.assertEqual(L([1,2,3])[:2], [1,2])
3680 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3681 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3682 # Now do lists and __setitem__
3683 a = L([1,2,3])
3684 a[slice(1, 3)] = [3,2]
3685 self.assertEqual(a, [1,3,2])
3686 a[slice(0, 2, 1)] = [3,1]
3687 self.assertEqual(a, [3,1,2])
3688 a.__setitem__(slice(1, 3), [2,1])
3689 self.assertEqual(a, [3,2,1])
3690 a.__setitem__(slice(0, 2, 1), [2,3])
3691 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003692
Georg Brandl479a7e72008-02-05 18:13:15 +00003693 def test_subtype_resurrection(self):
3694 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003695
Georg Brandl479a7e72008-02-05 18:13:15 +00003696 class C(object):
3697 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003698
Georg Brandl479a7e72008-02-05 18:13:15 +00003699 def __del__(self):
3700 # resurrect the instance
3701 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003702
Georg Brandl479a7e72008-02-05 18:13:15 +00003703 c = C()
3704 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003705
Benjamin Petersone549ead2009-03-28 21:42:05 +00003706 # The most interesting thing here is whether this blows up, due to
3707 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3708 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003709 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003710
Georg Brandl479a7e72008-02-05 18:13:15 +00003711 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003712 # the last container slot works: that will attempt to delete c again,
3713 # which will cause c to get appended back to the container again
3714 # "during" the del. (On non-CPython implementations, however, __del__
3715 # is typically not called again.)
3716 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003717 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003718 del C.container[-1]
3719 if support.check_impl_detail():
3720 support.gc_collect()
3721 self.assertEqual(len(C.container), 1)
3722 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003723
Georg Brandl479a7e72008-02-05 18:13:15 +00003724 # Make c mortal again, so that the test framework with -l doesn't report
3725 # it as a leak.
3726 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003727
Georg Brandl479a7e72008-02-05 18:13:15 +00003728 def test_slots_trash(self):
3729 # Testing slot trash...
3730 # Deallocating deeply nested slotted trash caused stack overflows
3731 class trash(object):
3732 __slots__ = ['x']
3733 def __init__(self, x):
3734 self.x = x
3735 o = None
3736 for i in range(50000):
3737 o = trash(o)
3738 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003739
Georg Brandl479a7e72008-02-05 18:13:15 +00003740 def test_slots_multiple_inheritance(self):
3741 # SF bug 575229, multiple inheritance w/ slots dumps core
3742 class A(object):
3743 __slots__=()
3744 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003745 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003746 class C(A,B) :
3747 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003748 if support.check_impl_detail():
3749 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003750 self.assertTrue(hasattr(C, '__dict__'))
3751 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003752 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003753
Georg Brandl479a7e72008-02-05 18:13:15 +00003754 def test_rmul(self):
3755 # Testing correct invocation of __rmul__...
3756 # SF patch 592646
3757 class C(object):
3758 def __mul__(self, other):
3759 return "mul"
3760 def __rmul__(self, other):
3761 return "rmul"
3762 a = C()
3763 self.assertEqual(a*2, "mul")
3764 self.assertEqual(a*2.2, "mul")
3765 self.assertEqual(2*a, "rmul")
3766 self.assertEqual(2.2*a, "rmul")
3767
3768 def test_ipow(self):
3769 # Testing correct invocation of __ipow__...
3770 # [SF bug 620179]
3771 class C(object):
3772 def __ipow__(self, other):
3773 pass
3774 a = C()
3775 a **= 2
3776
3777 def test_mutable_bases(self):
3778 # Testing mutable bases...
3779
3780 # stuff that should work:
3781 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003782 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 class C2(object):
3784 def __getattribute__(self, attr):
3785 if attr == 'a':
3786 return 2
3787 else:
3788 return super(C2, self).__getattribute__(attr)
3789 def meth(self):
3790 return 1
3791 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003792 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003793 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003794 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003795 d = D()
3796 e = E()
3797 D.__bases__ = (C,)
3798 D.__bases__ = (C2,)
3799 self.assertEqual(d.meth(), 1)
3800 self.assertEqual(e.meth(), 1)
3801 self.assertEqual(d.a, 2)
3802 self.assertEqual(e.a, 2)
3803 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003804
Georg Brandl479a7e72008-02-05 18:13:15 +00003805 try:
3806 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003807 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003808 pass
3809 else:
3810 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003811
Georg Brandl479a7e72008-02-05 18:13:15 +00003812 try:
3813 D.__bases__ = ()
3814 except TypeError as msg:
3815 if str(msg) == "a new-style class can't have only classic bases":
3816 self.fail("wrong error message for .__bases__ = ()")
3817 else:
3818 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003819
Georg Brandl479a7e72008-02-05 18:13:15 +00003820 try:
3821 D.__bases__ = (D,)
3822 except TypeError:
3823 pass
3824 else:
3825 # actually, we'll have crashed by here...
3826 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003827
Georg Brandl479a7e72008-02-05 18:13:15 +00003828 try:
3829 D.__bases__ = (C, C)
3830 except TypeError:
3831 pass
3832 else:
3833 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003834
Georg Brandl479a7e72008-02-05 18:13:15 +00003835 try:
3836 D.__bases__ = (E,)
3837 except TypeError:
3838 pass
3839 else:
3840 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003841
Benjamin Petersonae937c02009-04-18 20:54:08 +00003842 def test_builtin_bases(self):
3843 # Make sure all the builtin types can have their base queried without
3844 # segfaulting. See issue #5787.
3845 builtin_types = [tp for tp in builtins.__dict__.values()
3846 if isinstance(tp, type)]
3847 for tp in builtin_types:
3848 object.__getattribute__(tp, "__bases__")
3849 if tp is not object:
3850 self.assertEqual(len(tp.__bases__), 1, tp)
3851
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003852 class L(list):
3853 pass
3854
3855 class C(object):
3856 pass
3857
3858 class D(C):
3859 pass
3860
3861 try:
3862 L.__bases__ = (dict,)
3863 except TypeError:
3864 pass
3865 else:
3866 self.fail("shouldn't turn list subclass into dict subclass")
3867
3868 try:
3869 list.__bases__ = (dict,)
3870 except TypeError:
3871 pass
3872 else:
3873 self.fail("shouldn't be able to assign to list.__bases__")
3874
3875 try:
3876 D.__bases__ = (C, list)
3877 except TypeError:
3878 pass
3879 else:
3880 assert 0, "best_base calculation found wanting"
3881
Benjamin Petersonae937c02009-04-18 20:54:08 +00003882
Georg Brandl479a7e72008-02-05 18:13:15 +00003883 def test_mutable_bases_with_failing_mro(self):
3884 # Testing mutable bases with failing mro...
3885 class WorkOnce(type):
3886 def __new__(self, name, bases, ns):
3887 self.flag = 0
3888 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3889 def mro(self):
3890 if self.flag > 0:
3891 raise RuntimeError("bozo")
3892 else:
3893 self.flag += 1
3894 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003895
Georg Brandl479a7e72008-02-05 18:13:15 +00003896 class WorkAlways(type):
3897 def mro(self):
3898 # this is here to make sure that .mro()s aren't called
3899 # with an exception set (which was possible at one point).
3900 # An error message will be printed in a debug build.
3901 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003902 return type.mro(self)
3903
Georg Brandl479a7e72008-02-05 18:13:15 +00003904 class C(object):
3905 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003906
Georg Brandl479a7e72008-02-05 18:13:15 +00003907 class C2(object):
3908 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003909
Georg Brandl479a7e72008-02-05 18:13:15 +00003910 class D(C):
3911 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003912
Georg Brandl479a7e72008-02-05 18:13:15 +00003913 class E(D):
3914 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003915
Georg Brandl479a7e72008-02-05 18:13:15 +00003916 class F(D, metaclass=WorkOnce):
3917 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003918
Georg Brandl479a7e72008-02-05 18:13:15 +00003919 class G(D, metaclass=WorkAlways):
3920 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003921
Georg Brandl479a7e72008-02-05 18:13:15 +00003922 # Immediate subclasses have their mro's adjusted in alphabetical
3923 # order, so E's will get adjusted before adjusting F's fails. We
3924 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003925
Georg Brandl479a7e72008-02-05 18:13:15 +00003926 E_mro_before = E.__mro__
3927 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003928
Armin Rigofd163f92005-12-29 15:59:19 +00003929 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003930 D.__bases__ = (C2,)
3931 except RuntimeError:
3932 self.assertEqual(E.__mro__, E_mro_before)
3933 self.assertEqual(D.__mro__, D_mro_before)
3934 else:
3935 self.fail("exception not propagated")
3936
3937 def test_mutable_bases_catch_mro_conflict(self):
3938 # Testing mutable bases catch mro conflict...
3939 class A(object):
3940 pass
3941
3942 class B(object):
3943 pass
3944
3945 class C(A, B):
3946 pass
3947
3948 class D(A, B):
3949 pass
3950
3951 class E(C, D):
3952 pass
3953
3954 try:
3955 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003956 except TypeError:
3957 pass
3958 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003959 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003960
Georg Brandl479a7e72008-02-05 18:13:15 +00003961 def test_mutable_names(self):
3962 # Testing mutable names...
3963 class C(object):
3964 pass
3965
3966 # C.__module__ could be 'test_descr' or '__main__'
3967 mod = C.__module__
3968
3969 C.__name__ = 'D'
3970 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3971
3972 C.__name__ = 'D.E'
3973 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3974
3975 def test_subclass_right_op(self):
3976 # Testing correct dispatch of subclass overloading __r<op>__...
3977
3978 # This code tests various cases where right-dispatch of a subclass
3979 # should be preferred over left-dispatch of a base class.
3980
3981 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3982
3983 class B(int):
3984 def __floordiv__(self, other):
3985 return "B.__floordiv__"
3986 def __rfloordiv__(self, other):
3987 return "B.__rfloordiv__"
3988
3989 self.assertEqual(B(1) // 1, "B.__floordiv__")
3990 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3991
3992 # Case 2: subclass of object; this is just the baseline for case 3
3993
3994 class C(object):
3995 def __floordiv__(self, other):
3996 return "C.__floordiv__"
3997 def __rfloordiv__(self, other):
3998 return "C.__rfloordiv__"
3999
4000 self.assertEqual(C() // 1, "C.__floordiv__")
4001 self.assertEqual(1 // C(), "C.__rfloordiv__")
4002
4003 # Case 3: subclass of new-style class; here it gets interesting
4004
4005 class D(C):
4006 def __floordiv__(self, other):
4007 return "D.__floordiv__"
4008 def __rfloordiv__(self, other):
4009 return "D.__rfloordiv__"
4010
4011 self.assertEqual(D() // C(), "D.__floordiv__")
4012 self.assertEqual(C() // D(), "D.__rfloordiv__")
4013
4014 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4015
4016 class E(C):
4017 pass
4018
4019 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4020
4021 self.assertEqual(E() // 1, "C.__floordiv__")
4022 self.assertEqual(1 // E(), "C.__rfloordiv__")
4023 self.assertEqual(E() // C(), "C.__floordiv__")
4024 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4025
Benjamin Petersone549ead2009-03-28 21:42:05 +00004026 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004027 def test_meth_class_get(self):
4028 # Testing __get__ method of METH_CLASS C methods...
4029 # Full coverage of descrobject.c::classmethod_get()
4030
4031 # Baseline
4032 arg = [1, 2, 3]
4033 res = {1: None, 2: None, 3: None}
4034 self.assertEqual(dict.fromkeys(arg), res)
4035 self.assertEqual({}.fromkeys(arg), res)
4036
4037 # Now get the descriptor
4038 descr = dict.__dict__["fromkeys"]
4039
4040 # More baseline using the descriptor directly
4041 self.assertEqual(descr.__get__(None, dict)(arg), res)
4042 self.assertEqual(descr.__get__({})(arg), res)
4043
4044 # Now check various error cases
4045 try:
4046 descr.__get__(None, None)
4047 except TypeError:
4048 pass
4049 else:
4050 self.fail("shouldn't have allowed descr.__get__(None, None)")
4051 try:
4052 descr.__get__(42)
4053 except TypeError:
4054 pass
4055 else:
4056 self.fail("shouldn't have allowed descr.__get__(42)")
4057 try:
4058 descr.__get__(None, 42)
4059 except TypeError:
4060 pass
4061 else:
4062 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4063 try:
4064 descr.__get__(None, int)
4065 except TypeError:
4066 pass
4067 else:
4068 self.fail("shouldn't have allowed descr.__get__(None, int)")
4069
4070 def test_isinst_isclass(self):
4071 # Testing proxy isinstance() and isclass()...
4072 class Proxy(object):
4073 def __init__(self, obj):
4074 self.__obj = obj
4075 def __getattribute__(self, name):
4076 if name.startswith("_Proxy__"):
4077 return object.__getattribute__(self, name)
4078 else:
4079 return getattr(self.__obj, name)
4080 # Test with a classic class
4081 class C:
4082 pass
4083 a = C()
4084 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004085 self.assertIsInstance(a, C) # Baseline
4086 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004087 # Test with a classic subclass
4088 class D(C):
4089 pass
4090 a = D()
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 new-style class
4095 class C(object):
4096 pass
4097 a = C()
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 subclass
4102 class D(C):
4103 pass
4104 a = D()
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
4109 def test_proxy_super(self):
4110 # Testing super() for a proxy object...
4111 class Proxy(object):
4112 def __init__(self, obj):
4113 self.__obj = obj
4114 def __getattribute__(self, name):
4115 if name.startswith("_Proxy__"):
4116 return object.__getattribute__(self, name)
4117 else:
4118 return getattr(self.__obj, name)
4119
4120 class B(object):
4121 def f(self):
4122 return "B.f"
4123
4124 class C(B):
4125 def f(self):
4126 return super(C, self).f() + "->C.f"
4127
4128 obj = C()
4129 p = Proxy(obj)
4130 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4131
4132 def test_carloverre(self):
4133 # Testing prohibition of Carlo Verre's hack...
4134 try:
4135 object.__setattr__(str, "foo", 42)
4136 except TypeError:
4137 pass
4138 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004139 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004140 try:
4141 object.__delattr__(str, "lower")
4142 except TypeError:
4143 pass
4144 else:
4145 self.fail("Carlo Verre __delattr__ succeeded!")
4146
4147 def test_weakref_segfault(self):
4148 # Testing weakref segfault...
4149 # SF 742911
4150 import weakref
4151
4152 class Provoker:
4153 def __init__(self, referrent):
4154 self.ref = weakref.ref(referrent)
4155
4156 def __del__(self):
4157 x = self.ref()
4158
4159 class Oops(object):
4160 pass
4161
4162 o = Oops()
4163 o.whatever = Provoker(o)
4164 del o
4165
4166 def test_wrapper_segfault(self):
4167 # SF 927248: deeply nested wrappers could cause stack overflow
4168 f = lambda:None
4169 for i in range(1000000):
4170 f = f.__call__
4171 f = None
4172
4173 def test_file_fault(self):
4174 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004175 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004176 class StdoutGuard:
4177 def __getattr__(self, attr):
4178 sys.stdout = sys.__stdout__
4179 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4180 sys.stdout = StdoutGuard()
4181 try:
4182 print("Oops!")
4183 except RuntimeError:
4184 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004185 finally:
4186 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004187
4188 def test_vicious_descriptor_nonsense(self):
4189 # Testing vicious_descriptor_nonsense...
4190
4191 # A potential segfault spotted by Thomas Wouters in mail to
4192 # python-dev 2003-04-17, turned into an example & fixed by Michael
4193 # Hudson just less than four months later...
4194
4195 class Evil(object):
4196 def __hash__(self):
4197 return hash('attr')
4198 def __eq__(self, other):
4199 del C.attr
4200 return 0
4201
4202 class Descr(object):
4203 def __get__(self, ob, type=None):
4204 return 1
4205
4206 class C(object):
4207 attr = Descr()
4208
4209 c = C()
4210 c.__dict__[Evil()] = 0
4211
4212 self.assertEqual(c.attr, 1)
4213 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004214 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004215 self.assertEqual(hasattr(c, 'attr'), False)
4216
4217 def test_init(self):
4218 # SF 1155938
4219 class Foo(object):
4220 def __init__(self):
4221 return 10
4222 try:
4223 Foo()
4224 except TypeError:
4225 pass
4226 else:
4227 self.fail("did not test __init__() for None return")
4228
4229 def test_method_wrapper(self):
4230 # Testing method-wrapper objects...
4231 # <type 'method-wrapper'> did not support any reflection before 2.5
4232
Mark Dickinson211c6252009-02-01 10:28:51 +00004233 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004234
4235 l = []
4236 self.assertEqual(l.__add__, l.__add__)
4237 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004238 self.assertTrue(l.__add__ != [5].__add__)
4239 self.assertTrue(l.__add__ != l.__mul__)
4240 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004241 if hasattr(l.__add__, '__self__'):
4242 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004243 self.assertTrue(l.__add__.__self__ is l)
4244 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004245 else:
4246 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004247 self.assertTrue(l.__add__.im_self is l)
4248 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004249 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4250 try:
4251 hash(l.__add__)
4252 except TypeError:
4253 pass
4254 else:
4255 self.fail("no TypeError from hash([].__add__)")
4256
4257 t = ()
4258 t += (7,)
4259 self.assertEqual(t.__add__, (7,).__add__)
4260 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4261
4262 def test_not_implemented(self):
4263 # Testing NotImplemented...
4264 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004265 import operator
4266
4267 def specialmethod(self, other):
4268 return NotImplemented
4269
4270 def check(expr, x, y):
4271 try:
4272 exec(expr, {'x': x, 'y': y, 'operator': operator})
4273 except TypeError:
4274 pass
4275 else:
4276 self.fail("no TypeError from %r" % (expr,))
4277
4278 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4279 # TypeErrors
4280 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4281 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004282 for name, expr, iexpr in [
4283 ('__add__', 'x + y', 'x += y'),
4284 ('__sub__', 'x - y', 'x -= y'),
4285 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004286 ('__truediv__', 'operator.truediv(x, y)', None),
4287 ('__floordiv__', 'operator.floordiv(x, y)', None),
4288 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004289 ('__mod__', 'x % y', 'x %= y'),
4290 ('__divmod__', 'divmod(x, y)', None),
4291 ('__pow__', 'x ** y', 'x **= y'),
4292 ('__lshift__', 'x << y', 'x <<= y'),
4293 ('__rshift__', 'x >> y', 'x >>= y'),
4294 ('__and__', 'x & y', 'x &= y'),
4295 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004296 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004297 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004298 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004299 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004300 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004301 check(expr, a, N1)
4302 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004303 if iexpr:
4304 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004305 check(iexpr, a, N1)
4306 check(iexpr, a, N2)
4307 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004308 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004309 c = C()
4310 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004311 check(iexpr, c, N1)
4312 check(iexpr, c, N2)
4313
Georg Brandl479a7e72008-02-05 18:13:15 +00004314 def test_assign_slice(self):
4315 # ceval.c's assign_slice used to check for
4316 # tp->tp_as_sequence->sq_slice instead of
4317 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004318
Georg Brandl479a7e72008-02-05 18:13:15 +00004319 class C(object):
4320 def __setitem__(self, idx, value):
4321 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004322
Georg Brandl479a7e72008-02-05 18:13:15 +00004323 c = C()
4324 c[1:2] = 3
4325 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004326
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004327 def test_set_and_no_get(self):
4328 # See
4329 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4330 class Descr(object):
4331
4332 def __init__(self, name):
4333 self.name = name
4334
4335 def __set__(self, obj, value):
4336 obj.__dict__[self.name] = value
4337 descr = Descr("a")
4338
4339 class X(object):
4340 a = descr
4341
4342 x = X()
4343 self.assertIs(x.a, descr)
4344 x.a = 42
4345 self.assertEqual(x.a, 42)
4346
Benjamin Peterson21896a32010-03-21 22:03:03 +00004347 # Also check type_getattro for correctness.
4348 class Meta(type):
4349 pass
4350 class X(object):
4351 __metaclass__ = Meta
4352 X.a = 42
4353 Meta.a = Descr("a")
4354 self.assertEqual(X.a, 42)
4355
Benjamin Peterson9262b842008-11-17 22:45:50 +00004356 def test_getattr_hooks(self):
4357 # issue 4230
4358
4359 class Descriptor(object):
4360 counter = 0
4361 def __get__(self, obj, objtype=None):
4362 def getter(name):
4363 self.counter += 1
4364 raise AttributeError(name)
4365 return getter
4366
4367 descr = Descriptor()
4368 class A(object):
4369 __getattribute__ = descr
4370 class B(object):
4371 __getattr__ = descr
4372 class C(object):
4373 __getattribute__ = descr
4374 __getattr__ = descr
4375
4376 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004377 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004378 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004379 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004380 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004381 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004382
4383 import gc
4384 class EvilGetattribute(object):
4385 # This used to segfault
4386 def __getattr__(self, name):
4387 raise AttributeError(name)
4388 def __getattribute__(self, name):
4389 del EvilGetattribute.__getattr__
4390 for i in range(5):
4391 gc.collect()
4392 raise AttributeError(name)
4393
4394 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4395
Benjamin Peterson477ba912011-01-12 15:34:01 +00004396 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004397 # type pretends not to have __abstractmethods__.
4398 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4399 class meta(type):
4400 pass
4401 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004402 class X(object):
4403 pass
4404 with self.assertRaises(AttributeError):
4405 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004406
Victor Stinner3249dec2011-05-01 23:19:15 +02004407 def test_proxy_call(self):
4408 class FakeStr:
4409 __class__ = str
4410
4411 fake_str = FakeStr()
4412 # isinstance() reads __class__
4413 self.assertTrue(isinstance(fake_str, str))
4414
4415 # call a method descriptor
4416 with self.assertRaises(TypeError):
4417 str.split(fake_str)
4418
4419 # call a slot wrapper descriptor
4420 with self.assertRaises(TypeError):
4421 str.__add__(fake_str, "abc")
4422
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004423 def test_repr_as_str(self):
4424 # Issue #11603: crash or infinite loop when rebinding __str__ as
4425 # __repr__.
4426 class Foo:
4427 pass
4428 Foo.__repr__ = Foo.__str__
4429 foo = Foo()
4430 str(foo)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004431
Georg Brandl479a7e72008-02-05 18:13:15 +00004432class DictProxyTests(unittest.TestCase):
4433 def setUp(self):
4434 class C(object):
4435 def meth(self):
4436 pass
4437 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004438
Georg Brandl479a7e72008-02-05 18:13:15 +00004439 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004440 # Testing dict-proxy keys...
4441 it = self.C.__dict__.keys()
4442 self.assertNotIsInstance(it, list)
4443 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004444 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004445 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl479a7e72008-02-05 18:13:15 +00004446 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004447
Georg Brandl479a7e72008-02-05 18:13:15 +00004448 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004449 # Testing dict-proxy values...
4450 it = self.C.__dict__.values()
4451 self.assertNotIsInstance(it, list)
4452 values = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004453 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004454
Georg Brandl479a7e72008-02-05 18:13:15 +00004455 def test_iter_items(self):
4456 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004457 it = self.C.__dict__.items()
4458 self.assertNotIsInstance(it, list)
4459 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004460 keys.sort()
4461 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4462 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004463
Georg Brandl479a7e72008-02-05 18:13:15 +00004464 def test_dict_type_with_metaclass(self):
4465 # Testing type of __dict__ when metaclass set...
4466 class B(object):
4467 pass
4468 class M(type):
4469 pass
4470 class C(metaclass=M):
4471 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4472 pass
4473 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004474
Ezio Melottiac53ab62010-12-18 14:59:43 +00004475 def test_repr(self):
4476 # Testing dict_proxy.__repr__
4477 dict_ = {k: v for k, v in self.C.__dict__.items()}
4478 self.assertEqual(repr(self.C.__dict__), 'dict_proxy({!r})'.format(dict_))
4479
Christian Heimesbbffeb62008-01-24 09:42:52 +00004480
Georg Brandl479a7e72008-02-05 18:13:15 +00004481class PTypesLongInitTest(unittest.TestCase):
4482 # This is in its own TestCase so that it can be run before any other tests.
4483 def test_pytype_long_ready(self):
4484 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004485
Georg Brandl479a7e72008-02-05 18:13:15 +00004486 # This dumps core when SF bug 551412 isn't fixed --
4487 # but only when test_descr.py is run separately.
4488 # (That can't be helped -- as soon as PyType_Ready()
4489 # is called for PyLong_Type, the bug is gone.)
4490 class UserLong(object):
4491 def __pow__(self, *args):
4492 pass
4493 try:
4494 pow(0, UserLong(), 0)
4495 except:
4496 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004497
Georg Brandl479a7e72008-02-05 18:13:15 +00004498 # Another segfault only when run early
4499 # (before PyType_Ready(tuple) is called)
4500 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004501
4502
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004503def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004504 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004505 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004506 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004507
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004508if __name__ == "__main__":
4509 test_main()