blob: 2b2026cee9b39c14139a4c25cb1fd6bde5cb5a87 [file] [log] [blame]
Benjamin Petersonae937c02009-04-18 20:54:08 +00001import builtins
Benjamin Petersona5758c02009-05-09 18:15:04 +00002import sys
Guido van Rossum360e4b82007-05-14 22:51:27 +00003import types
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00004import math
Georg Brandl479a7e72008-02-05 18:13:15 +00005import unittest
Tim Peters4d9b4662002-04-16 01:59:17 +00006
Georg Brandl479a7e72008-02-05 18:13:15 +00007from copy import deepcopy
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test import support
Guido van Rossum875eeaa2001-10-11 18:33:53 +00009
Tim Peters6d6c1a32001-08-02 04:15:00 +000010
Georg Brandl479a7e72008-02-05 18:13:15 +000011class OperatorsTest(unittest.TestCase):
Tim Peters3caca232001-12-06 06:23:26 +000012
Georg Brandl479a7e72008-02-05 18:13:15 +000013 def __init__(self, *args, **kwargs):
14 unittest.TestCase.__init__(self, *args, **kwargs)
15 self.binops = {
16 'add': '+',
17 'sub': '-',
18 'mul': '*',
19 'div': '/',
20 'divmod': 'divmod',
21 'pow': '**',
22 'lshift': '<<',
23 'rshift': '>>',
24 'and': '&',
25 'xor': '^',
26 'or': '|',
27 'cmp': 'cmp',
28 'lt': '<',
29 'le': '<=',
30 'eq': '==',
31 'ne': '!=',
32 'gt': '>',
33 'ge': '>=',
34 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000035
Georg Brandl479a7e72008-02-05 18:13:15 +000036 for name, expr in list(self.binops.items()):
37 if expr.islower():
38 expr = expr + "(a, b)"
39 else:
40 expr = 'a %s b' % expr
41 self.binops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000042
Georg Brandl479a7e72008-02-05 18:13:15 +000043 self.unops = {
44 'pos': '+',
45 'neg': '-',
46 'abs': 'abs',
47 'invert': '~',
48 'int': 'int',
49 'float': 'float',
50 'oct': 'oct',
51 'hex': 'hex',
52 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000053
Georg Brandl479a7e72008-02-05 18:13:15 +000054 for name, expr in list(self.unops.items()):
55 if expr.islower():
56 expr = expr + "(a)"
57 else:
58 expr = '%s a' % expr
59 self.unops[name] = expr
Tim Peters6d6c1a32001-08-02 04:15:00 +000060
Georg Brandl479a7e72008-02-05 18:13:15 +000061 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
62 d = {'a': a}
63 self.assertEqual(eval(expr, d), res)
64 t = type(a)
65 m = getattr(t, meth)
Tim Peters6d6c1a32001-08-02 04:15:00 +000066
Georg Brandl479a7e72008-02-05 18:13:15 +000067 # Find method in parent class
68 while meth not in t.__dict__:
69 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000070 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
71 # method object; the getattr() below obtains its underlying function.
72 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000073 self.assertEqual(m(a), res)
74 bm = getattr(a, meth)
75 self.assertEqual(bm(), res)
Tim Peters2f93e282001-10-04 05:27:00 +000076
Georg Brandl479a7e72008-02-05 18:13:15 +000077 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
78 d = {'a': a, 'b': b}
Tim Peters2f93e282001-10-04 05:27:00 +000079
Georg Brandl479a7e72008-02-05 18:13:15 +000080 # XXX Hack so this passes before 2.3 when -Qnew is specified.
81 if meth == "__div__" and 1/2 == 0.5:
82 meth = "__truediv__"
Tim Peters2f93e282001-10-04 05:27:00 +000083
Georg Brandl479a7e72008-02-05 18:13:15 +000084 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl479a7e72008-02-05 18:13:15 +000086 self.assertEqual(eval(expr, d), res)
87 t = type(a)
88 m = getattr(t, meth)
89 while meth not in t.__dict__:
90 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +000091 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
92 # method object; the getattr() below obtains its underlying function.
93 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +000094 self.assertEqual(m(a, b), res)
95 bm = getattr(a, meth)
96 self.assertEqual(bm(b), res)
Tim Peters2f93e282001-10-04 05:27:00 +000097
Georg Brandl479a7e72008-02-05 18:13:15 +000098 def sliceop_test(self, a, b, c, res, expr="a[b:c]", meth="__getitem__"):
99 d = {'a': a, 'b': b, 'c': c}
100 self.assertEqual(eval(expr, d), res)
101 t = type(a)
102 m = getattr(t, meth)
103 while meth not in t.__dict__:
104 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000105 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
106 # method object; the getattr() below obtains its underlying function.
107 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000108 self.assertEqual(m(a, slice(b, c)), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(slice(b, c)), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111
Georg Brandl479a7e72008-02-05 18:13:15 +0000112 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113 d = {'a': deepcopy(a), 'b': b}
114 exec(stmt, d)
115 self.assertEqual(d['a'], res)
116 t = type(a)
117 m = getattr(t, meth)
118 while meth not in t.__dict__:
119 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000120 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
121 # method object; the getattr() below obtains its underlying function.
122 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000123 d['a'] = deepcopy(a)
124 m(d['a'], b)
125 self.assertEqual(d['a'], res)
126 d['a'] = deepcopy(a)
127 bm = getattr(d['a'], meth)
128 bm(b)
129 self.assertEqual(d['a'], res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000130
Georg Brandl479a7e72008-02-05 18:13:15 +0000131 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
132 d = {'a': deepcopy(a), 'b': b, 'c': c}
133 exec(stmt, d)
134 self.assertEqual(d['a'], res)
135 t = type(a)
136 m = getattr(t, meth)
137 while meth not in t.__dict__:
138 t = t.__bases__[0]
Benjamin Petersone549ead2009-03-28 21:42:05 +0000139 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
140 # method object; the getattr() below obtains its underlying function.
141 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000142 d['a'] = deepcopy(a)
143 m(d['a'], b, c)
144 self.assertEqual(d['a'], res)
145 d['a'] = deepcopy(a)
146 bm = getattr(d['a'], meth)
147 bm(b, c)
148 self.assertEqual(d['a'], res)
149
150 def setsliceop_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setitem__"):
151 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152 exec(stmt, dictionary)
153 self.assertEqual(dictionary['a'], res)
154 t = type(a)
155 while meth not in t.__dict__:
156 t = t.__bases__[0]
157 m = getattr(t, meth)
Benjamin Petersone549ead2009-03-28 21:42:05 +0000158 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
159 # method object; the getattr() below obtains its underlying function.
160 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
Georg Brandl479a7e72008-02-05 18:13:15 +0000161 dictionary['a'] = deepcopy(a)
162 m(dictionary['a'], slice(b, c), d)
163 self.assertEqual(dictionary['a'], res)
164 dictionary['a'] = deepcopy(a)
165 bm = getattr(dictionary['a'], meth)
166 bm(slice(b, c), d)
167 self.assertEqual(dictionary['a'], res)
168
169 def test_lists(self):
170 # Testing list operations...
171 # Asserts are within individual test methods
172 self.binop_test([1], [2], [1,2], "a+b", "__add__")
173 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
174 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
175 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
176 self.sliceop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getitem__")
177 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
178 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
179 self.unop_test([1,2,3], 3, "len(a)", "__len__")
180 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
181 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
182 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
183 self.setsliceop_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184 "__setitem__")
185
186 def test_dicts(self):
187 # Testing dict operations...
Georg Brandl479a7e72008-02-05 18:13:15 +0000188 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
189 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
190 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
191
192 d = {1:2, 3:4}
193 l1 = []
194 for i in list(d.keys()):
195 l1.append(i)
196 l = []
197 for i in iter(d):
198 l.append(i)
199 self.assertEqual(l, l1)
200 l = []
201 for i in d.__iter__():
202 l.append(i)
203 self.assertEqual(l, l1)
204 l = []
205 for i in dict.__iter__(d):
206 l.append(i)
207 self.assertEqual(l, l1)
208 d = {1:2, 3:4}
209 self.unop_test(d, 2, "len(a)", "__len__")
210 self.assertEqual(eval(repr(d), {}), d)
211 self.assertEqual(eval(d.__repr__(), {}), d)
212 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
213 "__setitem__")
214
215 # Tests for unary and binary operators
216 def number_operators(self, a, b, skip=[]):
217 dict = {'a': a, 'b': b}
218
219 for name, expr in list(self.binops.items()):
220 if name not in skip:
221 name = "__%s__" % name
222 if hasattr(a, name):
223 res = eval(expr, dict)
224 self.binop_test(a, b, res, expr, name)
225
226 for name, expr in list(self.unops.items()):
227 if name not in skip:
228 name = "__%s__" % name
229 if hasattr(a, name):
230 res = eval(expr, dict)
231 self.unop_test(a, res, expr, name)
232
233 def test_ints(self):
234 # Testing int operations...
235 self.number_operators(100, 3)
236 # The following crashes in Python 2.2
237 self.assertEqual((1).__bool__(), 1)
238 self.assertEqual((0).__bool__(), 0)
239 # This returns 'NotImplemented' in Python 2.2
240 class C(int):
241 def __add__(self, other):
242 return NotImplemented
243 self.assertEqual(C(5), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000244 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000245 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000246 except TypeError:
247 pass
248 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000249 self.fail("NotImplemented should have caused TypeError")
Tim Peters25786c02001-09-02 08:22:48 +0000250
Georg Brandl479a7e72008-02-05 18:13:15 +0000251 def test_floats(self):
252 # Testing float operations...
253 self.number_operators(100.0, 3.0)
Tim Peters25786c02001-09-02 08:22:48 +0000254
Georg Brandl479a7e72008-02-05 18:13:15 +0000255 def test_complexes(self):
256 # Testing complex operations...
257 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
Mark Dickinson5c2db372009-12-05 20:28:34 +0000258 'int', 'float',
Georg Brandl479a7e72008-02-05 18:13:15 +0000259 'divmod', 'mod'])
Tim Peters25786c02001-09-02 08:22:48 +0000260
Georg Brandl479a7e72008-02-05 18:13:15 +0000261 class Number(complex):
262 __slots__ = ['prec']
263 def __new__(cls, *args, **kwds):
264 result = complex.__new__(cls, *args)
265 result.prec = kwds.get('prec', 12)
266 return result
267 def __repr__(self):
268 prec = self.prec
269 if self.imag == 0.0:
270 return "%.*g" % (prec, self.real)
271 if self.real == 0.0:
272 return "%.*gj" % (prec, self.imag)
273 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
274 __str__ = __repr__
Tim Peters25786c02001-09-02 08:22:48 +0000275
Georg Brandl479a7e72008-02-05 18:13:15 +0000276 a = Number(3.14, prec=6)
277 self.assertEqual(repr(a), "3.14")
278 self.assertEqual(a.prec, 6)
Tim Peters1fc240e2001-10-26 05:06:50 +0000279
Georg Brandl479a7e72008-02-05 18:13:15 +0000280 a = Number(a, prec=2)
281 self.assertEqual(repr(a), "3.1")
282 self.assertEqual(a.prec, 2)
Tim Peters1fc240e2001-10-26 05:06:50 +0000283
Georg Brandl479a7e72008-02-05 18:13:15 +0000284 a = Number(234.5)
285 self.assertEqual(repr(a), "234.5")
286 self.assertEqual(a.prec, 12)
Tim Peters1fc240e2001-10-26 05:06:50 +0000287
Mark Dickinsonb09a3d62010-09-23 20:11:19 +0000288 def test_explicit_reverse_methods(self):
289 # see issue 9930
290 self.assertEqual(complex.__radd__(3j, 4.0), complex(4.0, 3.0))
291 self.assertEqual(float.__rsub__(3.0, 1), -2.0)
292
Benjamin Petersone549ead2009-03-28 21:42:05 +0000293 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000294 def test_spam_lists(self):
295 # Testing spamlist operations...
296 import copy, xxsubtype as spam
297
298 def spamlist(l, memo=None):
299 import xxsubtype as spam
300 return spam.spamlist(l)
301
302 # This is an ugly hack:
303 copy._deepcopy_dispatch[spam.spamlist] = spamlist
304
305 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
306 "__add__")
307 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
308 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
309 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
310 self.sliceop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
311 "__getitem__")
312 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
313 "__iadd__")
314 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
315 "__imul__")
316 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
317 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
318 "__mul__")
319 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
320 "__rmul__")
321 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
322 "__setitem__")
323 self.setsliceop_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
324 spamlist([1,5,6,4]), "a[b:c]=d", "__setitem__")
325 # Test subclassing
326 class C(spam.spamlist):
327 def foo(self): return 1
328 a = C()
329 self.assertEqual(a, [])
330 self.assertEqual(a.foo(), 1)
331 a.append(100)
332 self.assertEqual(a, [100])
333 self.assertEqual(a.getstate(), 0)
334 a.setstate(42)
335 self.assertEqual(a.getstate(), 42)
336
Benjamin Petersone549ead2009-03-28 21:42:05 +0000337 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +0000338 def test_spam_dicts(self):
339 # Testing spamdict operations...
340 import copy, xxsubtype as spam
341 def spamdict(d, memo=None):
342 import xxsubtype as spam
343 sd = spam.spamdict()
344 for k, v in list(d.items()):
345 sd[k] = v
346 return sd
347 # This is an ugly hack:
348 copy._deepcopy_dispatch[spam.spamdict] = spamdict
349
Georg Brandl479a7e72008-02-05 18:13:15 +0000350 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
351 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
352 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
353 d = spamdict({1:2,3:4})
354 l1 = []
355 for i in list(d.keys()):
356 l1.append(i)
357 l = []
358 for i in iter(d):
359 l.append(i)
360 self.assertEqual(l, l1)
361 l = []
362 for i in d.__iter__():
363 l.append(i)
364 self.assertEqual(l, l1)
365 l = []
366 for i in type(spamdict({})).__iter__(d):
367 l.append(i)
368 self.assertEqual(l, l1)
369 straightd = {1:2, 3:4}
370 spamd = spamdict(straightd)
371 self.unop_test(spamd, 2, "len(a)", "__len__")
372 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
373 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
374 "a[b]=c", "__setitem__")
375 # Test subclassing
376 class C(spam.spamdict):
377 def foo(self): return 1
378 a = C()
379 self.assertEqual(list(a.items()), [])
380 self.assertEqual(a.foo(), 1)
381 a['foo'] = 'bar'
382 self.assertEqual(list(a.items()), [('foo', 'bar')])
383 self.assertEqual(a.getstate(), 0)
384 a.setstate(100)
385 self.assertEqual(a.getstate(), 100)
386
387class ClassPropertiesAndMethods(unittest.TestCase):
388
389 def test_python_dicts(self):
390 # Testing Python subclass of dict...
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000391 self.assertTrue(issubclass(dict, dict))
Ezio Melottie9615932010-01-24 19:26:24 +0000392 self.assertIsInstance({}, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000393 d = dict()
394 self.assertEqual(d, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000395 self.assertTrue(d.__class__ is dict)
Ezio Melottie9615932010-01-24 19:26:24 +0000396 self.assertIsInstance(d, dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000397 class C(dict):
398 state = -1
399 def __init__(self_local, *a, **kw):
400 if a:
401 self.assertEqual(len(a), 1)
402 self_local.state = a[0]
403 if kw:
404 for k, v in list(kw.items()):
405 self_local[v] = k
406 def __getitem__(self, key):
407 return self.get(key, 0)
408 def __setitem__(self_local, key, value):
Ezio Melottie9615932010-01-24 19:26:24 +0000409 self.assertIsInstance(key, type(0))
Georg Brandl479a7e72008-02-05 18:13:15 +0000410 dict.__setitem__(self_local, key, value)
411 def setstate(self, state):
412 self.state = state
413 def getstate(self):
414 return self.state
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000415 self.assertTrue(issubclass(C, dict))
Georg Brandl479a7e72008-02-05 18:13:15 +0000416 a1 = C(12)
417 self.assertEqual(a1.state, 12)
418 a2 = C(foo=1, bar=2)
419 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
420 a = C()
421 self.assertEqual(a.state, -1)
422 self.assertEqual(a.getstate(), -1)
423 a.setstate(0)
424 self.assertEqual(a.state, 0)
425 self.assertEqual(a.getstate(), 0)
426 a.setstate(10)
427 self.assertEqual(a.state, 10)
428 self.assertEqual(a.getstate(), 10)
429 self.assertEqual(a[42], 0)
430 a[42] = 24
431 self.assertEqual(a[42], 24)
432 N = 50
433 for i in range(N):
434 a[i] = C()
435 for j in range(N):
436 a[i][j] = i*j
437 for i in range(N):
438 for j in range(N):
439 self.assertEqual(a[i][j], i*j)
440
441 def test_python_lists(self):
442 # Testing Python subclass of list...
443 class C(list):
444 def __getitem__(self, i):
445 if isinstance(i, slice):
446 return i.start, i.stop
447 return list.__getitem__(self, i) + 100
448 a = C()
449 a.extend([0,1,2])
450 self.assertEqual(a[0], 100)
451 self.assertEqual(a[1], 101)
452 self.assertEqual(a[2], 102)
453 self.assertEqual(a[100:200], (100,200))
454
455 def test_metaclass(self):
Georg Brandle81f5ef2008-05-27 20:34:09 +0000456 # Testing metaclasses...
Georg Brandl479a7e72008-02-05 18:13:15 +0000457 class C(metaclass=type):
458 def __init__(self):
459 self.__state = 0
460 def getstate(self):
461 return self.__state
462 def setstate(self, state):
463 self.__state = state
464 a = C()
465 self.assertEqual(a.getstate(), 0)
466 a.setstate(10)
467 self.assertEqual(a.getstate(), 10)
468 class _metaclass(type):
469 def myself(cls): return cls
470 class D(metaclass=_metaclass):
471 pass
472 self.assertEqual(D.myself(), D)
473 d = D()
474 self.assertEqual(d.__class__, D)
475 class M1(type):
476 def __new__(cls, name, bases, dict):
477 dict['__spam__'] = 1
478 return type.__new__(cls, name, bases, dict)
479 class C(metaclass=M1):
480 pass
481 self.assertEqual(C.__spam__, 1)
482 c = C()
483 self.assertEqual(c.__spam__, 1)
484
485 class _instance(object):
486 pass
487 class M2(object):
488 @staticmethod
489 def __new__(cls, name, bases, dict):
490 self = object.__new__(cls)
491 self.name = name
492 self.bases = bases
493 self.dict = dict
494 return self
495 def __call__(self):
496 it = _instance()
497 # Early binding of methods
498 for key in self.dict:
499 if key.startswith("__"):
500 continue
501 setattr(it, key, self.dict[key].__get__(it, self))
502 return it
503 class C(metaclass=M2):
504 def spam(self):
505 return 42
506 self.assertEqual(C.name, 'C')
507 self.assertEqual(C.bases, ())
Benjamin Peterson577473f2010-01-19 00:09:57 +0000508 self.assertIn('spam', C.dict)
Georg Brandl479a7e72008-02-05 18:13:15 +0000509 c = C()
510 self.assertEqual(c.spam(), 42)
511
512 # More metaclass examples
513
514 class autosuper(type):
515 # Automatically add __super to the class
516 # This trick only works for dynamic classes
517 def __new__(metaclass, name, bases, dict):
518 cls = super(autosuper, metaclass).__new__(metaclass,
519 name, bases, dict)
520 # Name mangling for __super removes leading underscores
521 while name[:1] == "_":
522 name = name[1:]
523 if name:
524 name = "_%s__super" % name
525 else:
526 name = "__super"
527 setattr(cls, name, super(cls))
528 return cls
529 class A(metaclass=autosuper):
530 def meth(self):
531 return "A"
532 class B(A):
533 def meth(self):
534 return "B" + self.__super.meth()
535 class C(A):
536 def meth(self):
537 return "C" + self.__super.meth()
538 class D(C, B):
539 def meth(self):
540 return "D" + self.__super.meth()
541 self.assertEqual(D().meth(), "DCBA")
542 class E(B, C):
543 def meth(self):
544 return "E" + self.__super.meth()
545 self.assertEqual(E().meth(), "EBCA")
546
547 class autoproperty(type):
548 # Automatically create property attributes when methods
549 # named _get_x and/or _set_x are found
550 def __new__(metaclass, name, bases, dict):
551 hits = {}
552 for key, val in dict.items():
553 if key.startswith("_get_"):
554 key = key[5:]
555 get, set = hits.get(key, (None, None))
556 get = val
557 hits[key] = get, set
558 elif key.startswith("_set_"):
559 key = key[5:]
560 get, set = hits.get(key, (None, None))
561 set = val
562 hits[key] = get, set
563 for key, (get, set) in hits.items():
564 dict[key] = property(get, set)
565 return super(autoproperty, metaclass).__new__(metaclass,
566 name, bases, dict)
567 class A(metaclass=autoproperty):
568 def _get_x(self):
569 return -self.__x
570 def _set_x(self, x):
571 self.__x = -x
572 a = A()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000573 self.assertTrue(not hasattr(a, "x"))
Georg Brandl479a7e72008-02-05 18:13:15 +0000574 a.x = 12
575 self.assertEqual(a.x, 12)
576 self.assertEqual(a._A__x, -12)
577
578 class multimetaclass(autoproperty, autosuper):
579 # Merge of multiple cooperating metaclasses
580 pass
581 class A(metaclass=multimetaclass):
582 def _get_x(self):
583 return "A"
584 class B(A):
585 def _get_x(self):
586 return "B" + self.__super._get_x()
587 class C(A):
588 def _get_x(self):
589 return "C" + self.__super._get_x()
590 class D(C, B):
591 def _get_x(self):
592 return "D" + self.__super._get_x()
593 self.assertEqual(D().x, "DCBA")
594
595 # Make sure type(x) doesn't call x.__class__.__init__
596 class T(type):
597 counter = 0
598 def __init__(self, *args):
599 T.counter += 1
600 class C(metaclass=T):
601 pass
602 self.assertEqual(T.counter, 1)
603 a = C()
604 self.assertEqual(type(a), C)
605 self.assertEqual(T.counter, 1)
606
607 class C(object): pass
608 c = C()
609 try: c()
610 except TypeError: pass
611 else: self.fail("calling object w/o call method should raise "
612 "TypeError")
613
614 # Testing code to find most derived baseclass
615 class A(type):
616 def __new__(*args, **kwargs):
617 return type.__new__(*args, **kwargs)
618
619 class B(object):
620 pass
621
622 class C(object, metaclass=A):
623 pass
624
625 # The most derived metaclass of D is A rather than type.
626 class D(B, C):
627 pass
Nick Coghlande31b192011-10-23 22:04:16 +1000628 self.assertIs(A, type(D))
629
630 # issue1294232: correct metaclass calculation
631 new_calls = [] # to check the order of __new__ calls
632 class AMeta(type):
633 @staticmethod
634 def __new__(mcls, name, bases, ns):
635 new_calls.append('AMeta')
636 return super().__new__(mcls, name, bases, ns)
637 @classmethod
638 def __prepare__(mcls, name, bases):
639 return {}
640
641 class BMeta(AMeta):
642 @staticmethod
643 def __new__(mcls, name, bases, ns):
644 new_calls.append('BMeta')
645 return super().__new__(mcls, name, bases, ns)
646 @classmethod
647 def __prepare__(mcls, name, bases):
648 ns = super().__prepare__(name, bases)
649 ns['BMeta_was_here'] = True
650 return ns
651
652 class A(metaclass=AMeta):
653 pass
654 self.assertEqual(['AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000655 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000656
657 class B(metaclass=BMeta):
658 pass
659 # BMeta.__new__ calls AMeta.__new__ with super:
660 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000661 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000662
663 class C(A, B):
664 pass
665 # The most derived metaclass is BMeta:
666 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000667 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000668 # BMeta.__prepare__ should've been called:
669 self.assertIn('BMeta_was_here', C.__dict__)
670
671 # The order of the bases shouldn't matter:
672 class C2(B, A):
673 pass
674 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000675 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000676 self.assertIn('BMeta_was_here', C2.__dict__)
677
678 # Check correct metaclass calculation when a metaclass is declared:
679 class D(C, metaclass=type):
680 pass
681 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000682 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000683 self.assertIn('BMeta_was_here', D.__dict__)
684
685 class E(C, metaclass=AMeta):
686 pass
687 self.assertEqual(['BMeta', 'AMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000688 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000689 self.assertIn('BMeta_was_here', E.__dict__)
690
691 # Special case: the given metaclass isn't a class,
692 # so there is no metaclass calculation.
693 marker = object()
694 def func(*args, **kwargs):
695 return marker
696 class X(metaclass=func):
697 pass
698 class Y(object, metaclass=func):
699 pass
700 class Z(D, metaclass=func):
701 pass
702 self.assertIs(marker, X)
703 self.assertIs(marker, Y)
704 self.assertIs(marker, Z)
705
706 # The given metaclass is a class,
707 # but not a descendant of type.
708 prepare_calls = [] # to track __prepare__ calls
709 class ANotMeta:
710 def __new__(mcls, *args, **kwargs):
711 new_calls.append('ANotMeta')
712 return super().__new__(mcls)
713 @classmethod
714 def __prepare__(mcls, name, bases):
715 prepare_calls.append('ANotMeta')
716 return {}
717 class BNotMeta(ANotMeta):
718 def __new__(mcls, *args, **kwargs):
719 new_calls.append('BNotMeta')
720 return super().__new__(mcls)
721 @classmethod
722 def __prepare__(mcls, name, bases):
723 prepare_calls.append('BNotMeta')
724 return super().__prepare__(name, bases)
725
726 class A(metaclass=ANotMeta):
727 pass
728 self.assertIs(ANotMeta, type(A))
729 self.assertEqual(['ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000730 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000731 self.assertEqual(['ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000732 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000733
734 class B(metaclass=BNotMeta):
735 pass
736 self.assertIs(BNotMeta, type(B))
737 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000738 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000739 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000740 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000741
742 class C(A, B):
743 pass
744 self.assertIs(BNotMeta, type(C))
745 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000746 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000747 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000748 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000749
750 class C2(B, A):
751 pass
752 self.assertIs(BNotMeta, type(C2))
753 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000754 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000755 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000756 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000757
758 # This is a TypeError, because of a metaclass conflict:
759 # BNotMeta is neither a subclass, nor a superclass of type
760 with self.assertRaises(TypeError):
761 class D(C, metaclass=type):
762 pass
763
764 class E(C, metaclass=ANotMeta):
765 pass
766 self.assertIs(BNotMeta, type(E))
767 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000768 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000769 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000770 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000771
772 class F(object(), C):
773 pass
774 self.assertIs(BNotMeta, type(F))
775 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000776 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000777 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000778 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000779
780 class F2(C, object()):
781 pass
782 self.assertIs(BNotMeta, type(F2))
783 self.assertEqual(['BNotMeta', 'ANotMeta'], new_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000784 new_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000785 self.assertEqual(['BNotMeta', 'ANotMeta'], prepare_calls)
Nick Coghlan9715d262011-10-23 22:36:42 +1000786 prepare_calls.clear()
Nick Coghlande31b192011-10-23 22:04:16 +1000787
788 # TypeError: BNotMeta is neither a
789 # subclass, nor a superclass of int
790 with self.assertRaises(TypeError):
791 class X(C, int()):
792 pass
793 with self.assertRaises(TypeError):
794 class X(int(), C):
795 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000796
797 def test_module_subclasses(self):
798 # Testing Python subclass of module...
799 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000800 MT = type(sys)
801 class MM(MT):
802 def __init__(self, name):
803 MT.__init__(self, name)
804 def __getattribute__(self, name):
805 log.append(("getattr", name))
806 return MT.__getattribute__(self, name)
807 def __setattr__(self, name, value):
808 log.append(("setattr", name, value))
809 MT.__setattr__(self, name, value)
810 def __delattr__(self, name):
811 log.append(("delattr", name))
812 MT.__delattr__(self, name)
813 a = MM("a")
814 a.foo = 12
815 x = a.foo
816 del a.foo
817 self.assertEqual(log, [("setattr", "foo", 12),
818 ("getattr", "foo"),
819 ("delattr", "foo")])
820
821 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000822 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000823 class Module(types.ModuleType, str):
824 pass
825 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000826 pass
827 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000828 self.fail("inheriting from ModuleType and str at the same time "
829 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000830
Georg Brandl479a7e72008-02-05 18:13:15 +0000831 def test_multiple_inheritance(self):
832 # Testing multiple inheritance...
833 class C(object):
834 def __init__(self):
835 self.__state = 0
836 def getstate(self):
837 return self.__state
838 def setstate(self, state):
839 self.__state = state
840 a = C()
841 self.assertEqual(a.getstate(), 0)
842 a.setstate(10)
843 self.assertEqual(a.getstate(), 10)
844 class D(dict, C):
845 def __init__(self):
846 type({}).__init__(self)
847 C.__init__(self)
848 d = D()
849 self.assertEqual(list(d.keys()), [])
850 d["hello"] = "world"
851 self.assertEqual(list(d.items()), [("hello", "world")])
852 self.assertEqual(d["hello"], "world")
853 self.assertEqual(d.getstate(), 0)
854 d.setstate(10)
855 self.assertEqual(d.getstate(), 10)
856 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000857
Georg Brandl479a7e72008-02-05 18:13:15 +0000858 # SF bug #442833
859 class Node(object):
860 def __int__(self):
861 return int(self.foo())
862 def foo(self):
863 return "23"
864 class Frag(Node, list):
865 def foo(self):
866 return "42"
867 self.assertEqual(Node().__int__(), 23)
868 self.assertEqual(int(Node()), 23)
869 self.assertEqual(Frag().__int__(), 42)
870 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000871
Georg Brandl479a7e72008-02-05 18:13:15 +0000872 def test_diamond_inheritence(self):
873 # Testing multiple inheritance special cases...
874 class A(object):
875 def spam(self): return "A"
876 self.assertEqual(A().spam(), "A")
877 class B(A):
878 def boo(self): return "B"
879 def spam(self): return "B"
880 self.assertEqual(B().spam(), "B")
881 self.assertEqual(B().boo(), "B")
882 class C(A):
883 def boo(self): return "C"
884 self.assertEqual(C().spam(), "A")
885 self.assertEqual(C().boo(), "C")
886 class D(B, C): pass
887 self.assertEqual(D().spam(), "B")
888 self.assertEqual(D().boo(), "B")
889 self.assertEqual(D.__mro__, (D, B, C, A, object))
890 class E(C, B): pass
891 self.assertEqual(E().spam(), "B")
892 self.assertEqual(E().boo(), "C")
893 self.assertEqual(E.__mro__, (E, C, B, A, object))
894 # MRO order disagreement
895 try:
896 class F(D, E): pass
897 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000898 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000899 else:
900 self.fail("expected MRO order disagreement (F)")
901 try:
902 class G(E, D): pass
903 except TypeError:
904 pass
905 else:
906 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000907
Georg Brandl479a7e72008-02-05 18:13:15 +0000908 # see thread python-dev/2002-October/029035.html
909 def test_ex5_from_c3_switch(self):
910 # Testing ex5 from C3 switch discussion...
911 class A(object): pass
912 class B(object): pass
913 class C(object): pass
914 class X(A): pass
915 class Y(A): pass
916 class Z(X,B,Y,C): pass
917 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000918
Georg Brandl479a7e72008-02-05 18:13:15 +0000919 # see "A Monotonic Superclass Linearization for Dylan",
920 # by Kim Barrett et al. (OOPSLA 1996)
921 def test_monotonicity(self):
922 # Testing MRO monotonicity...
923 class Boat(object): pass
924 class DayBoat(Boat): pass
925 class WheelBoat(Boat): pass
926 class EngineLess(DayBoat): pass
927 class SmallMultihull(DayBoat): pass
928 class PedalWheelBoat(EngineLess,WheelBoat): pass
929 class SmallCatamaran(SmallMultihull): pass
930 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000931
Georg Brandl479a7e72008-02-05 18:13:15 +0000932 self.assertEqual(PedalWheelBoat.__mro__,
933 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
934 self.assertEqual(SmallCatamaran.__mro__,
935 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
936 self.assertEqual(Pedalo.__mro__,
937 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
938 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000939
Georg Brandl479a7e72008-02-05 18:13:15 +0000940 # see "A Monotonic Superclass Linearization for Dylan",
941 # by Kim Barrett et al. (OOPSLA 1996)
942 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200943 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000944 class Pane(object): pass
945 class ScrollingMixin(object): pass
946 class EditingMixin(object): pass
947 class ScrollablePane(Pane,ScrollingMixin): pass
948 class EditablePane(Pane,EditingMixin): pass
949 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000950
Georg Brandl479a7e72008-02-05 18:13:15 +0000951 self.assertEqual(EditableScrollablePane.__mro__,
952 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
953 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000954
Georg Brandl479a7e72008-02-05 18:13:15 +0000955 def test_mro_disagreement(self):
956 # Testing error messages for MRO disagreement...
957 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000958order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000959
Georg Brandl479a7e72008-02-05 18:13:15 +0000960 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000961 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000962 callable(*args)
963 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000964 # the exact msg is generally considered an impl detail
965 if support.check_impl_detail():
966 if not str(msg).startswith(expected):
967 self.fail("Message %r, expected %r" %
968 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000969 else:
970 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000971
Georg Brandl479a7e72008-02-05 18:13:15 +0000972 class A(object): pass
973 class B(A): pass
974 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000975
Georg Brandl479a7e72008-02-05 18:13:15 +0000976 # Test some very simple errors
977 raises(TypeError, "duplicate base class A",
978 type, "X", (A, A), {})
979 raises(TypeError, mro_err_msg,
980 type, "X", (A, B), {})
981 raises(TypeError, mro_err_msg,
982 type, "X", (A, C, B), {})
983 # Test a slightly more complex error
984 class GridLayout(object): pass
985 class HorizontalGrid(GridLayout): pass
986 class VerticalGrid(GridLayout): pass
987 class HVGrid(HorizontalGrid, VerticalGrid): pass
988 class VHGrid(VerticalGrid, HorizontalGrid): pass
989 raises(TypeError, mro_err_msg,
990 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000991
Georg Brandl479a7e72008-02-05 18:13:15 +0000992 def test_object_class(self):
993 # Testing object class...
994 a = object()
995 self.assertEqual(a.__class__, object)
996 self.assertEqual(type(a), object)
997 b = object()
998 self.assertNotEqual(a, b)
999 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +00001000 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001001 a.foo = 12
1002 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +00001003 pass
1004 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001005 self.fail("object() should not allow setting a foo attribute")
1006 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +00001007
Georg Brandl479a7e72008-02-05 18:13:15 +00001008 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001009 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00001010 x = Cdict()
1011 self.assertEqual(x.__dict__, {})
1012 x.foo = 1
1013 self.assertEqual(x.foo, 1)
1014 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +00001015
Georg Brandl479a7e72008-02-05 18:13:15 +00001016 def test_slots(self):
1017 # Testing __slots__...
1018 class C0(object):
1019 __slots__ = []
1020 x = C0()
1021 self.assertFalse(hasattr(x, "__dict__"))
1022 self.assertFalse(hasattr(x, "foo"))
1023
1024 class C1(object):
1025 __slots__ = ['a']
1026 x = C1()
1027 self.assertFalse(hasattr(x, "__dict__"))
1028 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +00001029 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +00001030 self.assertEqual(x.a, 1)
1031 x.a = None
1032 self.assertEqual(x.a, None)
1033 del x.a
1034 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +00001035
Georg Brandl479a7e72008-02-05 18:13:15 +00001036 class C3(object):
1037 __slots__ = ['a', 'b', 'c']
1038 x = C3()
1039 self.assertFalse(hasattr(x, "__dict__"))
1040 self.assertFalse(hasattr(x, 'a'))
1041 self.assertFalse(hasattr(x, 'b'))
1042 self.assertFalse(hasattr(x, 'c'))
1043 x.a = 1
1044 x.b = 2
1045 x.c = 3
1046 self.assertEqual(x.a, 1)
1047 self.assertEqual(x.b, 2)
1048 self.assertEqual(x.c, 3)
1049
1050 class C4(object):
1051 """Validate name mangling"""
1052 __slots__ = ['__a']
1053 def __init__(self, value):
1054 self.__a = value
1055 def get(self):
1056 return self.__a
1057 x = C4(5)
1058 self.assertFalse(hasattr(x, '__dict__'))
1059 self.assertFalse(hasattr(x, '__a'))
1060 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001061 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001062 x.__a = 6
1063 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +00001064 pass
1065 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001066 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001067
Georg Brandl479a7e72008-02-05 18:13:15 +00001068 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +00001069 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001070 class C(object):
1071 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +00001072 except TypeError:
1073 pass
1074 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001075 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +00001076 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00001077 class C(object):
1078 __slots__ = ["foo bar"]
1079 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +00001080 pass
1081 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00001082 self.fail("['foo bar'] slots not caught")
1083 try:
1084 class C(object):
1085 __slots__ = ["foo\0bar"]
1086 except TypeError:
1087 pass
1088 else:
1089 self.fail("['foo\\0bar'] slots not caught")
1090 try:
1091 class C(object):
1092 __slots__ = ["1"]
1093 except TypeError:
1094 pass
1095 else:
1096 self.fail("['1'] slots not caught")
1097 try:
1098 class C(object):
1099 __slots__ = [""]
1100 except TypeError:
1101 pass
1102 else:
1103 self.fail("[''] slots not caught")
1104 class C(object):
1105 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1106 # XXX(nnorwitz): was there supposed to be something tested
1107 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +00001108
Georg Brandl479a7e72008-02-05 18:13:15 +00001109 # Test a single string is not expanded as a sequence.
1110 class C(object):
1111 __slots__ = "abc"
1112 c = C()
1113 c.abc = 5
1114 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +00001115
Georg Brandl479a7e72008-02-05 18:13:15 +00001116 # Test unicode slot names
1117 # Test a single unicode string is not expanded as a sequence.
1118 class C(object):
1119 __slots__ = "abc"
1120 c = C()
1121 c.abc = 5
1122 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +00001123
Georg Brandl479a7e72008-02-05 18:13:15 +00001124 # _unicode_to_string used to modify slots in certain circumstances
1125 slots = ("foo", "bar")
1126 class C(object):
1127 __slots__ = slots
1128 x = C()
1129 x.foo = 5
1130 self.assertEqual(x.foo, 5)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001131 self.assertTrue(type(slots[0]) is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00001132 # this used to leak references
1133 try:
1134 class C(object):
1135 __slots__ = [chr(128)]
1136 except (TypeError, UnicodeEncodeError):
1137 pass
1138 else:
1139 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +00001140
Georg Brandl479a7e72008-02-05 18:13:15 +00001141 # Test leaks
1142 class Counted(object):
1143 counter = 0 # counts the number of instances alive
1144 def __init__(self):
1145 Counted.counter += 1
1146 def __del__(self):
1147 Counted.counter -= 1
1148 class C(object):
1149 __slots__ = ['a', 'b', 'c']
1150 x = C()
1151 x.a = Counted()
1152 x.b = Counted()
1153 x.c = Counted()
1154 self.assertEqual(Counted.counter, 3)
1155 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001156 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001157 self.assertEqual(Counted.counter, 0)
1158 class D(C):
1159 pass
1160 x = D()
1161 x.a = Counted()
1162 x.z = Counted()
1163 self.assertEqual(Counted.counter, 2)
1164 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001165 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001166 self.assertEqual(Counted.counter, 0)
1167 class E(D):
1168 __slots__ = ['e']
1169 x = E()
1170 x.a = Counted()
1171 x.z = Counted()
1172 x.e = Counted()
1173 self.assertEqual(Counted.counter, 3)
1174 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001175 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001176 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001177
Georg Brandl479a7e72008-02-05 18:13:15 +00001178 # Test cyclical leaks [SF bug 519621]
1179 class F(object):
1180 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001181 s = F()
1182 s.a = [Counted(), s]
1183 self.assertEqual(Counted.counter, 1)
1184 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001185 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001186 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001187
Georg Brandl479a7e72008-02-05 18:13:15 +00001188 # Test lookup leaks [SF bug 572567]
Georg Brandl1b37e872010-03-14 10:45:50 +00001189 import gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001190 if hasattr(gc, 'get_objects'):
1191 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001192 def __eq__(self, other):
1193 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001194 g = G()
1195 orig_objects = len(gc.get_objects())
1196 for i in range(10):
1197 g==g
1198 new_objects = len(gc.get_objects())
1199 self.assertEqual(orig_objects, new_objects)
1200
Georg Brandl479a7e72008-02-05 18:13:15 +00001201 class H(object):
1202 __slots__ = ['a', 'b']
1203 def __init__(self):
1204 self.a = 1
1205 self.b = 2
1206 def __del__(self_):
1207 self.assertEqual(self_.a, 1)
1208 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001209 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001210 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001211 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001212 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001213
Benjamin Petersond12362a2009-12-30 19:44:54 +00001214 class X(object):
1215 __slots__ = "a"
1216 with self.assertRaises(AttributeError):
1217 del X().a
1218
Georg Brandl479a7e72008-02-05 18:13:15 +00001219 def test_slots_special(self):
1220 # Testing __dict__ and __weakref__ in __slots__...
1221 class D(object):
1222 __slots__ = ["__dict__"]
1223 a = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001224 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001225 self.assertFalse(hasattr(a, "__weakref__"))
1226 a.foo = 42
1227 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001228
Georg Brandl479a7e72008-02-05 18:13:15 +00001229 class W(object):
1230 __slots__ = ["__weakref__"]
1231 a = W()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001232 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001233 self.assertFalse(hasattr(a, "__dict__"))
1234 try:
1235 a.foo = 42
1236 except AttributeError:
1237 pass
1238 else:
1239 self.fail("shouldn't be allowed to set a.foo")
1240
1241 class C1(W, D):
1242 __slots__ = []
1243 a = C1()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001244 self.assertTrue(hasattr(a, "__dict__"))
1245 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001246 a.foo = 42
1247 self.assertEqual(a.__dict__, {"foo": 42})
1248
1249 class C2(D, W):
1250 __slots__ = []
1251 a = C2()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001252 self.assertTrue(hasattr(a, "__dict__"))
1253 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001254 a.foo = 42
1255 self.assertEqual(a.__dict__, {"foo": 42})
1256
Christian Heimesa156e092008-02-16 07:38:31 +00001257 def test_slots_descriptor(self):
1258 # Issue2115: slot descriptors did not correctly check
1259 # the type of the given object
1260 import abc
1261 class MyABC(metaclass=abc.ABCMeta):
1262 __slots__ = "a"
1263
1264 class Unrelated(object):
1265 pass
1266 MyABC.register(Unrelated)
1267
1268 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001269 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001270
1271 # This used to crash
1272 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1273
Georg Brandl479a7e72008-02-05 18:13:15 +00001274 def test_dynamics(self):
1275 # Testing class attribute propagation...
1276 class D(object):
1277 pass
1278 class E(D):
1279 pass
1280 class F(D):
1281 pass
1282 D.foo = 1
1283 self.assertEqual(D.foo, 1)
1284 # Test that dynamic attributes are inherited
1285 self.assertEqual(E.foo, 1)
1286 self.assertEqual(F.foo, 1)
1287 # Test dynamic instances
1288 class C(object):
1289 pass
1290 a = C()
1291 self.assertFalse(hasattr(a, "foobar"))
1292 C.foobar = 2
1293 self.assertEqual(a.foobar, 2)
1294 C.method = lambda self: 42
1295 self.assertEqual(a.method(), 42)
1296 C.__repr__ = lambda self: "C()"
1297 self.assertEqual(repr(a), "C()")
1298 C.__int__ = lambda self: 100
1299 self.assertEqual(int(a), 100)
1300 self.assertEqual(a.foobar, 2)
1301 self.assertFalse(hasattr(a, "spam"))
1302 def mygetattr(self, name):
1303 if name == "spam":
1304 return "spam"
1305 raise AttributeError
1306 C.__getattr__ = mygetattr
1307 self.assertEqual(a.spam, "spam")
1308 a.new = 12
1309 self.assertEqual(a.new, 12)
1310 def mysetattr(self, name, value):
1311 if name == "spam":
1312 raise AttributeError
1313 return object.__setattr__(self, name, value)
1314 C.__setattr__ = mysetattr
1315 try:
1316 a.spam = "not spam"
1317 except AttributeError:
1318 pass
1319 else:
1320 self.fail("expected AttributeError")
1321 self.assertEqual(a.spam, "spam")
1322 class D(C):
1323 pass
1324 d = D()
1325 d.foo = 1
1326 self.assertEqual(d.foo, 1)
1327
1328 # Test handling of int*seq and seq*int
1329 class I(int):
1330 pass
1331 self.assertEqual("a"*I(2), "aa")
1332 self.assertEqual(I(2)*"a", "aa")
1333 self.assertEqual(2*I(3), 6)
1334 self.assertEqual(I(3)*2, 6)
1335 self.assertEqual(I(3)*I(2), 6)
1336
Georg Brandl479a7e72008-02-05 18:13:15 +00001337 # Test comparison of classes with dynamic metaclasses
1338 class dynamicmetaclass(type):
1339 pass
1340 class someclass(metaclass=dynamicmetaclass):
1341 pass
1342 self.assertNotEqual(someclass, object)
1343
1344 def test_errors(self):
1345 # Testing errors...
1346 try:
1347 class C(list, dict):
1348 pass
1349 except TypeError:
1350 pass
1351 else:
1352 self.fail("inheritance from both list and dict should be illegal")
1353
1354 try:
1355 class C(object, None):
1356 pass
1357 except TypeError:
1358 pass
1359 else:
1360 self.fail("inheritance from non-type should be illegal")
1361 class Classic:
1362 pass
1363
1364 try:
1365 class C(type(len)):
1366 pass
1367 except TypeError:
1368 pass
1369 else:
1370 self.fail("inheritance from CFunction should be illegal")
1371
1372 try:
1373 class C(object):
1374 __slots__ = 1
1375 except TypeError:
1376 pass
1377 else:
1378 self.fail("__slots__ = 1 should be illegal")
1379
1380 try:
1381 class C(object):
1382 __slots__ = [1]
1383 except TypeError:
1384 pass
1385 else:
1386 self.fail("__slots__ = [1] should be illegal")
1387
1388 class M1(type):
1389 pass
1390 class M2(type):
1391 pass
1392 class A1(object, metaclass=M1):
1393 pass
1394 class A2(object, metaclass=M2):
1395 pass
1396 try:
1397 class B(A1, A2):
1398 pass
1399 except TypeError:
1400 pass
1401 else:
1402 self.fail("finding the most derived metaclass should have failed")
1403
1404 def test_classmethods(self):
1405 # Testing class methods...
1406 class C(object):
1407 def foo(*a): return a
1408 goo = classmethod(foo)
1409 c = C()
1410 self.assertEqual(C.goo(1), (C, 1))
1411 self.assertEqual(c.goo(1), (C, 1))
1412 self.assertEqual(c.foo(1), (c, 1))
1413 class D(C):
1414 pass
1415 d = D()
1416 self.assertEqual(D.goo(1), (D, 1))
1417 self.assertEqual(d.goo(1), (D, 1))
1418 self.assertEqual(d.foo(1), (d, 1))
1419 self.assertEqual(D.foo(d, 1), (d, 1))
1420 # Test for a specific crash (SF bug 528132)
1421 def f(cls, arg): return (cls, arg)
1422 ff = classmethod(f)
1423 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1424 self.assertEqual(ff.__get__(0)(42), (int, 42))
1425
1426 # Test super() with classmethods (SF bug 535444)
1427 self.assertEqual(C.goo.__self__, C)
1428 self.assertEqual(D.goo.__self__, D)
1429 self.assertEqual(super(D,D).goo.__self__, D)
1430 self.assertEqual(super(D,d).goo.__self__, D)
1431 self.assertEqual(super(D,D).goo(), (D,))
1432 self.assertEqual(super(D,d).goo(), (D,))
1433
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001434 # Verify that a non-callable will raise
1435 meth = classmethod(1).__get__(1)
1436 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001437
1438 # Verify that classmethod() doesn't allow keyword args
1439 try:
1440 classmethod(f, kw=1)
1441 except TypeError:
1442 pass
1443 else:
1444 self.fail("classmethod shouldn't accept keyword args")
1445
Benjamin 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())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001802 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001803
Georg Brandl479a7e72008-02-05 18:13:15 +00001804 def test_specials(self):
1805 # Testing special operators...
1806 # Test operators like __hash__ for which a built-in default exists
1807
1808 # Test the default behavior for static classes
1809 class C(object):
1810 def __getitem__(self, i):
1811 if 0 <= i < 10: return i
1812 raise IndexError
1813 c1 = C()
1814 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001815 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001816 self.assertNotEqual(id(c1), id(c2))
1817 hash(c1)
1818 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001819 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001820 self.assertTrue(c1 != c2)
1821 self.assertTrue(not c1 != c1)
1822 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001823 # Note that the module name appears in str/repr, and that varies
1824 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001825 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001826 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001827 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001828 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001829 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001830 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001831 # Test the default behavior for dynamic classes
1832 class D(object):
1833 def __getitem__(self, i):
1834 if 0 <= i < 10: return i
1835 raise IndexError
1836 d1 = D()
1837 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001838 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001839 self.assertNotEqual(id(d1), id(d2))
1840 hash(d1)
1841 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001842 self.assertEqual(d1, d1)
1843 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001844 self.assertTrue(not d1 != d1)
1845 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001846 # Note that the module name appears in str/repr, and that varies
1847 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001848 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001849 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001850 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001851 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001852 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001853 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001854 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001855 class Proxy(object):
1856 def __init__(self, x):
1857 self.x = x
1858 def __bool__(self):
1859 return not not self.x
1860 def __hash__(self):
1861 return hash(self.x)
1862 def __eq__(self, other):
1863 return self.x == other
1864 def __ne__(self, other):
1865 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001866 def __ge__(self, other):
1867 return self.x >= other
1868 def __gt__(self, other):
1869 return self.x > other
1870 def __le__(self, other):
1871 return self.x <= other
1872 def __lt__(self, other):
1873 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001874 def __str__(self):
1875 return "Proxy:%s" % self.x
1876 def __repr__(self):
1877 return "Proxy(%r)" % self.x
1878 def __contains__(self, value):
1879 return value in self.x
1880 p0 = Proxy(0)
1881 p1 = Proxy(1)
1882 p_1 = Proxy(-1)
1883 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001884 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001885 self.assertEqual(hash(p0), hash(0))
1886 self.assertEqual(p0, p0)
1887 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001888 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001889 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001890 self.assertTrue(p0 < p1)
1891 self.assertTrue(p0 <= p1)
1892 self.assertTrue(p1 > p0)
1893 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001894 self.assertEqual(str(p0), "Proxy:0")
1895 self.assertEqual(repr(p0), "Proxy(0)")
1896 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001897 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001898 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001899 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001900 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001901
Georg Brandl479a7e72008-02-05 18:13:15 +00001902 def test_weakrefs(self):
1903 # Testing weak references...
1904 import weakref
1905 class C(object):
1906 pass
1907 c = C()
1908 r = weakref.ref(c)
1909 self.assertEqual(r(), c)
1910 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001911 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001912 self.assertEqual(r(), None)
1913 del r
1914 class NoWeak(object):
1915 __slots__ = ['foo']
1916 no = NoWeak()
1917 try:
1918 weakref.ref(no)
1919 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001920 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001921 else:
1922 self.fail("weakref.ref(no) should be illegal")
1923 class Weak(object):
1924 __slots__ = ['foo', '__weakref__']
1925 yes = Weak()
1926 r = weakref.ref(yes)
1927 self.assertEqual(r(), yes)
1928 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001929 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001930 self.assertEqual(r(), None)
1931 del r
1932
1933 def test_properties(self):
1934 # Testing property...
1935 class C(object):
1936 def getx(self):
1937 return self.__x
1938 def setx(self, value):
1939 self.__x = value
1940 def delx(self):
1941 del self.__x
1942 x = property(getx, setx, delx, doc="I'm the x property.")
1943 a = C()
1944 self.assertFalse(hasattr(a, "x"))
1945 a.x = 42
1946 self.assertEqual(a._C__x, 42)
1947 self.assertEqual(a.x, 42)
1948 del a.x
1949 self.assertFalse(hasattr(a, "x"))
1950 self.assertFalse(hasattr(a, "_C__x"))
1951 C.x.__set__(a, 100)
1952 self.assertEqual(C.x.__get__(a), 100)
1953 C.x.__delete__(a)
1954 self.assertFalse(hasattr(a, "x"))
1955
1956 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001957 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001958
1959 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001960 self.assertIn("__doc__", attrs)
1961 self.assertIn("fget", attrs)
1962 self.assertIn("fset", attrs)
1963 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001964
1965 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001966 self.assertTrue(raw.fget is C.__dict__['getx'])
1967 self.assertTrue(raw.fset is C.__dict__['setx'])
1968 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001969
1970 for attr in "__doc__", "fget", "fset", "fdel":
1971 try:
1972 setattr(raw, attr, 42)
1973 except AttributeError as msg:
1974 if str(msg).find('readonly') < 0:
1975 self.fail("when setting readonly attr %r on a property, "
1976 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1977 else:
1978 self.fail("expected AttributeError from trying to set readonly %r "
1979 "attr on a property" % attr)
1980
1981 class D(object):
1982 __getitem__ = property(lambda s: 1/0)
1983
1984 d = D()
1985 try:
1986 for i in d:
1987 str(i)
1988 except ZeroDivisionError:
1989 pass
1990 else:
1991 self.fail("expected ZeroDivisionError from bad property")
1992
R. David Murray378c0cf2010-02-24 01:46:21 +00001993 @unittest.skipIf(sys.flags.optimize >= 2,
1994 "Docstrings are omitted with -O2 and above")
1995 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00001996 class E(object):
1997 def getter(self):
1998 "getter method"
1999 return 0
2000 def setter(self_, value):
2001 "setter method"
2002 pass
2003 prop = property(getter)
2004 self.assertEqual(prop.__doc__, "getter method")
2005 prop2 = property(fset=setter)
2006 self.assertEqual(prop2.__doc__, None)
2007
R. David Murray378c0cf2010-02-24 01:46:21 +00002008 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00002009 # this segfaulted in 2.5b2
2010 try:
2011 import _testcapi
2012 except ImportError:
2013 pass
2014 else:
2015 class X(object):
2016 p = property(_testcapi.test_with_docstring)
2017
2018 def test_properties_plus(self):
2019 class C(object):
2020 foo = property(doc="hello")
2021 @foo.getter
2022 def foo(self):
2023 return self._foo
2024 @foo.setter
2025 def foo(self, value):
2026 self._foo = abs(value)
2027 @foo.deleter
2028 def foo(self):
2029 del self._foo
2030 c = C()
2031 self.assertEqual(C.foo.__doc__, "hello")
2032 self.assertFalse(hasattr(c, "foo"))
2033 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002034 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00002035 self.assertEqual(c._foo, 42)
2036 self.assertEqual(c.foo, 42)
2037 del c.foo
2038 self.assertFalse(hasattr(c, '_foo'))
2039 self.assertFalse(hasattr(c, "foo"))
2040
2041 class D(C):
2042 @C.foo.deleter
2043 def foo(self):
2044 try:
2045 del self._foo
2046 except AttributeError:
2047 pass
2048 d = D()
2049 d.foo = 24
2050 self.assertEqual(d.foo, 24)
2051 del d.foo
2052 del d.foo
2053
2054 class E(object):
2055 @property
2056 def foo(self):
2057 return self._foo
2058 @foo.setter
2059 def foo(self, value):
2060 raise RuntimeError
2061 @foo.setter
2062 def foo(self, value):
2063 self._foo = abs(value)
2064 @foo.deleter
2065 def foo(self, value=None):
2066 del self._foo
2067
2068 e = E()
2069 e.foo = -42
2070 self.assertEqual(e.foo, 42)
2071 del e.foo
2072
2073 class F(E):
2074 @E.foo.deleter
2075 def foo(self):
2076 del self._foo
2077 @foo.setter
2078 def foo(self, value):
2079 self._foo = max(0, value)
2080 f = F()
2081 f.foo = -10
2082 self.assertEqual(f.foo, 0)
2083 del f.foo
2084
2085 def test_dict_constructors(self):
2086 # Testing dict constructor ...
2087 d = dict()
2088 self.assertEqual(d, {})
2089 d = dict({})
2090 self.assertEqual(d, {})
2091 d = dict({1: 2, 'a': 'b'})
2092 self.assertEqual(d, {1: 2, 'a': 'b'})
2093 self.assertEqual(d, dict(list(d.items())))
2094 self.assertEqual(d, dict(iter(d.items())))
2095 d = dict({'one':1, 'two':2})
2096 self.assertEqual(d, dict(one=1, two=2))
2097 self.assertEqual(d, dict(**d))
2098 self.assertEqual(d, dict({"one": 1}, two=2))
2099 self.assertEqual(d, dict([("two", 2)], one=1))
2100 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2101 self.assertEqual(d, dict(**d))
2102
2103 for badarg in 0, 0, 0j, "0", [0], (0,):
2104 try:
2105 dict(badarg)
2106 except TypeError:
2107 pass
2108 except ValueError:
2109 if badarg == "0":
2110 # It's a sequence, and its elements are also sequences (gotta
2111 # love strings <wink>), but they aren't of length 2, so this
2112 # one seemed better as a ValueError than a TypeError.
2113 pass
2114 else:
2115 self.fail("no TypeError from dict(%r)" % badarg)
2116 else:
2117 self.fail("no TypeError from dict(%r)" % badarg)
2118
2119 try:
2120 dict({}, {})
2121 except TypeError:
2122 pass
2123 else:
2124 self.fail("no TypeError from dict({}, {})")
2125
2126 class Mapping:
2127 # Lacks a .keys() method; will be added later.
2128 dict = {1:2, 3:4, 'a':1j}
2129
2130 try:
2131 dict(Mapping())
2132 except TypeError:
2133 pass
2134 else:
2135 self.fail("no TypeError from dict(incomplete mapping)")
2136
2137 Mapping.keys = lambda self: list(self.dict.keys())
2138 Mapping.__getitem__ = lambda self, i: self.dict[i]
2139 d = dict(Mapping())
2140 self.assertEqual(d, Mapping.dict)
2141
2142 # Init from sequence of iterable objects, each producing a 2-sequence.
2143 class AddressBookEntry:
2144 def __init__(self, first, last):
2145 self.first = first
2146 self.last = last
2147 def __iter__(self):
2148 return iter([self.first, self.last])
2149
2150 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2151 AddressBookEntry('Barry', 'Peters'),
2152 AddressBookEntry('Tim', 'Peters'),
2153 AddressBookEntry('Barry', 'Warsaw')])
2154 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2155
2156 d = dict(zip(range(4), range(1, 5)))
2157 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2158
2159 # Bad sequence lengths.
2160 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2161 try:
2162 dict(bad)
2163 except ValueError:
2164 pass
2165 else:
2166 self.fail("no ValueError from dict(%r)" % bad)
2167
2168 def test_dir(self):
2169 # Testing dir() ...
2170 junk = 12
2171 self.assertEqual(dir(), ['junk', 'self'])
2172 del junk
2173
2174 # Just make sure these don't blow up!
2175 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2176 dir(arg)
2177
2178 # Test dir on new-style classes. Since these have object as a
2179 # base class, a lot more gets sucked in.
2180 def interesting(strings):
2181 return [s for s in strings if not s.startswith('_')]
2182
2183 class C(object):
2184 Cdata = 1
2185 def Cmethod(self): pass
2186
2187 cstuff = ['Cdata', 'Cmethod']
2188 self.assertEqual(interesting(dir(C)), cstuff)
2189
2190 c = C()
2191 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002192 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002193
2194 c.cdata = 2
2195 c.cmethod = lambda self: 0
2196 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002197 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002198
2199 class A(C):
2200 Adata = 1
2201 def Amethod(self): pass
2202
2203 astuff = ['Adata', 'Amethod'] + cstuff
2204 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002205 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002206 a = A()
2207 self.assertEqual(interesting(dir(a)), astuff)
2208 a.adata = 42
2209 a.amethod = lambda self: 3
2210 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002211 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002212
2213 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002214 class M(type(sys)):
2215 pass
2216 minstance = M("m")
2217 minstance.b = 2
2218 minstance.a = 1
2219 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2220 self.assertEqual(names, ['a', 'b'])
2221
2222 class M2(M):
2223 def getdict(self):
2224 return "Not a dict!"
2225 __dict__ = property(getdict)
2226
2227 m2instance = M2("m2")
2228 m2instance.b = 2
2229 m2instance.a = 1
2230 self.assertEqual(m2instance.__dict__, "Not a dict!")
2231 try:
2232 dir(m2instance)
2233 except TypeError:
2234 pass
2235
2236 # Two essentially featureless objects, just inheriting stuff from
2237 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002238 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002239
2240 # Nasty test case for proxied objects
2241 class Wrapper(object):
2242 def __init__(self, obj):
2243 self.__obj = obj
2244 def __repr__(self):
2245 return "Wrapper(%s)" % repr(self.__obj)
2246 def __getitem__(self, key):
2247 return Wrapper(self.__obj[key])
2248 def __len__(self):
2249 return len(self.__obj)
2250 def __getattr__(self, name):
2251 return Wrapper(getattr(self.__obj, name))
2252
2253 class C(object):
2254 def __getclass(self):
2255 return Wrapper(type(self))
2256 __class__ = property(__getclass)
2257
2258 dir(C()) # This used to segfault
2259
2260 def test_supers(self):
2261 # Testing super...
2262
2263 class A(object):
2264 def meth(self, a):
2265 return "A(%r)" % a
2266
2267 self.assertEqual(A().meth(1), "A(1)")
2268
2269 class B(A):
2270 def __init__(self):
2271 self.__super = super(B, self)
2272 def meth(self, a):
2273 return "B(%r)" % a + self.__super.meth(a)
2274
2275 self.assertEqual(B().meth(2), "B(2)A(2)")
2276
2277 class C(A):
2278 def meth(self, a):
2279 return "C(%r)" % a + self.__super.meth(a)
2280 C._C__super = super(C)
2281
2282 self.assertEqual(C().meth(3), "C(3)A(3)")
2283
2284 class D(C, B):
2285 def meth(self, a):
2286 return "D(%r)" % a + super(D, self).meth(a)
2287
2288 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2289
2290 # Test for subclassing super
2291
2292 class mysuper(super):
2293 def __init__(self, *args):
2294 return super(mysuper, self).__init__(*args)
2295
2296 class E(D):
2297 def meth(self, a):
2298 return "E(%r)" % a + mysuper(E, self).meth(a)
2299
2300 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2301
2302 class F(E):
2303 def meth(self, a):
2304 s = self.__super # == mysuper(F, self)
2305 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2306 F._F__super = mysuper(F)
2307
2308 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2309
2310 # Make sure certain errors are raised
2311
2312 try:
2313 super(D, 42)
2314 except TypeError:
2315 pass
2316 else:
2317 self.fail("shouldn't allow super(D, 42)")
2318
2319 try:
2320 super(D, C())
2321 except TypeError:
2322 pass
2323 else:
2324 self.fail("shouldn't allow super(D, C())")
2325
2326 try:
2327 super(D).__get__(12)
2328 except TypeError:
2329 pass
2330 else:
2331 self.fail("shouldn't allow super(D).__get__(12)")
2332
2333 try:
2334 super(D).__get__(C())
2335 except TypeError:
2336 pass
2337 else:
2338 self.fail("shouldn't allow super(D).__get__(C())")
2339
2340 # Make sure data descriptors can be overridden and accessed via super
2341 # (new feature in Python 2.3)
2342
2343 class DDbase(object):
2344 def getx(self): return 42
2345 x = property(getx)
2346
2347 class DDsub(DDbase):
2348 def getx(self): return "hello"
2349 x = property(getx)
2350
2351 dd = DDsub()
2352 self.assertEqual(dd.x, "hello")
2353 self.assertEqual(super(DDsub, dd).x, 42)
2354
2355 # Ensure that super() lookup of descriptor from classmethod
2356 # works (SF ID# 743627)
2357
2358 class Base(object):
2359 aProp = property(lambda self: "foo")
2360
2361 class Sub(Base):
2362 @classmethod
2363 def test(klass):
2364 return super(Sub,klass).aProp
2365
2366 self.assertEqual(Sub.test(), Base.aProp)
2367
2368 # Verify that super() doesn't allow keyword args
2369 try:
2370 super(Base, kw=1)
2371 except TypeError:
2372 pass
2373 else:
2374 self.assertEqual("super shouldn't accept keyword args")
2375
2376 def test_basic_inheritance(self):
2377 # Testing inheritance from basic types...
2378
2379 class hexint(int):
2380 def __repr__(self):
2381 return hex(self)
2382 def __add__(self, other):
2383 return hexint(int.__add__(self, other))
2384 # (Note that overriding __radd__ doesn't work,
2385 # because the int type gets first dibs.)
2386 self.assertEqual(repr(hexint(7) + 9), "0x10")
2387 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2388 a = hexint(12345)
2389 self.assertEqual(a, 12345)
2390 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002391 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002392 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002393 self.assertTrue((+a).__class__ is int)
2394 self.assertTrue((a >> 0).__class__ is int)
2395 self.assertTrue((a << 0).__class__ is int)
2396 self.assertTrue((hexint(0) << 12).__class__ is int)
2397 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002398
2399 class octlong(int):
2400 __slots__ = []
2401 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002402 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002403 def __add__(self, other):
2404 return self.__class__(super(octlong, self).__add__(other))
2405 __radd__ = __add__
2406 self.assertEqual(str(octlong(3) + 5), "0o10")
2407 # (Note that overriding __radd__ here only seems to work
2408 # because the example uses a short int left argument.)
2409 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2410 a = octlong(12345)
2411 self.assertEqual(a, 12345)
2412 self.assertEqual(int(a), 12345)
2413 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002414 self.assertTrue(int(a).__class__ is int)
2415 self.assertTrue((+a).__class__ is int)
2416 self.assertTrue((-a).__class__ is int)
2417 self.assertTrue((-octlong(0)).__class__ is int)
2418 self.assertTrue((a >> 0).__class__ is int)
2419 self.assertTrue((a << 0).__class__ is int)
2420 self.assertTrue((a - 0).__class__ is int)
2421 self.assertTrue((a * 1).__class__ is int)
2422 self.assertTrue((a ** 1).__class__ is int)
2423 self.assertTrue((a // 1).__class__ is int)
2424 self.assertTrue((1 * a).__class__ is int)
2425 self.assertTrue((a | 0).__class__ is int)
2426 self.assertTrue((a ^ 0).__class__ is int)
2427 self.assertTrue((a & -1).__class__ is int)
2428 self.assertTrue((octlong(0) << 12).__class__ is int)
2429 self.assertTrue((octlong(0) >> 12).__class__ is int)
2430 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002431
2432 # Because octlong overrides __add__, we can't check the absence of +0
2433 # optimizations using octlong.
2434 class longclone(int):
2435 pass
2436 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002437 self.assertTrue((a + 0).__class__ is int)
2438 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002439
2440 # Check that negative clones don't segfault
2441 a = longclone(-1)
2442 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002443 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002444
2445 class precfloat(float):
2446 __slots__ = ['prec']
2447 def __init__(self, value=0.0, prec=12):
2448 self.prec = int(prec)
2449 def __repr__(self):
2450 return "%.*g" % (self.prec, self)
2451 self.assertEqual(repr(precfloat(1.1)), "1.1")
2452 a = precfloat(12345)
2453 self.assertEqual(a, 12345.0)
2454 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002455 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002456 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002457 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002458
2459 class madcomplex(complex):
2460 def __repr__(self):
2461 return "%.17gj%+.17g" % (self.imag, self.real)
2462 a = madcomplex(-3, 4)
2463 self.assertEqual(repr(a), "4j-3")
2464 base = complex(-3, 4)
2465 self.assertEqual(base.__class__, complex)
2466 self.assertEqual(a, base)
2467 self.assertEqual(complex(a), base)
2468 self.assertEqual(complex(a).__class__, complex)
2469 a = madcomplex(a) # just trying another form of the constructor
2470 self.assertEqual(repr(a), "4j-3")
2471 self.assertEqual(a, base)
2472 self.assertEqual(complex(a), base)
2473 self.assertEqual(complex(a).__class__, complex)
2474 self.assertEqual(hash(a), hash(base))
2475 self.assertEqual((+a).__class__, complex)
2476 self.assertEqual((a + 0).__class__, complex)
2477 self.assertEqual(a + 0, base)
2478 self.assertEqual((a - 0).__class__, complex)
2479 self.assertEqual(a - 0, base)
2480 self.assertEqual((a * 1).__class__, complex)
2481 self.assertEqual(a * 1, base)
2482 self.assertEqual((a / 1).__class__, complex)
2483 self.assertEqual(a / 1, base)
2484
2485 class madtuple(tuple):
2486 _rev = None
2487 def rev(self):
2488 if self._rev is not None:
2489 return self._rev
2490 L = list(self)
2491 L.reverse()
2492 self._rev = self.__class__(L)
2493 return self._rev
2494 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2495 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2496 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2497 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2498 for i in range(512):
2499 t = madtuple(range(i))
2500 u = t.rev()
2501 v = u.rev()
2502 self.assertEqual(v, t)
2503 a = madtuple((1,2,3,4,5))
2504 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002505 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002506 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002507 self.assertTrue(a[:].__class__ is tuple)
2508 self.assertTrue((a * 1).__class__ is tuple)
2509 self.assertTrue((a * 0).__class__ is tuple)
2510 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002511 a = madtuple(())
2512 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002513 self.assertTrue(tuple(a).__class__ is tuple)
2514 self.assertTrue((a + a).__class__ is tuple)
2515 self.assertTrue((a * 0).__class__ is tuple)
2516 self.assertTrue((a * 1).__class__ is tuple)
2517 self.assertTrue((a * 2).__class__ is tuple)
2518 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002519
2520 class madstring(str):
2521 _rev = None
2522 def rev(self):
2523 if self._rev is not None:
2524 return self._rev
2525 L = list(self)
2526 L.reverse()
2527 self._rev = self.__class__("".join(L))
2528 return self._rev
2529 s = madstring("abcdefghijklmnopqrstuvwxyz")
2530 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2531 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2532 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2533 for i in range(256):
2534 s = madstring("".join(map(chr, range(i))))
2535 t = s.rev()
2536 u = t.rev()
2537 self.assertEqual(u, s)
2538 s = madstring("12345")
2539 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002540 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002541
2542 base = "\x00" * 5
2543 s = madstring(base)
2544 self.assertEqual(s, base)
2545 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002546 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002547 self.assertEqual(hash(s), hash(base))
2548 self.assertEqual({s: 1}[base], 1)
2549 self.assertEqual({base: 1}[s], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002550 self.assertTrue((s + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002551 self.assertEqual(s + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002552 self.assertTrue(("" + s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002553 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002554 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002555 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002556 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002557 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002558 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002559 self.assertEqual(s * 2, base + 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:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002563 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002564 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002565 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002566 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002567 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002568 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002569 self.assertEqual(s.rstrip(), base)
2570 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002571 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002572 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002573 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002574 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002575 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002576 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002577 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002578 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002579 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002580 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002581 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002582 self.assertEqual(s.lower(), base)
2583
2584 class madunicode(str):
2585 _rev = None
2586 def rev(self):
2587 if self._rev is not None:
2588 return self._rev
2589 L = list(self)
2590 L.reverse()
2591 self._rev = self.__class__("".join(L))
2592 return self._rev
2593 u = madunicode("ABCDEF")
2594 self.assertEqual(u, "ABCDEF")
2595 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2596 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2597 base = "12345"
2598 u = madunicode(base)
2599 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002600 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002601 self.assertEqual(hash(u), hash(base))
2602 self.assertEqual({u: 1}[base], 1)
2603 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002604 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002605 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002606 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002607 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002608 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002609 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002610 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002611 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002612 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002613 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002614 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002615 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002616 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002617 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002618 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002619 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002620 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002621 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002622 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002623 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002624 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002625 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002626 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002627 self.assertEqual(u.title(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002628 self.assertTrue((u + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002629 self.assertEqual(u + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002630 self.assertTrue(("" + u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002631 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002632 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002633 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002634 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002635 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002636 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002637 self.assertEqual(u * 2, base + 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:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002641 self.assertEqual(u[0:0], "")
2642
2643 class sublist(list):
2644 pass
2645 a = sublist(range(5))
2646 self.assertEqual(a, list(range(5)))
2647 a.append("hello")
2648 self.assertEqual(a, list(range(5)) + ["hello"])
2649 a[5] = 5
2650 self.assertEqual(a, list(range(6)))
2651 a.extend(range(6, 20))
2652 self.assertEqual(a, list(range(20)))
2653 a[-5:] = []
2654 self.assertEqual(a, list(range(15)))
2655 del a[10:15]
2656 self.assertEqual(len(a), 10)
2657 self.assertEqual(a, list(range(10)))
2658 self.assertEqual(list(a), list(range(10)))
2659 self.assertEqual(a[0], 0)
2660 self.assertEqual(a[9], 9)
2661 self.assertEqual(a[-10], 0)
2662 self.assertEqual(a[-1], 9)
2663 self.assertEqual(a[:5], list(range(5)))
2664
2665 ## class CountedInput(file):
2666 ## """Counts lines read by self.readline().
2667 ##
2668 ## self.lineno is the 0-based ordinal of the last line read, up to
2669 ## a maximum of one greater than the number of lines in the file.
2670 ##
2671 ## self.ateof is true if and only if the final "" line has been read,
2672 ## at which point self.lineno stops incrementing, and further calls
2673 ## to readline() continue to return "".
2674 ## """
2675 ##
2676 ## lineno = 0
2677 ## ateof = 0
2678 ## def readline(self):
2679 ## if self.ateof:
2680 ## return ""
2681 ## s = file.readline(self)
2682 ## # Next line works too.
2683 ## # s = super(CountedInput, self).readline()
2684 ## self.lineno += 1
2685 ## if s == "":
2686 ## self.ateof = 1
2687 ## return s
2688 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002689 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002690 ## lines = ['a\n', 'b\n', 'c\n']
2691 ## try:
2692 ## f.writelines(lines)
2693 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002694 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002695 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2696 ## got = f.readline()
2697 ## self.assertEqual(expected, got)
2698 ## self.assertEqual(f.lineno, i)
2699 ## self.assertEqual(f.ateof, (i > len(lines)))
2700 ## f.close()
2701 ## finally:
2702 ## try:
2703 ## f.close()
2704 ## except:
2705 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002706 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002707
2708 def test_keywords(self):
2709 # Testing keyword args to basic type constructors ...
2710 self.assertEqual(int(x=1), 1)
2711 self.assertEqual(float(x=2), 2.0)
2712 self.assertEqual(int(x=3), 3)
2713 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2714 self.assertEqual(str(object=500), '500')
2715 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2716 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2717 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2718 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2719
2720 for constructor in (int, float, int, complex, str, str,
2721 tuple, list):
2722 try:
2723 constructor(bogus_keyword_arg=1)
2724 except TypeError:
2725 pass
2726 else:
2727 self.fail("expected TypeError from bogus keyword argument to %r"
2728 % constructor)
2729
2730 def test_str_subclass_as_dict_key(self):
2731 # Testing a str subclass used as dict key ..
2732
2733 class cistr(str):
2734 """Sublcass of str that computes __eq__ case-insensitively.
2735
2736 Also computes a hash code of the string in canonical form.
2737 """
2738
2739 def __init__(self, value):
2740 self.canonical = value.lower()
2741 self.hashcode = hash(self.canonical)
2742
2743 def __eq__(self, other):
2744 if not isinstance(other, cistr):
2745 other = cistr(other)
2746 return self.canonical == other.canonical
2747
2748 def __hash__(self):
2749 return self.hashcode
2750
2751 self.assertEqual(cistr('ABC'), 'abc')
2752 self.assertEqual('aBc', cistr('ABC'))
2753 self.assertEqual(str(cistr('ABC')), 'ABC')
2754
2755 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2756 self.assertEqual(d[cistr('one')], 1)
2757 self.assertEqual(d[cistr('tWo')], 2)
2758 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002759 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002760 self.assertEqual(d.get(cistr('thrEE')), 3)
2761
2762 def test_classic_comparisons(self):
2763 # Testing classic comparisons...
2764 class classic:
2765 pass
2766
2767 for base in (classic, int, object):
2768 class C(base):
2769 def __init__(self, value):
2770 self.value = int(value)
2771 def __eq__(self, other):
2772 if isinstance(other, C):
2773 return self.value == other.value
2774 if isinstance(other, int) or isinstance(other, int):
2775 return self.value == other
2776 return NotImplemented
2777 def __ne__(self, other):
2778 if isinstance(other, C):
2779 return self.value != other.value
2780 if isinstance(other, int) or isinstance(other, int):
2781 return self.value != other
2782 return NotImplemented
2783 def __lt__(self, other):
2784 if isinstance(other, C):
2785 return self.value < other.value
2786 if isinstance(other, int) or isinstance(other, int):
2787 return self.value < other
2788 return NotImplemented
2789 def __le__(self, other):
2790 if isinstance(other, C):
2791 return self.value <= other.value
2792 if isinstance(other, int) or isinstance(other, int):
2793 return self.value <= other
2794 return NotImplemented
2795 def __gt__(self, other):
2796 if isinstance(other, C):
2797 return self.value > other.value
2798 if isinstance(other, int) or isinstance(other, int):
2799 return self.value > other
2800 return NotImplemented
2801 def __ge__(self, other):
2802 if isinstance(other, C):
2803 return self.value >= other.value
2804 if isinstance(other, int) or isinstance(other, int):
2805 return self.value >= other
2806 return NotImplemented
2807
2808 c1 = C(1)
2809 c2 = C(2)
2810 c3 = C(3)
2811 self.assertEqual(c1, 1)
2812 c = {1: c1, 2: c2, 3: c3}
2813 for x in 1, 2, 3:
2814 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002815 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002816 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002817 eval("x %s y" % op),
2818 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002819 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002820 eval("x %s y" % op),
2821 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002822 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002823 eval("x %s y" % op),
2824 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002825
2826 def test_rich_comparisons(self):
2827 # Testing rich comparisons...
2828 class Z(complex):
2829 pass
2830 z = Z(1)
2831 self.assertEqual(z, 1+0j)
2832 self.assertEqual(1+0j, z)
2833 class ZZ(complex):
2834 def __eq__(self, other):
2835 try:
2836 return abs(self - other) <= 1e-6
2837 except:
2838 return NotImplemented
2839 zz = ZZ(1.0000003)
2840 self.assertEqual(zz, 1+0j)
2841 self.assertEqual(1+0j, zz)
2842
2843 class classic:
2844 pass
2845 for base in (classic, int, object, list):
2846 class C(base):
2847 def __init__(self, value):
2848 self.value = int(value)
2849 def __cmp__(self_, other):
2850 self.fail("shouldn't call __cmp__")
2851 def __eq__(self, other):
2852 if isinstance(other, C):
2853 return self.value == other.value
2854 if isinstance(other, int) or isinstance(other, int):
2855 return self.value == other
2856 return NotImplemented
2857 def __ne__(self, other):
2858 if isinstance(other, C):
2859 return self.value != other.value
2860 if isinstance(other, int) or isinstance(other, int):
2861 return self.value != other
2862 return NotImplemented
2863 def __lt__(self, other):
2864 if isinstance(other, C):
2865 return self.value < other.value
2866 if isinstance(other, int) or isinstance(other, int):
2867 return self.value < other
2868 return NotImplemented
2869 def __le__(self, other):
2870 if isinstance(other, C):
2871 return self.value <= other.value
2872 if isinstance(other, int) or isinstance(other, int):
2873 return self.value <= other
2874 return NotImplemented
2875 def __gt__(self, other):
2876 if isinstance(other, C):
2877 return self.value > other.value
2878 if isinstance(other, int) or isinstance(other, int):
2879 return self.value > other
2880 return NotImplemented
2881 def __ge__(self, other):
2882 if isinstance(other, C):
2883 return self.value >= other.value
2884 if isinstance(other, int) or isinstance(other, int):
2885 return self.value >= other
2886 return NotImplemented
2887 c1 = C(1)
2888 c2 = C(2)
2889 c3 = C(3)
2890 self.assertEqual(c1, 1)
2891 c = {1: c1, 2: c2, 3: c3}
2892 for x in 1, 2, 3:
2893 for y in 1, 2, 3:
2894 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002895 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002896 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002897 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002898 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002899 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002900 "x=%d, y=%d" % (x, y))
2901
2902 def test_descrdoc(self):
2903 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002904 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002905 def check(descr, what):
2906 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002907 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002908 check(complex.real, "the real part of a complex number") # member descriptor
2909
2910 def test_doc_descriptor(self):
2911 # Testing __doc__ descriptor...
2912 # SF bug 542984
2913 class DocDescr(object):
2914 def __get__(self, object, otype):
2915 if object:
2916 object = object.__class__.__name__ + ' instance'
2917 if otype:
2918 otype = otype.__name__
2919 return 'object=%s; type=%s' % (object, otype)
2920 class OldClass:
2921 __doc__ = DocDescr()
2922 class NewClass(object):
2923 __doc__ = DocDescr()
2924 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2925 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2926 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2927 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2928
2929 def test_set_class(self):
2930 # Testing __class__ assignment...
2931 class C(object): pass
2932 class D(object): pass
2933 class E(object): pass
2934 class F(D, E): pass
2935 for cls in C, D, E, F:
2936 for cls2 in C, D, E, F:
2937 x = cls()
2938 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002939 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002940 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002941 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002942 def cant(x, C):
2943 try:
2944 x.__class__ = C
2945 except TypeError:
2946 pass
2947 else:
2948 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2949 try:
2950 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002951 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002952 pass
2953 else:
2954 self.fail("shouldn't allow del %r.__class__" % x)
2955 cant(C(), list)
2956 cant(list(), C)
2957 cant(C(), 1)
2958 cant(C(), object)
2959 cant(object(), list)
2960 cant(list(), object)
2961 class Int(int): __slots__ = []
2962 cant(2, Int)
2963 cant(Int(), int)
2964 cant(True, int)
2965 cant(2, bool)
2966 o = object()
2967 cant(o, type(1))
2968 cant(o, type(None))
2969 del o
2970 class G(object):
2971 __slots__ = ["a", "b"]
2972 class H(object):
2973 __slots__ = ["b", "a"]
2974 class I(object):
2975 __slots__ = ["a", "b"]
2976 class J(object):
2977 __slots__ = ["c", "b"]
2978 class K(object):
2979 __slots__ = ["a", "b", "d"]
2980 class L(H):
2981 __slots__ = ["e"]
2982 class M(I):
2983 __slots__ = ["e"]
2984 class N(J):
2985 __slots__ = ["__weakref__"]
2986 class P(J):
2987 __slots__ = ["__dict__"]
2988 class Q(J):
2989 pass
2990 class R(J):
2991 __slots__ = ["__dict__", "__weakref__"]
2992
2993 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2994 x = cls()
2995 x.a = 1
2996 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002997 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00002998 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2999 self.assertEqual(x.a, 1)
3000 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003001 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00003002 "assigning %r as __class__ for %r silently failed" % (cls, x))
3003 self.assertEqual(x.a, 1)
3004 for cls in G, J, K, L, M, N, P, R, list, Int:
3005 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3006 if cls is cls2:
3007 continue
3008 cant(cls(), cls2)
3009
Benjamin Peterson193152c2009-04-25 01:08:45 +00003010 # Issue5283: when __class__ changes in __del__, the wrong
3011 # type gets DECREF'd.
3012 class O(object):
3013 pass
3014 class A(object):
3015 def __del__(self):
3016 self.__class__ = O
3017 l = [A() for x in range(100)]
3018 del l
3019
Georg Brandl479a7e72008-02-05 18:13:15 +00003020 def test_set_dict(self):
3021 # Testing __dict__ assignment...
3022 class C(object): pass
3023 a = C()
3024 a.__dict__ = {'b': 1}
3025 self.assertEqual(a.b, 1)
3026 def cant(x, dict):
3027 try:
3028 x.__dict__ = dict
3029 except (AttributeError, TypeError):
3030 pass
3031 else:
3032 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3033 cant(a, None)
3034 cant(a, [])
3035 cant(a, 1)
3036 del a.__dict__ # Deleting __dict__ is allowed
3037
3038 class Base(object):
3039 pass
3040 def verify_dict_readonly(x):
3041 """
3042 x has to be an instance of a class inheriting from Base.
3043 """
3044 cant(x, {})
3045 try:
3046 del x.__dict__
3047 except (AttributeError, TypeError):
3048 pass
3049 else:
3050 self.fail("shouldn't allow del %r.__dict__" % x)
3051 dict_descr = Base.__dict__["__dict__"]
3052 try:
3053 dict_descr.__set__(x, {})
3054 except (AttributeError, TypeError):
3055 pass
3056 else:
3057 self.fail("dict_descr allowed access to %r's dict" % x)
3058
3059 # Classes don't allow __dict__ assignment and have readonly dicts
3060 class Meta1(type, Base):
3061 pass
3062 class Meta2(Base, type):
3063 pass
3064 class D(object, metaclass=Meta1):
3065 pass
3066 class E(object, metaclass=Meta2):
3067 pass
3068 for cls in C, D, E:
3069 verify_dict_readonly(cls)
3070 class_dict = cls.__dict__
3071 try:
3072 class_dict["spam"] = "eggs"
3073 except TypeError:
3074 pass
3075 else:
3076 self.fail("%r's __dict__ can be modified" % cls)
3077
3078 # Modules also disallow __dict__ assignment
3079 class Module1(types.ModuleType, Base):
3080 pass
3081 class Module2(Base, types.ModuleType):
3082 pass
3083 for ModuleType in Module1, Module2:
3084 mod = ModuleType("spam")
3085 verify_dict_readonly(mod)
3086 mod.__dict__["spam"] = "eggs"
3087
3088 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00003089 # (at least not any more than regular exception's __dict__ can
3090 # be deleted; on CPython it is not the case, whereas on PyPy they
3091 # can, just like any other new-style instance's __dict__.)
3092 def can_delete_dict(e):
3093 try:
3094 del e.__dict__
3095 except (TypeError, AttributeError):
3096 return False
3097 else:
3098 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00003099 class Exception1(Exception, Base):
3100 pass
3101 class Exception2(Base, Exception):
3102 pass
3103 for ExceptionType in Exception, Exception1, Exception2:
3104 e = ExceptionType()
3105 e.__dict__ = {"a": 1}
3106 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003107 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00003108
3109 def test_pickles(self):
3110 # Testing pickling and copying new-style classes and objects...
3111 import pickle
3112
3113 def sorteditems(d):
3114 L = list(d.items())
3115 L.sort()
3116 return L
3117
3118 global C
3119 class C(object):
3120 def __init__(self, a, b):
3121 super(C, self).__init__()
3122 self.a = a
3123 self.b = b
3124 def __repr__(self):
3125 return "C(%r, %r)" % (self.a, self.b)
3126
3127 global C1
3128 class C1(list):
3129 def __new__(cls, a, b):
3130 return super(C1, cls).__new__(cls)
3131 def __getnewargs__(self):
3132 return (self.a, self.b)
3133 def __init__(self, a, b):
3134 self.a = a
3135 self.b = b
3136 def __repr__(self):
3137 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3138
3139 global C2
3140 class C2(int):
3141 def __new__(cls, a, b, val=0):
3142 return super(C2, cls).__new__(cls, val)
3143 def __getnewargs__(self):
3144 return (self.a, self.b, int(self))
3145 def __init__(self, a, b, val=0):
3146 self.a = a
3147 self.b = b
3148 def __repr__(self):
3149 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3150
3151 global C3
3152 class C3(object):
3153 def __init__(self, foo):
3154 self.foo = foo
3155 def __getstate__(self):
3156 return self.foo
3157 def __setstate__(self, foo):
3158 self.foo = foo
3159
3160 global C4classic, C4
3161 class C4classic: # classic
3162 pass
3163 class C4(C4classic, object): # mixed inheritance
3164 pass
3165
Guido van Rossum3926a632001-09-25 16:25:58 +00003166 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00003167 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003168 s = pickle.dumps(cls, bin)
3169 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003170 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003171
3172 a = C1(1, 2); a.append(42); a.append(24)
3173 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003174 s = pickle.dumps((a, b), bin)
3175 x, y = pickle.loads(s)
3176 self.assertEqual(x.__class__, a.__class__)
3177 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3178 self.assertEqual(y.__class__, b.__class__)
3179 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3180 self.assertEqual(repr(x), repr(a))
3181 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003182 # Test for __getstate__ and __setstate__ on new style class
3183 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003184 s = pickle.dumps(u, bin)
3185 v = pickle.loads(s)
3186 self.assertEqual(u.__class__, v.__class__)
3187 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003188 # Test for picklability of hybrid class
3189 u = C4()
3190 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003191 s = pickle.dumps(u, bin)
3192 v = pickle.loads(s)
3193 self.assertEqual(u.__class__, v.__class__)
3194 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003195
Georg Brandl479a7e72008-02-05 18:13:15 +00003196 # Testing copy.deepcopy()
3197 import copy
3198 for cls in C, C1, C2:
3199 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003200 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003201
Georg Brandl479a7e72008-02-05 18:13:15 +00003202 a = C1(1, 2); a.append(42); a.append(24)
3203 b = C2("hello", "world", 42)
3204 x, y = copy.deepcopy((a, b))
3205 self.assertEqual(x.__class__, a.__class__)
3206 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3207 self.assertEqual(y.__class__, b.__class__)
3208 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3209 self.assertEqual(repr(x), repr(a))
3210 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003211
Georg Brandl479a7e72008-02-05 18:13:15 +00003212 def test_pickle_slots(self):
3213 # Testing pickling of classes with __slots__ ...
3214 import pickle
3215 # Pickling of classes with __slots__ but without __getstate__ should fail
3216 # (if using protocol 0 or 1)
3217 global B, C, D, E
3218 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003219 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003220 for base in [object, B]:
3221 class C(base):
3222 __slots__ = ['a']
3223 class D(C):
3224 pass
3225 try:
3226 pickle.dumps(C(), 0)
3227 except TypeError:
3228 pass
3229 else:
3230 self.fail("should fail: pickle C instance - %s" % base)
3231 try:
3232 pickle.dumps(C(), 0)
3233 except TypeError:
3234 pass
3235 else:
3236 self.fail("should fail: pickle D instance - %s" % base)
3237 # Give C a nice generic __getstate__ and __setstate__
3238 class C(base):
3239 __slots__ = ['a']
3240 def __getstate__(self):
3241 try:
3242 d = self.__dict__.copy()
3243 except AttributeError:
3244 d = {}
3245 for cls in self.__class__.__mro__:
3246 for sn in cls.__dict__.get('__slots__', ()):
3247 try:
3248 d[sn] = getattr(self, sn)
3249 except AttributeError:
3250 pass
3251 return d
3252 def __setstate__(self, d):
3253 for k, v in list(d.items()):
3254 setattr(self, k, v)
3255 class D(C):
3256 pass
3257 # Now it should work
3258 x = C()
3259 y = pickle.loads(pickle.dumps(x))
3260 self.assertEqual(hasattr(y, 'a'), 0)
3261 x.a = 42
3262 y = pickle.loads(pickle.dumps(x))
3263 self.assertEqual(y.a, 42)
3264 x = D()
3265 x.a = 42
3266 x.b = 100
3267 y = pickle.loads(pickle.dumps(x))
3268 self.assertEqual(y.a + y.b, 142)
3269 # A subclass that adds a slot should also work
3270 class E(C):
3271 __slots__ = ['b']
3272 x = E()
3273 x.a = 42
3274 x.b = "foo"
3275 y = pickle.loads(pickle.dumps(x))
3276 self.assertEqual(y.a, x.a)
3277 self.assertEqual(y.b, x.b)
3278
3279 def test_binary_operator_override(self):
3280 # Testing overrides of binary operations...
3281 class I(int):
3282 def __repr__(self):
3283 return "I(%r)" % int(self)
3284 def __add__(self, other):
3285 return I(int(self) + int(other))
3286 __radd__ = __add__
3287 def __pow__(self, other, mod=None):
3288 if mod is None:
3289 return I(pow(int(self), int(other)))
3290 else:
3291 return I(pow(int(self), int(other), int(mod)))
3292 def __rpow__(self, other, mod=None):
3293 if mod is None:
3294 return I(pow(int(other), int(self), mod))
3295 else:
3296 return I(pow(int(other), int(self), int(mod)))
3297
3298 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3299 self.assertEqual(repr(I(1) + 2), "I(3)")
3300 self.assertEqual(repr(1 + I(2)), "I(3)")
3301 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3302 self.assertEqual(repr(2 ** I(3)), "I(8)")
3303 self.assertEqual(repr(I(2) ** 3), "I(8)")
3304 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3305 class S(str):
3306 def __eq__(self, other):
3307 return self.lower() == other.lower()
3308
3309 def test_subclass_propagation(self):
3310 # Testing propagation of slot functions to subclasses...
3311 class A(object):
3312 pass
3313 class B(A):
3314 pass
3315 class C(A):
3316 pass
3317 class D(B, C):
3318 pass
3319 d = D()
3320 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3321 A.__hash__ = lambda self: 42
3322 self.assertEqual(hash(d), 42)
3323 C.__hash__ = lambda self: 314
3324 self.assertEqual(hash(d), 314)
3325 B.__hash__ = lambda self: 144
3326 self.assertEqual(hash(d), 144)
3327 D.__hash__ = lambda self: 100
3328 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003329 D.__hash__ = None
3330 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003331 del D.__hash__
3332 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003333 B.__hash__ = None
3334 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003335 del B.__hash__
3336 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003337 C.__hash__ = None
3338 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003339 del C.__hash__
3340 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003341 A.__hash__ = None
3342 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003343 del A.__hash__
3344 self.assertEqual(hash(d), orig_hash)
3345 d.foo = 42
3346 d.bar = 42
3347 self.assertEqual(d.foo, 42)
3348 self.assertEqual(d.bar, 42)
3349 def __getattribute__(self, name):
3350 if name == "foo":
3351 return 24
3352 return object.__getattribute__(self, name)
3353 A.__getattribute__ = __getattribute__
3354 self.assertEqual(d.foo, 24)
3355 self.assertEqual(d.bar, 42)
3356 def __getattr__(self, name):
3357 if name in ("spam", "foo", "bar"):
3358 return "hello"
3359 raise AttributeError(name)
3360 B.__getattr__ = __getattr__
3361 self.assertEqual(d.spam, "hello")
3362 self.assertEqual(d.foo, 24)
3363 self.assertEqual(d.bar, 42)
3364 del A.__getattribute__
3365 self.assertEqual(d.foo, 42)
3366 del d.foo
3367 self.assertEqual(d.foo, "hello")
3368 self.assertEqual(d.bar, 42)
3369 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003370 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003371 d.foo
3372 except AttributeError:
3373 pass
3374 else:
3375 self.fail("d.foo should be undefined now")
3376
3377 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003378 class A(object):
3379 pass
3380 class B(A):
3381 pass
3382 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003383 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003384 A.__setitem__ = lambda *a: None # crash
3385
3386 def test_buffer_inheritance(self):
3387 # Testing that buffer interface is inherited ...
3388
3389 import binascii
3390 # SF bug [#470040] ParseTuple t# vs subclasses.
3391
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003392 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003393 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003394 base = b'abc'
3395 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003396 # b2a_hex uses the buffer interface to get its argument's value, via
3397 # PyArg_ParseTuple 't#' code.
3398 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3399
Georg Brandl479a7e72008-02-05 18:13:15 +00003400 class MyInt(int):
3401 pass
3402 m = MyInt(42)
3403 try:
3404 binascii.b2a_hex(m)
3405 self.fail('subclass of int should not have a buffer interface')
3406 except TypeError:
3407 pass
3408
3409 def test_str_of_str_subclass(self):
3410 # Testing __str__ defined in subclass of str ...
3411 import binascii
3412 import io
3413
3414 class octetstring(str):
3415 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003416 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003417 def __repr__(self):
3418 return self + " repr"
3419
3420 o = octetstring('A')
3421 self.assertEqual(type(o), octetstring)
3422 self.assertEqual(type(str(o)), str)
3423 self.assertEqual(type(repr(o)), str)
3424 self.assertEqual(ord(o), 0x41)
3425 self.assertEqual(str(o), '41')
3426 self.assertEqual(repr(o), 'A repr')
3427 self.assertEqual(o.__str__(), '41')
3428 self.assertEqual(o.__repr__(), 'A repr')
3429
3430 capture = io.StringIO()
3431 # Calling str() or not exercises different internal paths.
3432 print(o, file=capture)
3433 print(str(o), file=capture)
3434 self.assertEqual(capture.getvalue(), '41\n41\n')
3435 capture.close()
3436
3437 def test_keyword_arguments(self):
3438 # Testing keyword arguments to __init__, __call__...
3439 def f(a): return a
3440 self.assertEqual(f.__call__(a=42), 42)
3441 a = []
3442 list.__init__(a, sequence=[0, 1, 2])
3443 self.assertEqual(a, [0, 1, 2])
3444
3445 def test_recursive_call(self):
3446 # Testing recursive __call__() by setting to instance of class...
3447 class A(object):
3448 pass
3449
3450 A.__call__ = A()
3451 try:
3452 A()()
3453 except RuntimeError:
3454 pass
3455 else:
3456 self.fail("Recursion limit should have been reached for __call__()")
3457
3458 def test_delete_hook(self):
3459 # Testing __del__ hook...
3460 log = []
3461 class C(object):
3462 def __del__(self):
3463 log.append(1)
3464 c = C()
3465 self.assertEqual(log, [])
3466 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003467 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003468 self.assertEqual(log, [1])
3469
3470 class D(object): pass
3471 d = D()
3472 try: del d[0]
3473 except TypeError: pass
3474 else: self.fail("invalid del() didn't raise TypeError")
3475
3476 def test_hash_inheritance(self):
3477 # Testing hash of mutable subclasses...
3478
3479 class mydict(dict):
3480 pass
3481 d = mydict()
3482 try:
3483 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003484 except TypeError:
3485 pass
3486 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003487 self.fail("hash() of dict subclass should fail")
3488
3489 class mylist(list):
3490 pass
3491 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003492 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003493 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003494 except TypeError:
3495 pass
3496 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003497 self.fail("hash() of list subclass should fail")
3498
3499 def test_str_operations(self):
3500 try: 'a' + 5
3501 except TypeError: pass
3502 else: self.fail("'' + 5 doesn't raise TypeError")
3503
3504 try: ''.split('')
3505 except ValueError: pass
3506 else: self.fail("''.split('') doesn't raise ValueError")
3507
3508 try: ''.join([0])
3509 except TypeError: pass
3510 else: self.fail("''.join([0]) doesn't raise TypeError")
3511
3512 try: ''.rindex('5')
3513 except ValueError: pass
3514 else: self.fail("''.rindex('5') doesn't raise ValueError")
3515
3516 try: '%(n)s' % None
3517 except TypeError: pass
3518 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3519
3520 try: '%(n' % {}
3521 except ValueError: pass
3522 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3523
3524 try: '%*s' % ('abc')
3525 except TypeError: pass
3526 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3527
3528 try: '%*.*s' % ('abc', 5)
3529 except TypeError: pass
3530 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3531
3532 try: '%s' % (1, 2)
3533 except TypeError: pass
3534 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3535
3536 try: '%' % None
3537 except ValueError: pass
3538 else: self.fail("'%' % None doesn't raise ValueError")
3539
3540 self.assertEqual('534253'.isdigit(), 1)
3541 self.assertEqual('534253x'.isdigit(), 0)
3542 self.assertEqual('%c' % 5, '\x05')
3543 self.assertEqual('%c' % '5', '5')
3544
3545 def test_deepcopy_recursive(self):
3546 # Testing deepcopy of recursive objects...
3547 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003548 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003549 a = Node()
3550 b = Node()
3551 a.b = b
3552 b.a = a
3553 z = deepcopy(a) # This blew up before
3554
3555 def test_unintialized_modules(self):
3556 # Testing uninitialized module objects...
3557 from types import ModuleType as M
3558 m = M.__new__(M)
3559 str(m)
3560 self.assertEqual(hasattr(m, "__name__"), 0)
3561 self.assertEqual(hasattr(m, "__file__"), 0)
3562 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003563 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003564 m.foo = 1
3565 self.assertEqual(m.__dict__, {"foo": 1})
3566
3567 def test_funny_new(self):
3568 # Testing __new__ returning something unexpected...
3569 class C(object):
3570 def __new__(cls, arg):
3571 if isinstance(arg, str): return [1, 2, 3]
3572 elif isinstance(arg, int): return object.__new__(D)
3573 else: return object.__new__(cls)
3574 class D(C):
3575 def __init__(self, arg):
3576 self.foo = arg
3577 self.assertEqual(C("1"), [1, 2, 3])
3578 self.assertEqual(D("1"), [1, 2, 3])
3579 d = D(None)
3580 self.assertEqual(d.foo, None)
3581 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003582 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003583 self.assertEqual(d.foo, 1)
3584 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003585 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003586 self.assertEqual(d.foo, 1)
3587
3588 def test_imul_bug(self):
3589 # Testing for __imul__ problems...
3590 # SF bug 544647
3591 class C(object):
3592 def __imul__(self, other):
3593 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003594 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003595 y = x
3596 y *= 1.0
3597 self.assertEqual(y, (x, 1.0))
3598 y = x
3599 y *= 2
3600 self.assertEqual(y, (x, 2))
3601 y = x
3602 y *= 3
3603 self.assertEqual(y, (x, 3))
3604 y = x
3605 y *= 1<<100
3606 self.assertEqual(y, (x, 1<<100))
3607 y = x
3608 y *= None
3609 self.assertEqual(y, (x, None))
3610 y = x
3611 y *= "foo"
3612 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003613
Georg Brandl479a7e72008-02-05 18:13:15 +00003614 def test_copy_setstate(self):
3615 # Testing that copy.*copy() correctly uses __setstate__...
3616 import copy
3617 class C(object):
3618 def __init__(self, foo=None):
3619 self.foo = foo
3620 self.__foo = foo
3621 def setfoo(self, foo=None):
3622 self.foo = foo
3623 def getfoo(self):
3624 return self.__foo
3625 def __getstate__(self):
3626 return [self.foo]
3627 def __setstate__(self_, lst):
3628 self.assertEqual(len(lst), 1)
3629 self_.__foo = self_.foo = lst[0]
3630 a = C(42)
3631 a.setfoo(24)
3632 self.assertEqual(a.foo, 24)
3633 self.assertEqual(a.getfoo(), 42)
3634 b = copy.copy(a)
3635 self.assertEqual(b.foo, 24)
3636 self.assertEqual(b.getfoo(), 24)
3637 b = copy.deepcopy(a)
3638 self.assertEqual(b.foo, 24)
3639 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003640
Georg Brandl479a7e72008-02-05 18:13:15 +00003641 def test_slices(self):
3642 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003643
Georg Brandl479a7e72008-02-05 18:13:15 +00003644 # Strings
3645 self.assertEqual("hello"[:4], "hell")
3646 self.assertEqual("hello"[slice(4)], "hell")
3647 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3648 class S(str):
3649 def __getitem__(self, x):
3650 return str.__getitem__(self, x)
3651 self.assertEqual(S("hello")[:4], "hell")
3652 self.assertEqual(S("hello")[slice(4)], "hell")
3653 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3654 # Tuples
3655 self.assertEqual((1,2,3)[:2], (1,2))
3656 self.assertEqual((1,2,3)[slice(2)], (1,2))
3657 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3658 class T(tuple):
3659 def __getitem__(self, x):
3660 return tuple.__getitem__(self, x)
3661 self.assertEqual(T((1,2,3))[:2], (1,2))
3662 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3663 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3664 # Lists
3665 self.assertEqual([1,2,3][:2], [1,2])
3666 self.assertEqual([1,2,3][slice(2)], [1,2])
3667 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3668 class L(list):
3669 def __getitem__(self, x):
3670 return list.__getitem__(self, x)
3671 self.assertEqual(L([1,2,3])[:2], [1,2])
3672 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3673 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3674 # Now do lists and __setitem__
3675 a = L([1,2,3])
3676 a[slice(1, 3)] = [3,2]
3677 self.assertEqual(a, [1,3,2])
3678 a[slice(0, 2, 1)] = [3,1]
3679 self.assertEqual(a, [3,1,2])
3680 a.__setitem__(slice(1, 3), [2,1])
3681 self.assertEqual(a, [3,2,1])
3682 a.__setitem__(slice(0, 2, 1), [2,3])
3683 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003684
Georg Brandl479a7e72008-02-05 18:13:15 +00003685 def test_subtype_resurrection(self):
3686 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003687
Georg Brandl479a7e72008-02-05 18:13:15 +00003688 class C(object):
3689 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003690
Georg Brandl479a7e72008-02-05 18:13:15 +00003691 def __del__(self):
3692 # resurrect the instance
3693 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003694
Georg Brandl479a7e72008-02-05 18:13:15 +00003695 c = C()
3696 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003697
Benjamin Petersone549ead2009-03-28 21:42:05 +00003698 # The most interesting thing here is whether this blows up, due to
3699 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3700 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003701 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003702
Georg Brandl479a7e72008-02-05 18:13:15 +00003703 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003704 # the last container slot works: that will attempt to delete c again,
3705 # which will cause c to get appended back to the container again
3706 # "during" the del. (On non-CPython implementations, however, __del__
3707 # is typically not called again.)
3708 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003709 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003710 del C.container[-1]
3711 if support.check_impl_detail():
3712 support.gc_collect()
3713 self.assertEqual(len(C.container), 1)
3714 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003715
Georg Brandl479a7e72008-02-05 18:13:15 +00003716 # Make c mortal again, so that the test framework with -l doesn't report
3717 # it as a leak.
3718 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003719
Georg Brandl479a7e72008-02-05 18:13:15 +00003720 def test_slots_trash(self):
3721 # Testing slot trash...
3722 # Deallocating deeply nested slotted trash caused stack overflows
3723 class trash(object):
3724 __slots__ = ['x']
3725 def __init__(self, x):
3726 self.x = x
3727 o = None
3728 for i in range(50000):
3729 o = trash(o)
3730 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003731
Georg Brandl479a7e72008-02-05 18:13:15 +00003732 def test_slots_multiple_inheritance(self):
3733 # SF bug 575229, multiple inheritance w/ slots dumps core
3734 class A(object):
3735 __slots__=()
3736 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003737 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003738 class C(A,B) :
3739 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003740 if support.check_impl_detail():
3741 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003742 self.assertTrue(hasattr(C, '__dict__'))
3743 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003744 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003745
Georg Brandl479a7e72008-02-05 18:13:15 +00003746 def test_rmul(self):
3747 # Testing correct invocation of __rmul__...
3748 # SF patch 592646
3749 class C(object):
3750 def __mul__(self, other):
3751 return "mul"
3752 def __rmul__(self, other):
3753 return "rmul"
3754 a = C()
3755 self.assertEqual(a*2, "mul")
3756 self.assertEqual(a*2.2, "mul")
3757 self.assertEqual(2*a, "rmul")
3758 self.assertEqual(2.2*a, "rmul")
3759
3760 def test_ipow(self):
3761 # Testing correct invocation of __ipow__...
3762 # [SF bug 620179]
3763 class C(object):
3764 def __ipow__(self, other):
3765 pass
3766 a = C()
3767 a **= 2
3768
3769 def test_mutable_bases(self):
3770 # Testing mutable bases...
3771
3772 # stuff that should work:
3773 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003774 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003775 class C2(object):
3776 def __getattribute__(self, attr):
3777 if attr == 'a':
3778 return 2
3779 else:
3780 return super(C2, self).__getattribute__(attr)
3781 def meth(self):
3782 return 1
3783 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003784 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003785 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003786 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003787 d = D()
3788 e = E()
3789 D.__bases__ = (C,)
3790 D.__bases__ = (C2,)
3791 self.assertEqual(d.meth(), 1)
3792 self.assertEqual(e.meth(), 1)
3793 self.assertEqual(d.a, 2)
3794 self.assertEqual(e.a, 2)
3795 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003796
Georg Brandl479a7e72008-02-05 18:13:15 +00003797 try:
3798 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003799 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003800 pass
3801 else:
3802 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003803
Georg Brandl479a7e72008-02-05 18:13:15 +00003804 try:
3805 D.__bases__ = ()
3806 except TypeError as msg:
3807 if str(msg) == "a new-style class can't have only classic bases":
3808 self.fail("wrong error message for .__bases__ = ()")
3809 else:
3810 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003811
Georg Brandl479a7e72008-02-05 18:13:15 +00003812 try:
3813 D.__bases__ = (D,)
3814 except TypeError:
3815 pass
3816 else:
3817 # actually, we'll have crashed by here...
3818 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003819
Georg Brandl479a7e72008-02-05 18:13:15 +00003820 try:
3821 D.__bases__ = (C, C)
3822 except TypeError:
3823 pass
3824 else:
3825 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003826
Georg Brandl479a7e72008-02-05 18:13:15 +00003827 try:
3828 D.__bases__ = (E,)
3829 except TypeError:
3830 pass
3831 else:
3832 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003833
Benjamin Petersonae937c02009-04-18 20:54:08 +00003834 def test_builtin_bases(self):
3835 # Make sure all the builtin types can have their base queried without
3836 # segfaulting. See issue #5787.
3837 builtin_types = [tp for tp in builtins.__dict__.values()
3838 if isinstance(tp, type)]
3839 for tp in builtin_types:
3840 object.__getattribute__(tp, "__bases__")
3841 if tp is not object:
3842 self.assertEqual(len(tp.__bases__), 1, tp)
3843
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003844 class L(list):
3845 pass
3846
3847 class C(object):
3848 pass
3849
3850 class D(C):
3851 pass
3852
3853 try:
3854 L.__bases__ = (dict,)
3855 except TypeError:
3856 pass
3857 else:
3858 self.fail("shouldn't turn list subclass into dict subclass")
3859
3860 try:
3861 list.__bases__ = (dict,)
3862 except TypeError:
3863 pass
3864 else:
3865 self.fail("shouldn't be able to assign to list.__bases__")
3866
3867 try:
3868 D.__bases__ = (C, list)
3869 except TypeError:
3870 pass
3871 else:
3872 assert 0, "best_base calculation found wanting"
3873
Benjamin Petersonae937c02009-04-18 20:54:08 +00003874
Georg Brandl479a7e72008-02-05 18:13:15 +00003875 def test_mutable_bases_with_failing_mro(self):
3876 # Testing mutable bases with failing mro...
3877 class WorkOnce(type):
3878 def __new__(self, name, bases, ns):
3879 self.flag = 0
3880 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3881 def mro(self):
3882 if self.flag > 0:
3883 raise RuntimeError("bozo")
3884 else:
3885 self.flag += 1
3886 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003887
Georg Brandl479a7e72008-02-05 18:13:15 +00003888 class WorkAlways(type):
3889 def mro(self):
3890 # this is here to make sure that .mro()s aren't called
3891 # with an exception set (which was possible at one point).
3892 # An error message will be printed in a debug build.
3893 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003894 return type.mro(self)
3895
Georg Brandl479a7e72008-02-05 18:13:15 +00003896 class C(object):
3897 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003898
Georg Brandl479a7e72008-02-05 18:13:15 +00003899 class C2(object):
3900 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003901
Georg Brandl479a7e72008-02-05 18:13:15 +00003902 class D(C):
3903 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003904
Georg Brandl479a7e72008-02-05 18:13:15 +00003905 class E(D):
3906 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003907
Georg Brandl479a7e72008-02-05 18:13:15 +00003908 class F(D, metaclass=WorkOnce):
3909 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003910
Georg Brandl479a7e72008-02-05 18:13:15 +00003911 class G(D, metaclass=WorkAlways):
3912 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003913
Georg Brandl479a7e72008-02-05 18:13:15 +00003914 # Immediate subclasses have their mro's adjusted in alphabetical
3915 # order, so E's will get adjusted before adjusting F's fails. We
3916 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003917
Georg Brandl479a7e72008-02-05 18:13:15 +00003918 E_mro_before = E.__mro__
3919 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003920
Armin Rigofd163f92005-12-29 15:59:19 +00003921 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003922 D.__bases__ = (C2,)
3923 except RuntimeError:
3924 self.assertEqual(E.__mro__, E_mro_before)
3925 self.assertEqual(D.__mro__, D_mro_before)
3926 else:
3927 self.fail("exception not propagated")
3928
3929 def test_mutable_bases_catch_mro_conflict(self):
3930 # Testing mutable bases catch mro conflict...
3931 class A(object):
3932 pass
3933
3934 class B(object):
3935 pass
3936
3937 class C(A, B):
3938 pass
3939
3940 class D(A, B):
3941 pass
3942
3943 class E(C, D):
3944 pass
3945
3946 try:
3947 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003948 except TypeError:
3949 pass
3950 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003951 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003952
Georg Brandl479a7e72008-02-05 18:13:15 +00003953 def test_mutable_names(self):
3954 # Testing mutable names...
3955 class C(object):
3956 pass
3957
3958 # C.__module__ could be 'test_descr' or '__main__'
3959 mod = C.__module__
3960
3961 C.__name__ = 'D'
3962 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3963
3964 C.__name__ = 'D.E'
3965 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3966
3967 def test_subclass_right_op(self):
3968 # Testing correct dispatch of subclass overloading __r<op>__...
3969
3970 # This code tests various cases where right-dispatch of a subclass
3971 # should be preferred over left-dispatch of a base class.
3972
3973 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3974
3975 class B(int):
3976 def __floordiv__(self, other):
3977 return "B.__floordiv__"
3978 def __rfloordiv__(self, other):
3979 return "B.__rfloordiv__"
3980
3981 self.assertEqual(B(1) // 1, "B.__floordiv__")
3982 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3983
3984 # Case 2: subclass of object; this is just the baseline for case 3
3985
3986 class C(object):
3987 def __floordiv__(self, other):
3988 return "C.__floordiv__"
3989 def __rfloordiv__(self, other):
3990 return "C.__rfloordiv__"
3991
3992 self.assertEqual(C() // 1, "C.__floordiv__")
3993 self.assertEqual(1 // C(), "C.__rfloordiv__")
3994
3995 # Case 3: subclass of new-style class; here it gets interesting
3996
3997 class D(C):
3998 def __floordiv__(self, other):
3999 return "D.__floordiv__"
4000 def __rfloordiv__(self, other):
4001 return "D.__rfloordiv__"
4002
4003 self.assertEqual(D() // C(), "D.__floordiv__")
4004 self.assertEqual(C() // D(), "D.__rfloordiv__")
4005
4006 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4007
4008 class E(C):
4009 pass
4010
4011 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4012
4013 self.assertEqual(E() // 1, "C.__floordiv__")
4014 self.assertEqual(1 // E(), "C.__rfloordiv__")
4015 self.assertEqual(E() // C(), "C.__floordiv__")
4016 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4017
Benjamin Petersone549ead2009-03-28 21:42:05 +00004018 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00004019 def test_meth_class_get(self):
4020 # Testing __get__ method of METH_CLASS C methods...
4021 # Full coverage of descrobject.c::classmethod_get()
4022
4023 # Baseline
4024 arg = [1, 2, 3]
4025 res = {1: None, 2: None, 3: None}
4026 self.assertEqual(dict.fromkeys(arg), res)
4027 self.assertEqual({}.fromkeys(arg), res)
4028
4029 # Now get the descriptor
4030 descr = dict.__dict__["fromkeys"]
4031
4032 # More baseline using the descriptor directly
4033 self.assertEqual(descr.__get__(None, dict)(arg), res)
4034 self.assertEqual(descr.__get__({})(arg), res)
4035
4036 # Now check various error cases
4037 try:
4038 descr.__get__(None, None)
4039 except TypeError:
4040 pass
4041 else:
4042 self.fail("shouldn't have allowed descr.__get__(None, None)")
4043 try:
4044 descr.__get__(42)
4045 except TypeError:
4046 pass
4047 else:
4048 self.fail("shouldn't have allowed descr.__get__(42)")
4049 try:
4050 descr.__get__(None, 42)
4051 except TypeError:
4052 pass
4053 else:
4054 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4055 try:
4056 descr.__get__(None, int)
4057 except TypeError:
4058 pass
4059 else:
4060 self.fail("shouldn't have allowed descr.__get__(None, int)")
4061
4062 def test_isinst_isclass(self):
4063 # Testing proxy isinstance() and isclass()...
4064 class Proxy(object):
4065 def __init__(self, obj):
4066 self.__obj = obj
4067 def __getattribute__(self, name):
4068 if name.startswith("_Proxy__"):
4069 return object.__getattribute__(self, name)
4070 else:
4071 return getattr(self.__obj, name)
4072 # Test with a classic class
4073 class C:
4074 pass
4075 a = C()
4076 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004077 self.assertIsInstance(a, C) # Baseline
4078 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004079 # Test with a classic subclass
4080 class D(C):
4081 pass
4082 a = D()
4083 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004084 self.assertIsInstance(a, C) # Baseline
4085 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004086 # Test with a new-style class
4087 class C(object):
4088 pass
4089 a = C()
4090 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004091 self.assertIsInstance(a, C) # Baseline
4092 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004093 # Test with a new-style subclass
4094 class D(C):
4095 pass
4096 a = D()
4097 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00004098 self.assertIsInstance(a, C) # Baseline
4099 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00004100
4101 def test_proxy_super(self):
4102 # Testing super() for a proxy object...
4103 class Proxy(object):
4104 def __init__(self, obj):
4105 self.__obj = obj
4106 def __getattribute__(self, name):
4107 if name.startswith("_Proxy__"):
4108 return object.__getattribute__(self, name)
4109 else:
4110 return getattr(self.__obj, name)
4111
4112 class B(object):
4113 def f(self):
4114 return "B.f"
4115
4116 class C(B):
4117 def f(self):
4118 return super(C, self).f() + "->C.f"
4119
4120 obj = C()
4121 p = Proxy(obj)
4122 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4123
4124 def test_carloverre(self):
4125 # Testing prohibition of Carlo Verre's hack...
4126 try:
4127 object.__setattr__(str, "foo", 42)
4128 except TypeError:
4129 pass
4130 else:
Ezio Melotti13925002011-03-16 11:05:33 +02004131 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00004132 try:
4133 object.__delattr__(str, "lower")
4134 except TypeError:
4135 pass
4136 else:
4137 self.fail("Carlo Verre __delattr__ succeeded!")
4138
4139 def test_weakref_segfault(self):
4140 # Testing weakref segfault...
4141 # SF 742911
4142 import weakref
4143
4144 class Provoker:
4145 def __init__(self, referrent):
4146 self.ref = weakref.ref(referrent)
4147
4148 def __del__(self):
4149 x = self.ref()
4150
4151 class Oops(object):
4152 pass
4153
4154 o = Oops()
4155 o.whatever = Provoker(o)
4156 del o
4157
4158 def test_wrapper_segfault(self):
4159 # SF 927248: deeply nested wrappers could cause stack overflow
4160 f = lambda:None
4161 for i in range(1000000):
4162 f = f.__call__
4163 f = None
4164
4165 def test_file_fault(self):
4166 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00004167 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004168 class StdoutGuard:
4169 def __getattr__(self, attr):
4170 sys.stdout = sys.__stdout__
4171 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4172 sys.stdout = StdoutGuard()
4173 try:
4174 print("Oops!")
4175 except RuntimeError:
4176 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004177 finally:
4178 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004179
4180 def test_vicious_descriptor_nonsense(self):
4181 # Testing vicious_descriptor_nonsense...
4182
4183 # A potential segfault spotted by Thomas Wouters in mail to
4184 # python-dev 2003-04-17, turned into an example & fixed by Michael
4185 # Hudson just less than four months later...
4186
4187 class Evil(object):
4188 def __hash__(self):
4189 return hash('attr')
4190 def __eq__(self, other):
4191 del C.attr
4192 return 0
4193
4194 class Descr(object):
4195 def __get__(self, ob, type=None):
4196 return 1
4197
4198 class C(object):
4199 attr = Descr()
4200
4201 c = C()
4202 c.__dict__[Evil()] = 0
4203
4204 self.assertEqual(c.attr, 1)
4205 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004206 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004207 self.assertEqual(hasattr(c, 'attr'), False)
4208
4209 def test_init(self):
4210 # SF 1155938
4211 class Foo(object):
4212 def __init__(self):
4213 return 10
4214 try:
4215 Foo()
4216 except TypeError:
4217 pass
4218 else:
4219 self.fail("did not test __init__() for None return")
4220
4221 def test_method_wrapper(self):
4222 # Testing method-wrapper objects...
4223 # <type 'method-wrapper'> did not support any reflection before 2.5
4224
Mark Dickinson211c6252009-02-01 10:28:51 +00004225 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004226
4227 l = []
4228 self.assertEqual(l.__add__, l.__add__)
4229 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004230 self.assertTrue(l.__add__ != [5].__add__)
4231 self.assertTrue(l.__add__ != l.__mul__)
4232 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004233 if hasattr(l.__add__, '__self__'):
4234 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004235 self.assertTrue(l.__add__.__self__ is l)
4236 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004237 else:
4238 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004239 self.assertTrue(l.__add__.im_self is l)
4240 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004241 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4242 try:
4243 hash(l.__add__)
4244 except TypeError:
4245 pass
4246 else:
4247 self.fail("no TypeError from hash([].__add__)")
4248
4249 t = ()
4250 t += (7,)
4251 self.assertEqual(t.__add__, (7,).__add__)
4252 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4253
4254 def test_not_implemented(self):
4255 # Testing NotImplemented...
4256 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004257 import operator
4258
4259 def specialmethod(self, other):
4260 return NotImplemented
4261
4262 def check(expr, x, y):
4263 try:
4264 exec(expr, {'x': x, 'y': y, 'operator': operator})
4265 except TypeError:
4266 pass
4267 else:
4268 self.fail("no TypeError from %r" % (expr,))
4269
4270 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4271 # TypeErrors
4272 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4273 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004274 for name, expr, iexpr in [
4275 ('__add__', 'x + y', 'x += y'),
4276 ('__sub__', 'x - y', 'x -= y'),
4277 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004278 ('__truediv__', 'operator.truediv(x, y)', None),
4279 ('__floordiv__', 'operator.floordiv(x, y)', None),
4280 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004281 ('__mod__', 'x % y', 'x %= y'),
4282 ('__divmod__', 'divmod(x, y)', None),
4283 ('__pow__', 'x ** y', 'x **= y'),
4284 ('__lshift__', 'x << y', 'x <<= y'),
4285 ('__rshift__', 'x >> y', 'x >>= y'),
4286 ('__and__', 'x & y', 'x &= y'),
4287 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004288 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004289 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004290 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004291 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004292 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004293 check(expr, a, N1)
4294 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004295 if iexpr:
4296 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004297 check(iexpr, a, N1)
4298 check(iexpr, a, N2)
4299 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004300 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004301 c = C()
4302 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004303 check(iexpr, c, N1)
4304 check(iexpr, c, N2)
4305
Georg Brandl479a7e72008-02-05 18:13:15 +00004306 def test_assign_slice(self):
4307 # ceval.c's assign_slice used to check for
4308 # tp->tp_as_sequence->sq_slice instead of
4309 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004310
Georg Brandl479a7e72008-02-05 18:13:15 +00004311 class C(object):
4312 def __setitem__(self, idx, value):
4313 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004314
Georg Brandl479a7e72008-02-05 18:13:15 +00004315 c = C()
4316 c[1:2] = 3
4317 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004318
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004319 def test_set_and_no_get(self):
4320 # See
4321 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4322 class Descr(object):
4323
4324 def __init__(self, name):
4325 self.name = name
4326
4327 def __set__(self, obj, value):
4328 obj.__dict__[self.name] = value
4329 descr = Descr("a")
4330
4331 class X(object):
4332 a = descr
4333
4334 x = X()
4335 self.assertIs(x.a, descr)
4336 x.a = 42
4337 self.assertEqual(x.a, 42)
4338
Benjamin Peterson21896a32010-03-21 22:03:03 +00004339 # Also check type_getattro for correctness.
4340 class Meta(type):
4341 pass
4342 class X(object):
4343 __metaclass__ = Meta
4344 X.a = 42
4345 Meta.a = Descr("a")
4346 self.assertEqual(X.a, 42)
4347
Benjamin Peterson9262b842008-11-17 22:45:50 +00004348 def test_getattr_hooks(self):
4349 # issue 4230
4350
4351 class Descriptor(object):
4352 counter = 0
4353 def __get__(self, obj, objtype=None):
4354 def getter(name):
4355 self.counter += 1
4356 raise AttributeError(name)
4357 return getter
4358
4359 descr = Descriptor()
4360 class A(object):
4361 __getattribute__ = descr
4362 class B(object):
4363 __getattr__ = descr
4364 class C(object):
4365 __getattribute__ = descr
4366 __getattr__ = descr
4367
4368 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004369 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004370 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004371 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004372 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004373 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004374
4375 import gc
4376 class EvilGetattribute(object):
4377 # This used to segfault
4378 def __getattr__(self, name):
4379 raise AttributeError(name)
4380 def __getattribute__(self, name):
4381 del EvilGetattribute.__getattr__
4382 for i in range(5):
4383 gc.collect()
4384 raise AttributeError(name)
4385
4386 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4387
Benjamin Peterson477ba912011-01-12 15:34:01 +00004388 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004389 # type pretends not to have __abstractmethods__.
4390 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4391 class meta(type):
4392 pass
4393 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004394 class X(object):
4395 pass
4396 with self.assertRaises(AttributeError):
4397 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004398
Victor Stinner3249dec2011-05-01 23:19:15 +02004399 def test_proxy_call(self):
4400 class FakeStr:
4401 __class__ = str
4402
4403 fake_str = FakeStr()
4404 # isinstance() reads __class__
4405 self.assertTrue(isinstance(fake_str, str))
4406
4407 # call a method descriptor
4408 with self.assertRaises(TypeError):
4409 str.split(fake_str)
4410
4411 # call a slot wrapper descriptor
4412 with self.assertRaises(TypeError):
4413 str.__add__(fake_str, "abc")
4414
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004415 def test_repr_as_str(self):
4416 # Issue #11603: crash or infinite loop when rebinding __str__ as
4417 # __repr__.
4418 class Foo:
4419 pass
4420 Foo.__repr__ = Foo.__str__
4421 foo = Foo()
4422 str(foo)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004423
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004424 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004425 with self.assertRaises(ValueError) as cm:
4426 class X:
4427 __slots__ = ["foo"]
4428 foo = None
4429 m = str(cm.exception)
4430 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4431
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004432 def test_set_doc(self):
4433 class X:
4434 "elephant"
4435 X.__doc__ = "banana"
4436 self.assertEqual(X.__doc__, "banana")
4437 with self.assertRaises(TypeError) as cm:
4438 type(list).__dict__["__doc__"].__set__(list, "blah")
4439 self.assertIn("can't set list.__doc__", str(cm.exception))
4440 with self.assertRaises(TypeError) as cm:
4441 type(X).__dict__["__doc__"].__delete__(X)
4442 self.assertIn("can't delete X.__doc__", str(cm.exception))
4443 self.assertEqual(X.__doc__, "banana")
4444
Antoine Pitrou9d574812011-12-12 13:47:25 +01004445 def test_qualname(self):
4446 descriptors = [str.lower, complex.real, float.real, int.__add__]
4447 types = ['method', 'member', 'getset', 'wrapper']
4448
4449 # make sure we have an example of each type of descriptor
4450 for d, n in zip(descriptors, types):
4451 self.assertEqual(type(d).__name__, n + '_descriptor')
4452
4453 for d in descriptors:
4454 qualname = d.__objclass__.__qualname__ + '.' + d.__name__
4455 self.assertEqual(d.__qualname__, qualname)
4456
4457 self.assertEqual(str.lower.__qualname__, 'str.lower')
4458 self.assertEqual(complex.real.__qualname__, 'complex.real')
4459 self.assertEqual(float.real.__qualname__, 'float.real')
4460 self.assertEqual(int.__add__.__qualname__, 'int.__add__')
4461
4462
Georg Brandl479a7e72008-02-05 18:13:15 +00004463class DictProxyTests(unittest.TestCase):
4464 def setUp(self):
4465 class C(object):
4466 def meth(self):
4467 pass
4468 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004469
Brett Cannon7a540732011-02-22 03:04:06 +00004470 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4471 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004472 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004473 # Testing dict-proxy keys...
4474 it = self.C.__dict__.keys()
4475 self.assertNotIsInstance(it, list)
4476 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004477 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004478 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl479a7e72008-02-05 18:13:15 +00004479 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004480
Brett Cannon7a540732011-02-22 03:04:06 +00004481 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4482 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004483 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004484 # Testing dict-proxy values...
4485 it = self.C.__dict__.values()
4486 self.assertNotIsInstance(it, list)
4487 values = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004488 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004489
Brett Cannon7a540732011-02-22 03:04:06 +00004490 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4491 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004492 def test_iter_items(self):
4493 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004494 it = self.C.__dict__.items()
4495 self.assertNotIsInstance(it, list)
4496 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004497 keys.sort()
4498 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4499 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004500
Georg Brandl479a7e72008-02-05 18:13:15 +00004501 def test_dict_type_with_metaclass(self):
4502 # Testing type of __dict__ when metaclass set...
4503 class B(object):
4504 pass
4505 class M(type):
4506 pass
4507 class C(metaclass=M):
4508 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4509 pass
4510 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004511
Ezio Melottiac53ab62010-12-18 14:59:43 +00004512 def test_repr(self):
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004513 # Testing dict_proxy.__repr__.
4514 # We can't blindly compare with the repr of another dict as ordering
4515 # of keys and values is arbitrary and may differ.
4516 r = repr(self.C.__dict__)
4517 self.assertTrue(r.startswith('dict_proxy('), r)
4518 self.assertTrue(r.endswith(')'), r)
4519 for k, v in self.C.__dict__.items():
4520 self.assertIn('{!r}: {!r}'.format(k, v), r)
Ezio Melottiac53ab62010-12-18 14:59:43 +00004521
Christian Heimesbbffeb62008-01-24 09:42:52 +00004522
Georg Brandl479a7e72008-02-05 18:13:15 +00004523class PTypesLongInitTest(unittest.TestCase):
4524 # This is in its own TestCase so that it can be run before any other tests.
4525 def test_pytype_long_ready(self):
4526 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004527
Georg Brandl479a7e72008-02-05 18:13:15 +00004528 # This dumps core when SF bug 551412 isn't fixed --
4529 # but only when test_descr.py is run separately.
4530 # (That can't be helped -- as soon as PyType_Ready()
4531 # is called for PyLong_Type, the bug is gone.)
4532 class UserLong(object):
4533 def __pow__(self, *args):
4534 pass
4535 try:
4536 pow(0, UserLong(), 0)
4537 except:
4538 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004539
Georg Brandl479a7e72008-02-05 18:13:15 +00004540 # Another segfault only when run early
4541 # (before PyType_Ready(tuple) is called)
4542 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004543
4544
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004545def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004546 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004547 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004548 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004549
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004550if __name__ == "__main__":
4551 test_main()