blob: 2a9f88083b9ffd6b561ea6d80664d951f7220dca [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
628
629 def test_module_subclasses(self):
630 # Testing Python subclass of module...
631 log = []
Georg Brandl479a7e72008-02-05 18:13:15 +0000632 MT = type(sys)
633 class MM(MT):
634 def __init__(self, name):
635 MT.__init__(self, name)
636 def __getattribute__(self, name):
637 log.append(("getattr", name))
638 return MT.__getattribute__(self, name)
639 def __setattr__(self, name, value):
640 log.append(("setattr", name, value))
641 MT.__setattr__(self, name, value)
642 def __delattr__(self, name):
643 log.append(("delattr", name))
644 MT.__delattr__(self, name)
645 a = MM("a")
646 a.foo = 12
647 x = a.foo
648 del a.foo
649 self.assertEqual(log, [("setattr", "foo", 12),
650 ("getattr", "foo"),
651 ("delattr", "foo")])
652
653 # http://python.org/sf/1174712
Tim Peters1fc240e2001-10-26 05:06:50 +0000654 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000655 class Module(types.ModuleType, str):
656 pass
657 except TypeError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000658 pass
659 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000660 self.fail("inheriting from ModuleType and str at the same time "
661 "should fail")
Tim Peters1fc240e2001-10-26 05:06:50 +0000662
Georg Brandl479a7e72008-02-05 18:13:15 +0000663 def test_multiple_inheritance(self):
664 # Testing multiple inheritance...
665 class C(object):
666 def __init__(self):
667 self.__state = 0
668 def getstate(self):
669 return self.__state
670 def setstate(self, state):
671 self.__state = state
672 a = C()
673 self.assertEqual(a.getstate(), 0)
674 a.setstate(10)
675 self.assertEqual(a.getstate(), 10)
676 class D(dict, C):
677 def __init__(self):
678 type({}).__init__(self)
679 C.__init__(self)
680 d = D()
681 self.assertEqual(list(d.keys()), [])
682 d["hello"] = "world"
683 self.assertEqual(list(d.items()), [("hello", "world")])
684 self.assertEqual(d["hello"], "world")
685 self.assertEqual(d.getstate(), 0)
686 d.setstate(10)
687 self.assertEqual(d.getstate(), 10)
688 self.assertEqual(D.__mro__, (D, dict, C, object))
Tim Peters5d2b77c2001-09-03 05:47:38 +0000689
Georg Brandl479a7e72008-02-05 18:13:15 +0000690 # SF bug #442833
691 class Node(object):
692 def __int__(self):
693 return int(self.foo())
694 def foo(self):
695 return "23"
696 class Frag(Node, list):
697 def foo(self):
698 return "42"
699 self.assertEqual(Node().__int__(), 23)
700 self.assertEqual(int(Node()), 23)
701 self.assertEqual(Frag().__int__(), 42)
702 self.assertEqual(int(Frag()), 42)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000703
Georg Brandl479a7e72008-02-05 18:13:15 +0000704 def test_diamond_inheritence(self):
705 # Testing multiple inheritance special cases...
706 class A(object):
707 def spam(self): return "A"
708 self.assertEqual(A().spam(), "A")
709 class B(A):
710 def boo(self): return "B"
711 def spam(self): return "B"
712 self.assertEqual(B().spam(), "B")
713 self.assertEqual(B().boo(), "B")
714 class C(A):
715 def boo(self): return "C"
716 self.assertEqual(C().spam(), "A")
717 self.assertEqual(C().boo(), "C")
718 class D(B, C): pass
719 self.assertEqual(D().spam(), "B")
720 self.assertEqual(D().boo(), "B")
721 self.assertEqual(D.__mro__, (D, B, C, A, object))
722 class E(C, B): pass
723 self.assertEqual(E().spam(), "B")
724 self.assertEqual(E().boo(), "C")
725 self.assertEqual(E.__mro__, (E, C, B, A, object))
726 # MRO order disagreement
727 try:
728 class F(D, E): pass
729 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000730 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000731 else:
732 self.fail("expected MRO order disagreement (F)")
733 try:
734 class G(E, D): pass
735 except TypeError:
736 pass
737 else:
738 self.fail("expected MRO order disagreement (G)")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000739
Georg Brandl479a7e72008-02-05 18:13:15 +0000740 # see thread python-dev/2002-October/029035.html
741 def test_ex5_from_c3_switch(self):
742 # Testing ex5 from C3 switch discussion...
743 class A(object): pass
744 class B(object): pass
745 class C(object): pass
746 class X(A): pass
747 class Y(A): pass
748 class Z(X,B,Y,C): pass
749 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000750
Georg Brandl479a7e72008-02-05 18:13:15 +0000751 # see "A Monotonic Superclass Linearization for Dylan",
752 # by Kim Barrett et al. (OOPSLA 1996)
753 def test_monotonicity(self):
754 # Testing MRO monotonicity...
755 class Boat(object): pass
756 class DayBoat(Boat): pass
757 class WheelBoat(Boat): pass
758 class EngineLess(DayBoat): pass
759 class SmallMultihull(DayBoat): pass
760 class PedalWheelBoat(EngineLess,WheelBoat): pass
761 class SmallCatamaran(SmallMultihull): pass
762 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
Guido van Rossume45763a2001-08-10 21:28:46 +0000763
Georg Brandl479a7e72008-02-05 18:13:15 +0000764 self.assertEqual(PedalWheelBoat.__mro__,
765 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
766 self.assertEqual(SmallCatamaran.__mro__,
767 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
768 self.assertEqual(Pedalo.__mro__,
769 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
770 SmallMultihull, DayBoat, WheelBoat, Boat, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000771
Georg Brandl479a7e72008-02-05 18:13:15 +0000772 # see "A Monotonic Superclass Linearization for Dylan",
773 # by Kim Barrett et al. (OOPSLA 1996)
774 def test_consistency_with_epg(self):
Ezio Melotti42da6632011-03-15 05:18:48 +0200775 # Testing consistency with EPG...
Georg Brandl479a7e72008-02-05 18:13:15 +0000776 class Pane(object): pass
777 class ScrollingMixin(object): pass
778 class EditingMixin(object): pass
779 class ScrollablePane(Pane,ScrollingMixin): pass
780 class EditablePane(Pane,EditingMixin): pass
781 class EditableScrollablePane(ScrollablePane,EditablePane): pass
Guido van Rossum9a818922002-11-14 19:50:14 +0000782
Georg Brandl479a7e72008-02-05 18:13:15 +0000783 self.assertEqual(EditableScrollablePane.__mro__,
784 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
785 ScrollingMixin, EditingMixin, object))
Guido van Rossum9a818922002-11-14 19:50:14 +0000786
Georg Brandl479a7e72008-02-05 18:13:15 +0000787 def test_mro_disagreement(self):
788 # Testing error messages for MRO disagreement...
789 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000790order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000791
Georg Brandl479a7e72008-02-05 18:13:15 +0000792 def raises(exc, expected, callable, *args):
Guido van Rossum58da9312007-11-10 23:39:45 +0000793 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000794 callable(*args)
795 except exc as msg:
Benjamin Petersone549ead2009-03-28 21:42:05 +0000796 # the exact msg is generally considered an impl detail
797 if support.check_impl_detail():
798 if not str(msg).startswith(expected):
799 self.fail("Message %r, expected %r" %
800 (str(msg), expected))
Georg Brandl479a7e72008-02-05 18:13:15 +0000801 else:
802 self.fail("Expected %s" % exc)
Guido van Rossum58da9312007-11-10 23:39:45 +0000803
Georg Brandl479a7e72008-02-05 18:13:15 +0000804 class A(object): pass
805 class B(A): pass
806 class C(object): pass
Christian Heimes9a371592007-12-28 14:08:13 +0000807
Georg Brandl479a7e72008-02-05 18:13:15 +0000808 # Test some very simple errors
809 raises(TypeError, "duplicate base class A",
810 type, "X", (A, A), {})
811 raises(TypeError, mro_err_msg,
812 type, "X", (A, B), {})
813 raises(TypeError, mro_err_msg,
814 type, "X", (A, C, B), {})
815 # Test a slightly more complex error
816 class GridLayout(object): pass
817 class HorizontalGrid(GridLayout): pass
818 class VerticalGrid(GridLayout): pass
819 class HVGrid(HorizontalGrid, VerticalGrid): pass
820 class VHGrid(VerticalGrid, HorizontalGrid): pass
821 raises(TypeError, mro_err_msg,
822 type, "ConfusedGrid", (HVGrid, VHGrid), {})
Guido van Rossum58da9312007-11-10 23:39:45 +0000823
Georg Brandl479a7e72008-02-05 18:13:15 +0000824 def test_object_class(self):
825 # Testing object class...
826 a = object()
827 self.assertEqual(a.__class__, object)
828 self.assertEqual(type(a), object)
829 b = object()
830 self.assertNotEqual(a, b)
831 self.assertFalse(hasattr(a, "foo"))
Tim Peters808b94e2001-09-13 19:33:07 +0000832 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000833 a.foo = 12
834 except (AttributeError, TypeError):
Tim Peters808b94e2001-09-13 19:33:07 +0000835 pass
836 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000837 self.fail("object() should not allow setting a foo attribute")
838 self.assertFalse(hasattr(object(), "__dict__"))
Tim Peters561f8992001-09-13 19:36:36 +0000839
Georg Brandl479a7e72008-02-05 18:13:15 +0000840 class Cdict(object):
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000841 pass
Georg Brandl479a7e72008-02-05 18:13:15 +0000842 x = Cdict()
843 self.assertEqual(x.__dict__, {})
844 x.foo = 1
845 self.assertEqual(x.foo, 1)
846 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossumd8faa362007-04-27 19:54:29 +0000847
Georg Brandl479a7e72008-02-05 18:13:15 +0000848 def test_slots(self):
849 # Testing __slots__...
850 class C0(object):
851 __slots__ = []
852 x = C0()
853 self.assertFalse(hasattr(x, "__dict__"))
854 self.assertFalse(hasattr(x, "foo"))
855
856 class C1(object):
857 __slots__ = ['a']
858 x = C1()
859 self.assertFalse(hasattr(x, "__dict__"))
860 self.assertFalse(hasattr(x, "a"))
Guido van Rossumd8faa362007-04-27 19:54:29 +0000861 x.a = 1
Georg Brandl479a7e72008-02-05 18:13:15 +0000862 self.assertEqual(x.a, 1)
863 x.a = None
864 self.assertEqual(x.a, None)
865 del x.a
866 self.assertFalse(hasattr(x, "a"))
Guido van Rossum5c294fb2001-09-25 03:43:42 +0000867
Georg Brandl479a7e72008-02-05 18:13:15 +0000868 class C3(object):
869 __slots__ = ['a', 'b', 'c']
870 x = C3()
871 self.assertFalse(hasattr(x, "__dict__"))
872 self.assertFalse(hasattr(x, 'a'))
873 self.assertFalse(hasattr(x, 'b'))
874 self.assertFalse(hasattr(x, 'c'))
875 x.a = 1
876 x.b = 2
877 x.c = 3
878 self.assertEqual(x.a, 1)
879 self.assertEqual(x.b, 2)
880 self.assertEqual(x.c, 3)
881
882 class C4(object):
883 """Validate name mangling"""
884 __slots__ = ['__a']
885 def __init__(self, value):
886 self.__a = value
887 def get(self):
888 return self.__a
889 x = C4(5)
890 self.assertFalse(hasattr(x, '__dict__'))
891 self.assertFalse(hasattr(x, '__a'))
892 self.assertEqual(x.get(), 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000893 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000894 x.__a = 6
895 except AttributeError:
Guido van Rossum6661be32001-10-26 04:26:12 +0000896 pass
897 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000898 self.fail("Double underscored names not mangled")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000899
Georg Brandl479a7e72008-02-05 18:13:15 +0000900 # Make sure slot names are proper identifiers
Guido van Rossum360e4b82007-05-14 22:51:27 +0000901 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000902 class C(object):
903 __slots__ = [None]
Guido van Rossum360e4b82007-05-14 22:51:27 +0000904 except TypeError:
905 pass
906 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000907 self.fail("[None] slots not caught")
Guido van Rossum360e4b82007-05-14 22:51:27 +0000908 try:
Georg Brandl479a7e72008-02-05 18:13:15 +0000909 class C(object):
910 __slots__ = ["foo bar"]
911 except TypeError:
Guido van Rossum360e4b82007-05-14 22:51:27 +0000912 pass
913 else:
Georg Brandl479a7e72008-02-05 18:13:15 +0000914 self.fail("['foo bar'] slots not caught")
915 try:
916 class C(object):
917 __slots__ = ["foo\0bar"]
918 except TypeError:
919 pass
920 else:
921 self.fail("['foo\\0bar'] slots not caught")
922 try:
923 class C(object):
924 __slots__ = ["1"]
925 except TypeError:
926 pass
927 else:
928 self.fail("['1'] slots not caught")
929 try:
930 class C(object):
931 __slots__ = [""]
932 except TypeError:
933 pass
934 else:
935 self.fail("[''] slots not caught")
936 class C(object):
937 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
938 # XXX(nnorwitz): was there supposed to be something tested
939 # from the class above?
Guido van Rossum360e4b82007-05-14 22:51:27 +0000940
Georg Brandl479a7e72008-02-05 18:13:15 +0000941 # Test a single string is not expanded as a sequence.
942 class C(object):
943 __slots__ = "abc"
944 c = C()
945 c.abc = 5
946 self.assertEqual(c.abc, 5)
Guido van Rossum6661be32001-10-26 04:26:12 +0000947
Georg Brandl479a7e72008-02-05 18:13:15 +0000948 # Test unicode slot names
949 # Test a single unicode string is not expanded as a sequence.
950 class C(object):
951 __slots__ = "abc"
952 c = C()
953 c.abc = 5
954 self.assertEqual(c.abc, 5)
Guido van Rossum3926a632001-09-25 16:25:58 +0000955
Georg Brandl479a7e72008-02-05 18:13:15 +0000956 # _unicode_to_string used to modify slots in certain circumstances
957 slots = ("foo", "bar")
958 class C(object):
959 __slots__ = slots
960 x = C()
961 x.foo = 5
962 self.assertEqual(x.foo, 5)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000963 self.assertTrue(type(slots[0]) is str)
Georg Brandl479a7e72008-02-05 18:13:15 +0000964 # this used to leak references
965 try:
966 class C(object):
967 __slots__ = [chr(128)]
968 except (TypeError, UnicodeEncodeError):
969 pass
970 else:
971 raise TestFailed("[chr(128)] slots not caught")
Guido van Rossum3926a632001-09-25 16:25:58 +0000972
Georg Brandl479a7e72008-02-05 18:13:15 +0000973 # Test leaks
974 class Counted(object):
975 counter = 0 # counts the number of instances alive
976 def __init__(self):
977 Counted.counter += 1
978 def __del__(self):
979 Counted.counter -= 1
980 class C(object):
981 __slots__ = ['a', 'b', 'c']
982 x = C()
983 x.a = Counted()
984 x.b = Counted()
985 x.c = Counted()
986 self.assertEqual(Counted.counter, 3)
987 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000988 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000989 self.assertEqual(Counted.counter, 0)
990 class D(C):
991 pass
992 x = D()
993 x.a = Counted()
994 x.z = Counted()
995 self.assertEqual(Counted.counter, 2)
996 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +0000997 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +0000998 self.assertEqual(Counted.counter, 0)
999 class E(D):
1000 __slots__ = ['e']
1001 x = E()
1002 x.a = Counted()
1003 x.z = Counted()
1004 x.e = Counted()
1005 self.assertEqual(Counted.counter, 3)
1006 del x
Benjamin Petersone549ead2009-03-28 21:42:05 +00001007 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001008 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001009
Georg Brandl479a7e72008-02-05 18:13:15 +00001010 # Test cyclical leaks [SF bug 519621]
1011 class F(object):
1012 __slots__ = ['a', 'b']
Georg Brandl479a7e72008-02-05 18:13:15 +00001013 s = F()
1014 s.a = [Counted(), s]
1015 self.assertEqual(Counted.counter, 1)
1016 s = None
Benjamin Petersone549ead2009-03-28 21:42:05 +00001017 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001018 self.assertEqual(Counted.counter, 0)
Guido van Rossum3926a632001-09-25 16:25:58 +00001019
Georg Brandl479a7e72008-02-05 18:13:15 +00001020 # Test lookup leaks [SF bug 572567]
Georg Brandl1b37e872010-03-14 10:45:50 +00001021 import gc
Benjamin Petersone549ead2009-03-28 21:42:05 +00001022 if hasattr(gc, 'get_objects'):
1023 class G(object):
Benjamin Petersona8b976b2009-10-11 18:28:48 +00001024 def __eq__(self, other):
1025 return False
Benjamin Petersone549ead2009-03-28 21:42:05 +00001026 g = G()
1027 orig_objects = len(gc.get_objects())
1028 for i in range(10):
1029 g==g
1030 new_objects = len(gc.get_objects())
1031 self.assertEqual(orig_objects, new_objects)
1032
Georg Brandl479a7e72008-02-05 18:13:15 +00001033 class H(object):
1034 __slots__ = ['a', 'b']
1035 def __init__(self):
1036 self.a = 1
1037 self.b = 2
1038 def __del__(self_):
1039 self.assertEqual(self_.a, 1)
1040 self.assertEqual(self_.b, 2)
Benjamin Petersonc1de4cc2008-11-03 21:29:09 +00001041 with support.captured_output('stderr') as s:
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001042 h = H()
Georg Brandl479a7e72008-02-05 18:13:15 +00001043 del h
Benjamin Petersonc0747cf2008-11-03 20:31:38 +00001044 self.assertEqual(s.getvalue(), '')
Guido van Rossum90c45142001-11-24 21:07:01 +00001045
Benjamin Petersond12362a2009-12-30 19:44:54 +00001046 class X(object):
1047 __slots__ = "a"
1048 with self.assertRaises(AttributeError):
1049 del X().a
1050
Georg Brandl479a7e72008-02-05 18:13:15 +00001051 def test_slots_special(self):
1052 # Testing __dict__ and __weakref__ in __slots__...
1053 class D(object):
1054 __slots__ = ["__dict__"]
1055 a = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001056 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001057 self.assertFalse(hasattr(a, "__weakref__"))
1058 a.foo = 42
1059 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum90c45142001-11-24 21:07:01 +00001060
Georg Brandl479a7e72008-02-05 18:13:15 +00001061 class W(object):
1062 __slots__ = ["__weakref__"]
1063 a = W()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001064 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001065 self.assertFalse(hasattr(a, "__dict__"))
1066 try:
1067 a.foo = 42
1068 except AttributeError:
1069 pass
1070 else:
1071 self.fail("shouldn't be allowed to set a.foo")
1072
1073 class C1(W, D):
1074 __slots__ = []
1075 a = C1()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001076 self.assertTrue(hasattr(a, "__dict__"))
1077 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001078 a.foo = 42
1079 self.assertEqual(a.__dict__, {"foo": 42})
1080
1081 class C2(D, W):
1082 __slots__ = []
1083 a = C2()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001084 self.assertTrue(hasattr(a, "__dict__"))
1085 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl479a7e72008-02-05 18:13:15 +00001086 a.foo = 42
1087 self.assertEqual(a.__dict__, {"foo": 42})
1088
Christian Heimesa156e092008-02-16 07:38:31 +00001089 def test_slots_descriptor(self):
1090 # Issue2115: slot descriptors did not correctly check
1091 # the type of the given object
1092 import abc
1093 class MyABC(metaclass=abc.ABCMeta):
1094 __slots__ = "a"
1095
1096 class Unrelated(object):
1097 pass
1098 MyABC.register(Unrelated)
1099
1100 u = Unrelated()
Ezio Melottie9615932010-01-24 19:26:24 +00001101 self.assertIsInstance(u, MyABC)
Christian Heimesa156e092008-02-16 07:38:31 +00001102
1103 # This used to crash
1104 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1105
Georg Brandl479a7e72008-02-05 18:13:15 +00001106 def test_dynamics(self):
1107 # Testing class attribute propagation...
1108 class D(object):
1109 pass
1110 class E(D):
1111 pass
1112 class F(D):
1113 pass
1114 D.foo = 1
1115 self.assertEqual(D.foo, 1)
1116 # Test that dynamic attributes are inherited
1117 self.assertEqual(E.foo, 1)
1118 self.assertEqual(F.foo, 1)
1119 # Test dynamic instances
1120 class C(object):
1121 pass
1122 a = C()
1123 self.assertFalse(hasattr(a, "foobar"))
1124 C.foobar = 2
1125 self.assertEqual(a.foobar, 2)
1126 C.method = lambda self: 42
1127 self.assertEqual(a.method(), 42)
1128 C.__repr__ = lambda self: "C()"
1129 self.assertEqual(repr(a), "C()")
1130 C.__int__ = lambda self: 100
1131 self.assertEqual(int(a), 100)
1132 self.assertEqual(a.foobar, 2)
1133 self.assertFalse(hasattr(a, "spam"))
1134 def mygetattr(self, name):
1135 if name == "spam":
1136 return "spam"
1137 raise AttributeError
1138 C.__getattr__ = mygetattr
1139 self.assertEqual(a.spam, "spam")
1140 a.new = 12
1141 self.assertEqual(a.new, 12)
1142 def mysetattr(self, name, value):
1143 if name == "spam":
1144 raise AttributeError
1145 return object.__setattr__(self, name, value)
1146 C.__setattr__ = mysetattr
1147 try:
1148 a.spam = "not spam"
1149 except AttributeError:
1150 pass
1151 else:
1152 self.fail("expected AttributeError")
1153 self.assertEqual(a.spam, "spam")
1154 class D(C):
1155 pass
1156 d = D()
1157 d.foo = 1
1158 self.assertEqual(d.foo, 1)
1159
1160 # Test handling of int*seq and seq*int
1161 class I(int):
1162 pass
1163 self.assertEqual("a"*I(2), "aa")
1164 self.assertEqual(I(2)*"a", "aa")
1165 self.assertEqual(2*I(3), 6)
1166 self.assertEqual(I(3)*2, 6)
1167 self.assertEqual(I(3)*I(2), 6)
1168
Georg Brandl479a7e72008-02-05 18:13:15 +00001169 # Test comparison of classes with dynamic metaclasses
1170 class dynamicmetaclass(type):
1171 pass
1172 class someclass(metaclass=dynamicmetaclass):
1173 pass
1174 self.assertNotEqual(someclass, object)
1175
1176 def test_errors(self):
1177 # Testing errors...
1178 try:
1179 class C(list, dict):
1180 pass
1181 except TypeError:
1182 pass
1183 else:
1184 self.fail("inheritance from both list and dict should be illegal")
1185
1186 try:
1187 class C(object, None):
1188 pass
1189 except TypeError:
1190 pass
1191 else:
1192 self.fail("inheritance from non-type should be illegal")
1193 class Classic:
1194 pass
1195
1196 try:
1197 class C(type(len)):
1198 pass
1199 except TypeError:
1200 pass
1201 else:
1202 self.fail("inheritance from CFunction should be illegal")
1203
1204 try:
1205 class C(object):
1206 __slots__ = 1
1207 except TypeError:
1208 pass
1209 else:
1210 self.fail("__slots__ = 1 should be illegal")
1211
1212 try:
1213 class C(object):
1214 __slots__ = [1]
1215 except TypeError:
1216 pass
1217 else:
1218 self.fail("__slots__ = [1] should be illegal")
1219
1220 class M1(type):
1221 pass
1222 class M2(type):
1223 pass
1224 class A1(object, metaclass=M1):
1225 pass
1226 class A2(object, metaclass=M2):
1227 pass
1228 try:
1229 class B(A1, A2):
1230 pass
1231 except TypeError:
1232 pass
1233 else:
1234 self.fail("finding the most derived metaclass should have failed")
1235
1236 def test_classmethods(self):
1237 # Testing class methods...
1238 class C(object):
1239 def foo(*a): return a
1240 goo = classmethod(foo)
1241 c = C()
1242 self.assertEqual(C.goo(1), (C, 1))
1243 self.assertEqual(c.goo(1), (C, 1))
1244 self.assertEqual(c.foo(1), (c, 1))
1245 class D(C):
1246 pass
1247 d = D()
1248 self.assertEqual(D.goo(1), (D, 1))
1249 self.assertEqual(d.goo(1), (D, 1))
1250 self.assertEqual(d.foo(1), (d, 1))
1251 self.assertEqual(D.foo(d, 1), (d, 1))
1252 # Test for a specific crash (SF bug 528132)
1253 def f(cls, arg): return (cls, arg)
1254 ff = classmethod(f)
1255 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1256 self.assertEqual(ff.__get__(0)(42), (int, 42))
1257
1258 # Test super() with classmethods (SF bug 535444)
1259 self.assertEqual(C.goo.__self__, C)
1260 self.assertEqual(D.goo.__self__, D)
1261 self.assertEqual(super(D,D).goo.__self__, D)
1262 self.assertEqual(super(D,d).goo.__self__, D)
1263 self.assertEqual(super(D,D).goo(), (D,))
1264 self.assertEqual(super(D,d).goo(), (D,))
1265
Benjamin Peterson8719ad52009-09-11 22:24:02 +00001266 # Verify that a non-callable will raise
1267 meth = classmethod(1).__get__(1)
1268 self.assertRaises(TypeError, meth)
Georg Brandl479a7e72008-02-05 18:13:15 +00001269
1270 # Verify that classmethod() doesn't allow keyword args
1271 try:
1272 classmethod(f, kw=1)
1273 except TypeError:
1274 pass
1275 else:
1276 self.fail("classmethod shouldn't accept keyword args")
1277
Benjamin Petersone549ead2009-03-28 21:42:05 +00001278 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001279 def test_classmethods_in_c(self):
1280 # Testing C-based class methods...
1281 import xxsubtype as spam
1282 a = (1, 2, 3)
1283 d = {'abc': 123}
1284 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1285 self.assertEqual(x, spam.spamlist)
1286 self.assertEqual(a, a1)
1287 self.assertEqual(d, d1)
1288 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1289 self.assertEqual(x, spam.spamlist)
1290 self.assertEqual(a, a1)
1291 self.assertEqual(d, d1)
1292
1293 def test_staticmethods(self):
1294 # Testing static methods...
1295 class C(object):
1296 def foo(*a): return a
1297 goo = staticmethod(foo)
1298 c = C()
1299 self.assertEqual(C.goo(1), (1,))
1300 self.assertEqual(c.goo(1), (1,))
1301 self.assertEqual(c.foo(1), (c, 1,))
1302 class D(C):
1303 pass
1304 d = D()
1305 self.assertEqual(D.goo(1), (1,))
1306 self.assertEqual(d.goo(1), (1,))
1307 self.assertEqual(d.foo(1), (d, 1))
1308 self.assertEqual(D.foo(d, 1), (d, 1))
1309
Benjamin Petersone549ead2009-03-28 21:42:05 +00001310 @support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl479a7e72008-02-05 18:13:15 +00001311 def test_staticmethods_in_c(self):
1312 # Testing C-based static methods...
1313 import xxsubtype as spam
1314 a = (1, 2, 3)
1315 d = {"abc": 123}
1316 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1317 self.assertEqual(x, None)
1318 self.assertEqual(a, a1)
1319 self.assertEqual(d, d1)
1320 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1321 self.assertEqual(x, None)
1322 self.assertEqual(a, a1)
1323 self.assertEqual(d, d1)
1324
1325 def test_classic(self):
1326 # Testing classic classes...
1327 class C:
1328 def foo(*a): return a
1329 goo = classmethod(foo)
1330 c = C()
1331 self.assertEqual(C.goo(1), (C, 1))
1332 self.assertEqual(c.goo(1), (C, 1))
1333 self.assertEqual(c.foo(1), (c, 1))
1334 class D(C):
1335 pass
1336 d = D()
1337 self.assertEqual(D.goo(1), (D, 1))
1338 self.assertEqual(d.goo(1), (D, 1))
1339 self.assertEqual(d.foo(1), (d, 1))
1340 self.assertEqual(D.foo(d, 1), (d, 1))
1341 class E: # *not* subclassing from C
1342 foo = C.foo
1343 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001344 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001345
1346 def test_compattr(self):
1347 # Testing computed attributes...
1348 class C(object):
1349 class computed_attribute(object):
1350 def __init__(self, get, set=None, delete=None):
1351 self.__get = get
1352 self.__set = set
1353 self.__delete = delete
1354 def __get__(self, obj, type=None):
1355 return self.__get(obj)
1356 def __set__(self, obj, value):
1357 return self.__set(obj, value)
1358 def __delete__(self, obj):
1359 return self.__delete(obj)
1360 def __init__(self):
1361 self.__x = 0
1362 def __get_x(self):
1363 x = self.__x
1364 self.__x = x+1
1365 return x
1366 def __set_x(self, x):
1367 self.__x = x
1368 def __delete_x(self):
1369 del self.__x
1370 x = computed_attribute(__get_x, __set_x, __delete_x)
1371 a = C()
1372 self.assertEqual(a.x, 0)
1373 self.assertEqual(a.x, 1)
1374 a.x = 10
1375 self.assertEqual(a.x, 10)
1376 self.assertEqual(a.x, 11)
1377 del a.x
1378 self.assertEqual(hasattr(a, 'x'), 0)
1379
1380 def test_newslots(self):
1381 # Testing __new__ slot override...
1382 class C(list):
1383 def __new__(cls):
1384 self = list.__new__(cls)
1385 self.foo = 1
1386 return self
1387 def __init__(self):
1388 self.foo = self.foo + 2
1389 a = C()
1390 self.assertEqual(a.foo, 3)
1391 self.assertEqual(a.__class__, C)
1392 class D(C):
1393 pass
1394 b = D()
1395 self.assertEqual(b.foo, 3)
1396 self.assertEqual(b.__class__, D)
1397
1398 def test_altmro(self):
1399 # Testing mro() and overriding it...
1400 class A(object):
1401 def f(self): return "A"
1402 class B(A):
1403 pass
1404 class C(A):
1405 def f(self): return "C"
1406 class D(B, C):
1407 pass
1408 self.assertEqual(D.mro(), [D, B, C, A, object])
1409 self.assertEqual(D.__mro__, (D, B, C, A, object))
1410 self.assertEqual(D().f(), "C")
1411
1412 class PerverseMetaType(type):
1413 def mro(cls):
1414 L = type.mro(cls)
1415 L.reverse()
1416 return L
1417 class X(D,B,C,A, metaclass=PerverseMetaType):
1418 pass
1419 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1420 self.assertEqual(X().f(), "A")
1421
1422 try:
1423 class _metaclass(type):
1424 def mro(self):
1425 return [self, dict, object]
1426 class X(object, metaclass=_metaclass):
1427 pass
Benjamin Petersone549ead2009-03-28 21:42:05 +00001428 # In CPython, the class creation above already raises
1429 # TypeError, as a protection against the fact that
1430 # instances of X would segfault it. In other Python
1431 # implementations it would be ok to let the class X
1432 # be created, but instead get a clean TypeError on the
1433 # __setitem__ below.
1434 x = object.__new__(X)
1435 x[5] = 6
Georg Brandl479a7e72008-02-05 18:13:15 +00001436 except TypeError:
1437 pass
1438 else:
1439 self.fail("devious mro() return not caught")
1440
1441 try:
1442 class _metaclass(type):
1443 def mro(self):
1444 return [1]
1445 class X(object, metaclass=_metaclass):
1446 pass
1447 except TypeError:
1448 pass
1449 else:
1450 self.fail("non-class mro() return not caught")
1451
1452 try:
1453 class _metaclass(type):
1454 def mro(self):
1455 return 1
1456 class X(object, metaclass=_metaclass):
1457 pass
1458 except TypeError:
1459 pass
1460 else:
1461 self.fail("non-sequence mro() return not caught")
1462
1463 def test_overloading(self):
1464 # Testing operator overloading...
1465
1466 class B(object):
1467 "Intermediate class because object doesn't have a __setattr__"
1468
1469 class C(B):
1470 def __getattr__(self, name):
1471 if name == "foo":
1472 return ("getattr", name)
1473 else:
1474 raise AttributeError
1475 def __setattr__(self, name, value):
1476 if name == "foo":
1477 self.setattr = (name, value)
1478 else:
1479 return B.__setattr__(self, name, value)
1480 def __delattr__(self, name):
1481 if name == "foo":
1482 self.delattr = name
1483 else:
1484 return B.__delattr__(self, name)
1485
1486 def __getitem__(self, key):
1487 return ("getitem", key)
1488 def __setitem__(self, key, value):
1489 self.setitem = (key, value)
1490 def __delitem__(self, key):
1491 self.delitem = key
1492
1493 a = C()
1494 self.assertEqual(a.foo, ("getattr", "foo"))
1495 a.foo = 12
1496 self.assertEqual(a.setattr, ("foo", 12))
1497 del a.foo
1498 self.assertEqual(a.delattr, "foo")
1499
1500 self.assertEqual(a[12], ("getitem", 12))
1501 a[12] = 21
1502 self.assertEqual(a.setitem, (12, 21))
1503 del a[12]
1504 self.assertEqual(a.delitem, 12)
1505
1506 self.assertEqual(a[0:10], ("getitem", slice(0, 10)))
1507 a[0:10] = "foo"
1508 self.assertEqual(a.setitem, (slice(0, 10), "foo"))
1509 del a[0:10]
1510 self.assertEqual(a.delitem, (slice(0, 10)))
1511
1512 def test_methods(self):
1513 # Testing methods...
1514 class C(object):
1515 def __init__(self, x):
1516 self.x = x
1517 def foo(self):
1518 return self.x
1519 c1 = C(1)
1520 self.assertEqual(c1.foo(), 1)
1521 class D(C):
1522 boo = C.foo
1523 goo = c1.foo
1524 d2 = D(2)
1525 self.assertEqual(d2.foo(), 2)
1526 self.assertEqual(d2.boo(), 2)
1527 self.assertEqual(d2.goo(), 1)
1528 class E(object):
1529 foo = C.foo
1530 self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001531 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl479a7e72008-02-05 18:13:15 +00001532
Benjamin Peterson224205f2009-05-08 03:25:19 +00001533 def test_special_method_lookup(self):
1534 # The lookup of special methods bypasses __getattr__ and
1535 # __getattribute__, but they still can be descriptors.
1536
1537 def run_context(manager):
1538 with manager:
1539 pass
1540 def iden(self):
1541 return self
1542 def hello(self):
1543 return b"hello"
Benjamin Peterson053c61f2009-05-09 17:21:13 +00001544 def empty_seq(self):
1545 return []
Benjamin Petersona5758c02009-05-09 18:15:04 +00001546 def zero(self):
1547 return 0
Benjamin Petersonaea44282010-01-04 01:10:28 +00001548 def complex_num(self):
1549 return 1j
Benjamin Petersona5758c02009-05-09 18:15:04 +00001550 def stop(self):
1551 raise StopIteration
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001552 def return_true(self, thing=None):
1553 return True
1554 def do_isinstance(obj):
1555 return isinstance(int, obj)
1556 def do_issubclass(obj):
1557 return issubclass(int, obj)
Benjamin Petersona7205592009-05-27 03:08:59 +00001558 def do_dict_missing(checker):
1559 class DictSub(checker.__class__, dict):
1560 pass
1561 self.assertEqual(DictSub()["hi"], 4)
1562 def some_number(self_, key):
1563 self.assertEqual(key, "hi")
1564 return 4
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001565 def swallow(*args): pass
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001566 def format_impl(self, spec):
1567 return "hello"
Benjamin Peterson224205f2009-05-08 03:25:19 +00001568
1569 # It would be nice to have every special method tested here, but I'm
1570 # only listing the ones I can remember outside of typeobject.c, since it
1571 # does it right.
1572 specials = [
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001573 ("__bytes__", bytes, hello, set(), {}),
1574 ("__reversed__", reversed, empty_seq, set(), {}),
1575 ("__length_hint__", list, zero, set(),
Benjamin Petersona5758c02009-05-09 18:15:04 +00001576 {"__iter__" : iden, "__next__" : stop}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001577 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1578 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Petersona7205592009-05-27 03:08:59 +00001579 ("__missing__", do_dict_missing, some_number,
1580 set(("__class__",)), {}),
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001581 ("__subclasscheck__", do_issubclass, return_true,
1582 set(("__bases__",)), {}),
Benjamin Peterson876b2f22009-06-28 03:18:59 +00001583 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1584 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonaea44282010-01-04 01:10:28 +00001585 ("__complex__", complex, complex_num, set(), {}),
Benjamin Petersonda2cf042010-06-05 00:45:37 +00001586 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson8bb9cde2010-07-01 15:16:55 +00001587 ("__floor__", math.floor, zero, set(), {}),
1588 ("__trunc__", math.trunc, zero, set(), {}),
Benjamin Petersonf751bc92010-07-02 13:46:42 +00001589 ("__ceil__", math.ceil, zero, set(), {}),
Benjamin Peterson7963a352011-05-23 16:11:05 -05001590 ("__dir__", dir, empty_seq, set(), {}),
Benjamin Peterson224205f2009-05-08 03:25:19 +00001591 ]
1592
1593 class Checker(object):
1594 def __getattr__(self, attr, test=self):
1595 test.fail("__getattr__ called with {0}".format(attr))
1596 def __getattribute__(self, attr, test=self):
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001597 if attr not in ok:
1598 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Petersona7205592009-05-27 03:08:59 +00001599 return object.__getattribute__(self, attr)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001600 class SpecialDescr(object):
1601 def __init__(self, impl):
1602 self.impl = impl
1603 def __get__(self, obj, owner):
1604 record.append(1)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001605 return self.impl.__get__(obj, owner)
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001606 class MyException(Exception):
1607 pass
1608 class ErrDescr(object):
1609 def __get__(self, obj, owner):
1610 raise MyException
Benjamin Peterson224205f2009-05-08 03:25:19 +00001611
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00001612 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson224205f2009-05-08 03:25:19 +00001613 class X(Checker):
1614 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001615 for attr, obj in env.items():
1616 setattr(X, attr, obj)
Benjamin Peterson8a282d12009-05-08 18:18:45 +00001617 setattr(X, name, meth_impl)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001618 runner(X())
1619
1620 record = []
1621 class X(Checker):
1622 pass
Benjamin Petersona5758c02009-05-09 18:15:04 +00001623 for attr, obj in env.items():
1624 setattr(X, attr, obj)
Benjamin Peterson224205f2009-05-08 03:25:19 +00001625 setattr(X, name, SpecialDescr(meth_impl))
1626 runner(X())
1627 self.assertEqual(record, [1], name)
1628
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001629 class X(Checker):
1630 pass
1631 for attr, obj in env.items():
1632 setattr(X, attr, obj)
1633 setattr(X, name, ErrDescr())
Benjamin Petersonb45c7082011-05-24 19:31:01 -05001634 self.assertRaises(MyException, runner, X())
Benjamin Peterson94c65d92009-05-25 03:10:48 +00001635
Georg Brandl479a7e72008-02-05 18:13:15 +00001636 def test_specials(self):
1637 # Testing special operators...
1638 # Test operators like __hash__ for which a built-in default exists
1639
1640 # Test the default behavior for static classes
1641 class C(object):
1642 def __getitem__(self, i):
1643 if 0 <= i < 10: return i
1644 raise IndexError
1645 c1 = C()
1646 c2 = C()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001647 self.assertTrue(not not c1) # What?
Georg Brandl479a7e72008-02-05 18:13:15 +00001648 self.assertNotEqual(id(c1), id(c2))
1649 hash(c1)
1650 hash(c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001651 self.assertEqual(c1, c1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001652 self.assertTrue(c1 != c2)
1653 self.assertTrue(not c1 != c1)
1654 self.assertTrue(not c1 == c2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001655 # Note that the module name appears in str/repr, and that varies
1656 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001657 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001658 self.assertEqual(str(c1), repr(c1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001659 self.assertNotIn(-1, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001660 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001661 self.assertIn(i, c1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001662 self.assertNotIn(10, c1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001663 # Test the default behavior for dynamic classes
1664 class D(object):
1665 def __getitem__(self, i):
1666 if 0 <= i < 10: return i
1667 raise IndexError
1668 d1 = D()
1669 d2 = D()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001670 self.assertTrue(not not d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001671 self.assertNotEqual(id(d1), id(d2))
1672 hash(d1)
1673 hash(d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001674 self.assertEqual(d1, d1)
1675 self.assertNotEqual(d1, d2)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001676 self.assertTrue(not d1 != d1)
1677 self.assertTrue(not d1 == d2)
Georg Brandl479a7e72008-02-05 18:13:15 +00001678 # Note that the module name appears in str/repr, and that varies
1679 # depending on whether this test is run standalone or from a framework.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001680 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001681 self.assertEqual(str(d1), repr(d1))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001682 self.assertNotIn(-1, d1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001683 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001684 self.assertIn(i, d1)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001685 self.assertNotIn(10, d1)
Benjamin Peterson60192082008-10-16 19:34:46 +00001686 # Test overridden behavior
Georg Brandl479a7e72008-02-05 18:13:15 +00001687 class Proxy(object):
1688 def __init__(self, x):
1689 self.x = x
1690 def __bool__(self):
1691 return not not self.x
1692 def __hash__(self):
1693 return hash(self.x)
1694 def __eq__(self, other):
1695 return self.x == other
1696 def __ne__(self, other):
1697 return self.x != other
Benjamin Peterson60192082008-10-16 19:34:46 +00001698 def __ge__(self, other):
1699 return self.x >= other
1700 def __gt__(self, other):
1701 return self.x > other
1702 def __le__(self, other):
1703 return self.x <= other
1704 def __lt__(self, other):
1705 return self.x < other
Georg Brandl479a7e72008-02-05 18:13:15 +00001706 def __str__(self):
1707 return "Proxy:%s" % self.x
1708 def __repr__(self):
1709 return "Proxy(%r)" % self.x
1710 def __contains__(self, value):
1711 return value in self.x
1712 p0 = Proxy(0)
1713 p1 = Proxy(1)
1714 p_1 = Proxy(-1)
1715 self.assertFalse(p0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001716 self.assertTrue(not not p1)
Georg Brandl479a7e72008-02-05 18:13:15 +00001717 self.assertEqual(hash(p0), hash(0))
1718 self.assertEqual(p0, p0)
1719 self.assertNotEqual(p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001720 self.assertTrue(not p0 != p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001721 self.assertEqual(not p0, p1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001722 self.assertTrue(p0 < p1)
1723 self.assertTrue(p0 <= p1)
1724 self.assertTrue(p1 > p0)
1725 self.assertTrue(p1 >= p0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001726 self.assertEqual(str(p0), "Proxy:0")
1727 self.assertEqual(repr(p0), "Proxy(0)")
1728 p10 = Proxy(range(10))
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001729 self.assertNotIn(-1, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001730 for i in range(10):
Benjamin Peterson577473f2010-01-19 00:09:57 +00001731 self.assertIn(i, p10)
Ezio Melottib58e0bd2010-01-23 15:40:09 +00001732 self.assertNotIn(10, p10)
Georg Brandl479a7e72008-02-05 18:13:15 +00001733
Georg Brandl479a7e72008-02-05 18:13:15 +00001734 def test_weakrefs(self):
1735 # Testing weak references...
1736 import weakref
1737 class C(object):
1738 pass
1739 c = C()
1740 r = weakref.ref(c)
1741 self.assertEqual(r(), c)
1742 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00001743 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001744 self.assertEqual(r(), None)
1745 del r
1746 class NoWeak(object):
1747 __slots__ = ['foo']
1748 no = NoWeak()
1749 try:
1750 weakref.ref(no)
1751 except TypeError as msg:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001752 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl479a7e72008-02-05 18:13:15 +00001753 else:
1754 self.fail("weakref.ref(no) should be illegal")
1755 class Weak(object):
1756 __slots__ = ['foo', '__weakref__']
1757 yes = Weak()
1758 r = weakref.ref(yes)
1759 self.assertEqual(r(), yes)
1760 del yes
Benjamin Petersone549ead2009-03-28 21:42:05 +00001761 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00001762 self.assertEqual(r(), None)
1763 del r
1764
1765 def test_properties(self):
1766 # Testing property...
1767 class C(object):
1768 def getx(self):
1769 return self.__x
1770 def setx(self, value):
1771 self.__x = value
1772 def delx(self):
1773 del self.__x
1774 x = property(getx, setx, delx, doc="I'm the x property.")
1775 a = C()
1776 self.assertFalse(hasattr(a, "x"))
1777 a.x = 42
1778 self.assertEqual(a._C__x, 42)
1779 self.assertEqual(a.x, 42)
1780 del a.x
1781 self.assertFalse(hasattr(a, "x"))
1782 self.assertFalse(hasattr(a, "_C__x"))
1783 C.x.__set__(a, 100)
1784 self.assertEqual(C.x.__get__(a), 100)
1785 C.x.__delete__(a)
1786 self.assertFalse(hasattr(a, "x"))
1787
1788 raw = C.__dict__['x']
Ezio Melottie9615932010-01-24 19:26:24 +00001789 self.assertIsInstance(raw, property)
Georg Brandl479a7e72008-02-05 18:13:15 +00001790
1791 attrs = dir(raw)
Benjamin Peterson577473f2010-01-19 00:09:57 +00001792 self.assertIn("__doc__", attrs)
1793 self.assertIn("fget", attrs)
1794 self.assertIn("fset", attrs)
1795 self.assertIn("fdel", attrs)
Georg Brandl479a7e72008-02-05 18:13:15 +00001796
1797 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001798 self.assertTrue(raw.fget is C.__dict__['getx'])
1799 self.assertTrue(raw.fset is C.__dict__['setx'])
1800 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl479a7e72008-02-05 18:13:15 +00001801
1802 for attr in "__doc__", "fget", "fset", "fdel":
1803 try:
1804 setattr(raw, attr, 42)
1805 except AttributeError as msg:
1806 if str(msg).find('readonly') < 0:
1807 self.fail("when setting readonly attr %r on a property, "
1808 "got unexpected AttributeError msg %r" % (attr, str(msg)))
1809 else:
1810 self.fail("expected AttributeError from trying to set readonly %r "
1811 "attr on a property" % attr)
1812
1813 class D(object):
1814 __getitem__ = property(lambda s: 1/0)
1815
1816 d = D()
1817 try:
1818 for i in d:
1819 str(i)
1820 except ZeroDivisionError:
1821 pass
1822 else:
1823 self.fail("expected ZeroDivisionError from bad property")
1824
R. David Murray378c0cf2010-02-24 01:46:21 +00001825 @unittest.skipIf(sys.flags.optimize >= 2,
1826 "Docstrings are omitted with -O2 and above")
1827 def test_properties_doc_attrib(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00001828 class E(object):
1829 def getter(self):
1830 "getter method"
1831 return 0
1832 def setter(self_, value):
1833 "setter method"
1834 pass
1835 prop = property(getter)
1836 self.assertEqual(prop.__doc__, "getter method")
1837 prop2 = property(fset=setter)
1838 self.assertEqual(prop2.__doc__, None)
1839
R. David Murray378c0cf2010-02-24 01:46:21 +00001840 def test_testcapi_no_segfault(self):
Georg Brandl479a7e72008-02-05 18:13:15 +00001841 # this segfaulted in 2.5b2
1842 try:
1843 import _testcapi
1844 except ImportError:
1845 pass
1846 else:
1847 class X(object):
1848 p = property(_testcapi.test_with_docstring)
1849
1850 def test_properties_plus(self):
1851 class C(object):
1852 foo = property(doc="hello")
1853 @foo.getter
1854 def foo(self):
1855 return self._foo
1856 @foo.setter
1857 def foo(self, value):
1858 self._foo = abs(value)
1859 @foo.deleter
1860 def foo(self):
1861 del self._foo
1862 c = C()
1863 self.assertEqual(C.foo.__doc__, "hello")
1864 self.assertFalse(hasattr(c, "foo"))
1865 c.foo = -42
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001866 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl479a7e72008-02-05 18:13:15 +00001867 self.assertEqual(c._foo, 42)
1868 self.assertEqual(c.foo, 42)
1869 del c.foo
1870 self.assertFalse(hasattr(c, '_foo'))
1871 self.assertFalse(hasattr(c, "foo"))
1872
1873 class D(C):
1874 @C.foo.deleter
1875 def foo(self):
1876 try:
1877 del self._foo
1878 except AttributeError:
1879 pass
1880 d = D()
1881 d.foo = 24
1882 self.assertEqual(d.foo, 24)
1883 del d.foo
1884 del d.foo
1885
1886 class E(object):
1887 @property
1888 def foo(self):
1889 return self._foo
1890 @foo.setter
1891 def foo(self, value):
1892 raise RuntimeError
1893 @foo.setter
1894 def foo(self, value):
1895 self._foo = abs(value)
1896 @foo.deleter
1897 def foo(self, value=None):
1898 del self._foo
1899
1900 e = E()
1901 e.foo = -42
1902 self.assertEqual(e.foo, 42)
1903 del e.foo
1904
1905 class F(E):
1906 @E.foo.deleter
1907 def foo(self):
1908 del self._foo
1909 @foo.setter
1910 def foo(self, value):
1911 self._foo = max(0, value)
1912 f = F()
1913 f.foo = -10
1914 self.assertEqual(f.foo, 0)
1915 del f.foo
1916
1917 def test_dict_constructors(self):
1918 # Testing dict constructor ...
1919 d = dict()
1920 self.assertEqual(d, {})
1921 d = dict({})
1922 self.assertEqual(d, {})
1923 d = dict({1: 2, 'a': 'b'})
1924 self.assertEqual(d, {1: 2, 'a': 'b'})
1925 self.assertEqual(d, dict(list(d.items())))
1926 self.assertEqual(d, dict(iter(d.items())))
1927 d = dict({'one':1, 'two':2})
1928 self.assertEqual(d, dict(one=1, two=2))
1929 self.assertEqual(d, dict(**d))
1930 self.assertEqual(d, dict({"one": 1}, two=2))
1931 self.assertEqual(d, dict([("two", 2)], one=1))
1932 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
1933 self.assertEqual(d, dict(**d))
1934
1935 for badarg in 0, 0, 0j, "0", [0], (0,):
1936 try:
1937 dict(badarg)
1938 except TypeError:
1939 pass
1940 except ValueError:
1941 if badarg == "0":
1942 # It's a sequence, and its elements are also sequences (gotta
1943 # love strings <wink>), but they aren't of length 2, so this
1944 # one seemed better as a ValueError than a TypeError.
1945 pass
1946 else:
1947 self.fail("no TypeError from dict(%r)" % badarg)
1948 else:
1949 self.fail("no TypeError from dict(%r)" % badarg)
1950
1951 try:
1952 dict({}, {})
1953 except TypeError:
1954 pass
1955 else:
1956 self.fail("no TypeError from dict({}, {})")
1957
1958 class Mapping:
1959 # Lacks a .keys() method; will be added later.
1960 dict = {1:2, 3:4, 'a':1j}
1961
1962 try:
1963 dict(Mapping())
1964 except TypeError:
1965 pass
1966 else:
1967 self.fail("no TypeError from dict(incomplete mapping)")
1968
1969 Mapping.keys = lambda self: list(self.dict.keys())
1970 Mapping.__getitem__ = lambda self, i: self.dict[i]
1971 d = dict(Mapping())
1972 self.assertEqual(d, Mapping.dict)
1973
1974 # Init from sequence of iterable objects, each producing a 2-sequence.
1975 class AddressBookEntry:
1976 def __init__(self, first, last):
1977 self.first = first
1978 self.last = last
1979 def __iter__(self):
1980 return iter([self.first, self.last])
1981
1982 d = dict([AddressBookEntry('Tim', 'Warsaw'),
1983 AddressBookEntry('Barry', 'Peters'),
1984 AddressBookEntry('Tim', 'Peters'),
1985 AddressBookEntry('Barry', 'Warsaw')])
1986 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
1987
1988 d = dict(zip(range(4), range(1, 5)))
1989 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
1990
1991 # Bad sequence lengths.
1992 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
1993 try:
1994 dict(bad)
1995 except ValueError:
1996 pass
1997 else:
1998 self.fail("no ValueError from dict(%r)" % bad)
1999
2000 def test_dir(self):
2001 # Testing dir() ...
2002 junk = 12
2003 self.assertEqual(dir(), ['junk', 'self'])
2004 del junk
2005
2006 # Just make sure these don't blow up!
2007 for arg in 2, 2, 2j, 2e0, [2], "2", b"2", (2,), {2:2}, type, self.test_dir:
2008 dir(arg)
2009
2010 # Test dir on new-style classes. Since these have object as a
2011 # base class, a lot more gets sucked in.
2012 def interesting(strings):
2013 return [s for s in strings if not s.startswith('_')]
2014
2015 class C(object):
2016 Cdata = 1
2017 def Cmethod(self): pass
2018
2019 cstuff = ['Cdata', 'Cmethod']
2020 self.assertEqual(interesting(dir(C)), cstuff)
2021
2022 c = C()
2023 self.assertEqual(interesting(dir(c)), cstuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002024 ## self.assertIn('__self__', dir(C.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002025
2026 c.cdata = 2
2027 c.cmethod = lambda self: 0
2028 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002029 ## self.assertIn('__self__', dir(c.Cmethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002030
2031 class A(C):
2032 Adata = 1
2033 def Amethod(self): pass
2034
2035 astuff = ['Adata', 'Amethod'] + cstuff
2036 self.assertEqual(interesting(dir(A)), astuff)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002037 ## self.assertIn('__self__', dir(A.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002038 a = A()
2039 self.assertEqual(interesting(dir(a)), astuff)
2040 a.adata = 42
2041 a.amethod = lambda self: 3
2042 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Benjamin Peterson577473f2010-01-19 00:09:57 +00002043 ## self.assertIn('__self__', dir(a.Amethod))
Georg Brandl479a7e72008-02-05 18:13:15 +00002044
2045 # Try a module subclass.
Georg Brandl479a7e72008-02-05 18:13:15 +00002046 class M(type(sys)):
2047 pass
2048 minstance = M("m")
2049 minstance.b = 2
2050 minstance.a = 1
2051 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2052 self.assertEqual(names, ['a', 'b'])
2053
2054 class M2(M):
2055 def getdict(self):
2056 return "Not a dict!"
2057 __dict__ = property(getdict)
2058
2059 m2instance = M2("m2")
2060 m2instance.b = 2
2061 m2instance.a = 1
2062 self.assertEqual(m2instance.__dict__, "Not a dict!")
2063 try:
2064 dir(m2instance)
2065 except TypeError:
2066 pass
2067
2068 # Two essentially featureless objects, just inheriting stuff from
2069 # object.
Benjamin Petersone549ead2009-03-28 21:42:05 +00002070 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
Georg Brandl479a7e72008-02-05 18:13:15 +00002071
2072 # Nasty test case for proxied objects
2073 class Wrapper(object):
2074 def __init__(self, obj):
2075 self.__obj = obj
2076 def __repr__(self):
2077 return "Wrapper(%s)" % repr(self.__obj)
2078 def __getitem__(self, key):
2079 return Wrapper(self.__obj[key])
2080 def __len__(self):
2081 return len(self.__obj)
2082 def __getattr__(self, name):
2083 return Wrapper(getattr(self.__obj, name))
2084
2085 class C(object):
2086 def __getclass(self):
2087 return Wrapper(type(self))
2088 __class__ = property(__getclass)
2089
2090 dir(C()) # This used to segfault
2091
2092 def test_supers(self):
2093 # Testing super...
2094
2095 class A(object):
2096 def meth(self, a):
2097 return "A(%r)" % a
2098
2099 self.assertEqual(A().meth(1), "A(1)")
2100
2101 class B(A):
2102 def __init__(self):
2103 self.__super = super(B, self)
2104 def meth(self, a):
2105 return "B(%r)" % a + self.__super.meth(a)
2106
2107 self.assertEqual(B().meth(2), "B(2)A(2)")
2108
2109 class C(A):
2110 def meth(self, a):
2111 return "C(%r)" % a + self.__super.meth(a)
2112 C._C__super = super(C)
2113
2114 self.assertEqual(C().meth(3), "C(3)A(3)")
2115
2116 class D(C, B):
2117 def meth(self, a):
2118 return "D(%r)" % a + super(D, self).meth(a)
2119
2120 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2121
2122 # Test for subclassing super
2123
2124 class mysuper(super):
2125 def __init__(self, *args):
2126 return super(mysuper, self).__init__(*args)
2127
2128 class E(D):
2129 def meth(self, a):
2130 return "E(%r)" % a + mysuper(E, self).meth(a)
2131
2132 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2133
2134 class F(E):
2135 def meth(self, a):
2136 s = self.__super # == mysuper(F, self)
2137 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2138 F._F__super = mysuper(F)
2139
2140 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2141
2142 # Make sure certain errors are raised
2143
2144 try:
2145 super(D, 42)
2146 except TypeError:
2147 pass
2148 else:
2149 self.fail("shouldn't allow super(D, 42)")
2150
2151 try:
2152 super(D, C())
2153 except TypeError:
2154 pass
2155 else:
2156 self.fail("shouldn't allow super(D, C())")
2157
2158 try:
2159 super(D).__get__(12)
2160 except TypeError:
2161 pass
2162 else:
2163 self.fail("shouldn't allow super(D).__get__(12)")
2164
2165 try:
2166 super(D).__get__(C())
2167 except TypeError:
2168 pass
2169 else:
2170 self.fail("shouldn't allow super(D).__get__(C())")
2171
2172 # Make sure data descriptors can be overridden and accessed via super
2173 # (new feature in Python 2.3)
2174
2175 class DDbase(object):
2176 def getx(self): return 42
2177 x = property(getx)
2178
2179 class DDsub(DDbase):
2180 def getx(self): return "hello"
2181 x = property(getx)
2182
2183 dd = DDsub()
2184 self.assertEqual(dd.x, "hello")
2185 self.assertEqual(super(DDsub, dd).x, 42)
2186
2187 # Ensure that super() lookup of descriptor from classmethod
2188 # works (SF ID# 743627)
2189
2190 class Base(object):
2191 aProp = property(lambda self: "foo")
2192
2193 class Sub(Base):
2194 @classmethod
2195 def test(klass):
2196 return super(Sub,klass).aProp
2197
2198 self.assertEqual(Sub.test(), Base.aProp)
2199
2200 # Verify that super() doesn't allow keyword args
2201 try:
2202 super(Base, kw=1)
2203 except TypeError:
2204 pass
2205 else:
2206 self.assertEqual("super shouldn't accept keyword args")
2207
2208 def test_basic_inheritance(self):
2209 # Testing inheritance from basic types...
2210
2211 class hexint(int):
2212 def __repr__(self):
2213 return hex(self)
2214 def __add__(self, other):
2215 return hexint(int.__add__(self, other))
2216 # (Note that overriding __radd__ doesn't work,
2217 # because the int type gets first dibs.)
2218 self.assertEqual(repr(hexint(7) + 9), "0x10")
2219 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2220 a = hexint(12345)
2221 self.assertEqual(a, 12345)
2222 self.assertEqual(int(a), 12345)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002223 self.assertTrue(int(a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002224 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002225 self.assertTrue((+a).__class__ is int)
2226 self.assertTrue((a >> 0).__class__ is int)
2227 self.assertTrue((a << 0).__class__ is int)
2228 self.assertTrue((hexint(0) << 12).__class__ is int)
2229 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002230
2231 class octlong(int):
2232 __slots__ = []
2233 def __str__(self):
Mark Dickinson5c2db372009-12-05 20:28:34 +00002234 return oct(self)
Georg Brandl479a7e72008-02-05 18:13:15 +00002235 def __add__(self, other):
2236 return self.__class__(super(octlong, self).__add__(other))
2237 __radd__ = __add__
2238 self.assertEqual(str(octlong(3) + 5), "0o10")
2239 # (Note that overriding __radd__ here only seems to work
2240 # because the example uses a short int left argument.)
2241 self.assertEqual(str(5 + octlong(3000)), "0o5675")
2242 a = octlong(12345)
2243 self.assertEqual(a, 12345)
2244 self.assertEqual(int(a), 12345)
2245 self.assertEqual(hash(a), hash(12345))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002246 self.assertTrue(int(a).__class__ is int)
2247 self.assertTrue((+a).__class__ is int)
2248 self.assertTrue((-a).__class__ is int)
2249 self.assertTrue((-octlong(0)).__class__ is int)
2250 self.assertTrue((a >> 0).__class__ is int)
2251 self.assertTrue((a << 0).__class__ is int)
2252 self.assertTrue((a - 0).__class__ is int)
2253 self.assertTrue((a * 1).__class__ is int)
2254 self.assertTrue((a ** 1).__class__ is int)
2255 self.assertTrue((a // 1).__class__ is int)
2256 self.assertTrue((1 * a).__class__ is int)
2257 self.assertTrue((a | 0).__class__ is int)
2258 self.assertTrue((a ^ 0).__class__ is int)
2259 self.assertTrue((a & -1).__class__ is int)
2260 self.assertTrue((octlong(0) << 12).__class__ is int)
2261 self.assertTrue((octlong(0) >> 12).__class__ is int)
2262 self.assertTrue(abs(octlong(0)).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002263
2264 # Because octlong overrides __add__, we can't check the absence of +0
2265 # optimizations using octlong.
2266 class longclone(int):
2267 pass
2268 a = longclone(1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002269 self.assertTrue((a + 0).__class__ is int)
2270 self.assertTrue((0 + a).__class__ is int)
Georg Brandl479a7e72008-02-05 18:13:15 +00002271
2272 # Check that negative clones don't segfault
2273 a = longclone(-1)
2274 self.assertEqual(a.__dict__, {})
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002275 self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl479a7e72008-02-05 18:13:15 +00002276
2277 class precfloat(float):
2278 __slots__ = ['prec']
2279 def __init__(self, value=0.0, prec=12):
2280 self.prec = int(prec)
2281 def __repr__(self):
2282 return "%.*g" % (self.prec, self)
2283 self.assertEqual(repr(precfloat(1.1)), "1.1")
2284 a = precfloat(12345)
2285 self.assertEqual(a, 12345.0)
2286 self.assertEqual(float(a), 12345.0)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002287 self.assertTrue(float(a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002288 self.assertEqual(hash(a), hash(12345.0))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002289 self.assertTrue((+a).__class__ is float)
Georg Brandl479a7e72008-02-05 18:13:15 +00002290
2291 class madcomplex(complex):
2292 def __repr__(self):
2293 return "%.17gj%+.17g" % (self.imag, self.real)
2294 a = madcomplex(-3, 4)
2295 self.assertEqual(repr(a), "4j-3")
2296 base = complex(-3, 4)
2297 self.assertEqual(base.__class__, complex)
2298 self.assertEqual(a, base)
2299 self.assertEqual(complex(a), base)
2300 self.assertEqual(complex(a).__class__, complex)
2301 a = madcomplex(a) # just trying another form of the constructor
2302 self.assertEqual(repr(a), "4j-3")
2303 self.assertEqual(a, base)
2304 self.assertEqual(complex(a), base)
2305 self.assertEqual(complex(a).__class__, complex)
2306 self.assertEqual(hash(a), hash(base))
2307 self.assertEqual((+a).__class__, complex)
2308 self.assertEqual((a + 0).__class__, complex)
2309 self.assertEqual(a + 0, base)
2310 self.assertEqual((a - 0).__class__, complex)
2311 self.assertEqual(a - 0, base)
2312 self.assertEqual((a * 1).__class__, complex)
2313 self.assertEqual(a * 1, base)
2314 self.assertEqual((a / 1).__class__, complex)
2315 self.assertEqual(a / 1, base)
2316
2317 class madtuple(tuple):
2318 _rev = None
2319 def rev(self):
2320 if self._rev is not None:
2321 return self._rev
2322 L = list(self)
2323 L.reverse()
2324 self._rev = self.__class__(L)
2325 return self._rev
2326 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2327 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2328 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2329 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2330 for i in range(512):
2331 t = madtuple(range(i))
2332 u = t.rev()
2333 v = u.rev()
2334 self.assertEqual(v, t)
2335 a = madtuple((1,2,3,4,5))
2336 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002337 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002338 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002339 self.assertTrue(a[:].__class__ is tuple)
2340 self.assertTrue((a * 1).__class__ is tuple)
2341 self.assertTrue((a * 0).__class__ is tuple)
2342 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002343 a = madtuple(())
2344 self.assertEqual(tuple(a), ())
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002345 self.assertTrue(tuple(a).__class__ is tuple)
2346 self.assertTrue((a + a).__class__ is tuple)
2347 self.assertTrue((a * 0).__class__ is tuple)
2348 self.assertTrue((a * 1).__class__ is tuple)
2349 self.assertTrue((a * 2).__class__ is tuple)
2350 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl479a7e72008-02-05 18:13:15 +00002351
2352 class madstring(str):
2353 _rev = None
2354 def rev(self):
2355 if self._rev is not None:
2356 return self._rev
2357 L = list(self)
2358 L.reverse()
2359 self._rev = self.__class__("".join(L))
2360 return self._rev
2361 s = madstring("abcdefghijklmnopqrstuvwxyz")
2362 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2363 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2364 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2365 for i in range(256):
2366 s = madstring("".join(map(chr, range(i))))
2367 t = s.rev()
2368 u = t.rev()
2369 self.assertEqual(u, s)
2370 s = madstring("12345")
2371 self.assertEqual(str(s), "12345")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002372 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002373
2374 base = "\x00" * 5
2375 s = madstring(base)
2376 self.assertEqual(s, base)
2377 self.assertEqual(str(s), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002378 self.assertTrue(str(s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002379 self.assertEqual(hash(s), hash(base))
2380 self.assertEqual({s: 1}[base], 1)
2381 self.assertEqual({base: 1}[s], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002382 self.assertTrue((s + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002383 self.assertEqual(s + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002384 self.assertTrue(("" + s).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002385 self.assertEqual("" + s, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002386 self.assertTrue((s * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002387 self.assertEqual(s * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002388 self.assertTrue((s * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002389 self.assertEqual(s * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002390 self.assertTrue((s * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002391 self.assertEqual(s * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002392 self.assertTrue(s[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002393 self.assertEqual(s[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002394 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002395 self.assertEqual(s[0:0], "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002396 self.assertTrue(s.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002397 self.assertEqual(s.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002398 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002399 self.assertEqual(s.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002400 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002401 self.assertEqual(s.rstrip(), base)
2402 identitytab = {}
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002403 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002404 self.assertEqual(s.translate(identitytab), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002405 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002406 self.assertEqual(s.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002407 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002408 self.assertEqual(s.ljust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002409 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002410 self.assertEqual(s.rjust(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002411 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002412 self.assertEqual(s.center(len(s)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002413 self.assertTrue(s.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002414 self.assertEqual(s.lower(), base)
2415
2416 class madunicode(str):
2417 _rev = None
2418 def rev(self):
2419 if self._rev is not None:
2420 return self._rev
2421 L = list(self)
2422 L.reverse()
2423 self._rev = self.__class__("".join(L))
2424 return self._rev
2425 u = madunicode("ABCDEF")
2426 self.assertEqual(u, "ABCDEF")
2427 self.assertEqual(u.rev(), madunicode("FEDCBA"))
2428 self.assertEqual(u.rev().rev(), madunicode("ABCDEF"))
2429 base = "12345"
2430 u = madunicode(base)
2431 self.assertEqual(str(u), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002432 self.assertTrue(str(u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002433 self.assertEqual(hash(u), hash(base))
2434 self.assertEqual({u: 1}[base], 1)
2435 self.assertEqual({base: 1}[u], 1)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002436 self.assertTrue(u.strip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002437 self.assertEqual(u.strip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002438 self.assertTrue(u.lstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002439 self.assertEqual(u.lstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002440 self.assertTrue(u.rstrip().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002441 self.assertEqual(u.rstrip(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002442 self.assertTrue(u.replace("x", "x").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002443 self.assertEqual(u.replace("x", "x"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002444 self.assertTrue(u.replace("xy", "xy").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002445 self.assertEqual(u.replace("xy", "xy"), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002446 self.assertTrue(u.center(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002447 self.assertEqual(u.center(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002448 self.assertTrue(u.ljust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002449 self.assertEqual(u.ljust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002450 self.assertTrue(u.rjust(len(u)).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002451 self.assertEqual(u.rjust(len(u)), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002452 self.assertTrue(u.lower().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002453 self.assertEqual(u.lower(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002454 self.assertTrue(u.upper().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002455 self.assertEqual(u.upper(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002456 self.assertTrue(u.capitalize().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002457 self.assertEqual(u.capitalize(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002458 self.assertTrue(u.title().__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002459 self.assertEqual(u.title(), base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002460 self.assertTrue((u + "").__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002461 self.assertEqual(u + "", base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002462 self.assertTrue(("" + u).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002463 self.assertEqual("" + u, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002464 self.assertTrue((u * 0).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002465 self.assertEqual(u * 0, "")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002466 self.assertTrue((u * 1).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002467 self.assertEqual(u * 1, base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002468 self.assertTrue((u * 2).__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002469 self.assertEqual(u * 2, base + base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002470 self.assertTrue(u[:].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002471 self.assertEqual(u[:], base)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002472 self.assertTrue(u[0:0].__class__ is str)
Georg Brandl479a7e72008-02-05 18:13:15 +00002473 self.assertEqual(u[0:0], "")
2474
2475 class sublist(list):
2476 pass
2477 a = sublist(range(5))
2478 self.assertEqual(a, list(range(5)))
2479 a.append("hello")
2480 self.assertEqual(a, list(range(5)) + ["hello"])
2481 a[5] = 5
2482 self.assertEqual(a, list(range(6)))
2483 a.extend(range(6, 20))
2484 self.assertEqual(a, list(range(20)))
2485 a[-5:] = []
2486 self.assertEqual(a, list(range(15)))
2487 del a[10:15]
2488 self.assertEqual(len(a), 10)
2489 self.assertEqual(a, list(range(10)))
2490 self.assertEqual(list(a), list(range(10)))
2491 self.assertEqual(a[0], 0)
2492 self.assertEqual(a[9], 9)
2493 self.assertEqual(a[-10], 0)
2494 self.assertEqual(a[-1], 9)
2495 self.assertEqual(a[:5], list(range(5)))
2496
2497 ## class CountedInput(file):
2498 ## """Counts lines read by self.readline().
2499 ##
2500 ## self.lineno is the 0-based ordinal of the last line read, up to
2501 ## a maximum of one greater than the number of lines in the file.
2502 ##
2503 ## self.ateof is true if and only if the final "" line has been read,
2504 ## at which point self.lineno stops incrementing, and further calls
2505 ## to readline() continue to return "".
2506 ## """
2507 ##
2508 ## lineno = 0
2509 ## ateof = 0
2510 ## def readline(self):
2511 ## if self.ateof:
2512 ## return ""
2513 ## s = file.readline(self)
2514 ## # Next line works too.
2515 ## # s = super(CountedInput, self).readline()
2516 ## self.lineno += 1
2517 ## if s == "":
2518 ## self.ateof = 1
2519 ## return s
2520 ##
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002521 ## f = file(name=support.TESTFN, mode='w')
Georg Brandl479a7e72008-02-05 18:13:15 +00002522 ## lines = ['a\n', 'b\n', 'c\n']
2523 ## try:
2524 ## f.writelines(lines)
2525 ## f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002526 ## f = CountedInput(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002527 ## for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2528 ## got = f.readline()
2529 ## self.assertEqual(expected, got)
2530 ## self.assertEqual(f.lineno, i)
2531 ## self.assertEqual(f.ateof, (i > len(lines)))
2532 ## f.close()
2533 ## finally:
2534 ## try:
2535 ## f.close()
2536 ## except:
2537 ## pass
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002538 ## support.unlink(support.TESTFN)
Georg Brandl479a7e72008-02-05 18:13:15 +00002539
2540 def test_keywords(self):
2541 # Testing keyword args to basic type constructors ...
2542 self.assertEqual(int(x=1), 1)
2543 self.assertEqual(float(x=2), 2.0)
2544 self.assertEqual(int(x=3), 3)
2545 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2546 self.assertEqual(str(object=500), '500')
2547 self.assertEqual(str(object=b'abc', errors='strict'), 'abc')
2548 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2549 self.assertEqual(list(sequence=(0, 1, 2)), list(range(3)))
2550 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2551
2552 for constructor in (int, float, int, complex, str, str,
2553 tuple, list):
2554 try:
2555 constructor(bogus_keyword_arg=1)
2556 except TypeError:
2557 pass
2558 else:
2559 self.fail("expected TypeError from bogus keyword argument to %r"
2560 % constructor)
2561
2562 def test_str_subclass_as_dict_key(self):
2563 # Testing a str subclass used as dict key ..
2564
2565 class cistr(str):
2566 """Sublcass of str that computes __eq__ case-insensitively.
2567
2568 Also computes a hash code of the string in canonical form.
2569 """
2570
2571 def __init__(self, value):
2572 self.canonical = value.lower()
2573 self.hashcode = hash(self.canonical)
2574
2575 def __eq__(self, other):
2576 if not isinstance(other, cistr):
2577 other = cistr(other)
2578 return self.canonical == other.canonical
2579
2580 def __hash__(self):
2581 return self.hashcode
2582
2583 self.assertEqual(cistr('ABC'), 'abc')
2584 self.assertEqual('aBc', cistr('ABC'))
2585 self.assertEqual(str(cistr('ABC')), 'ABC')
2586
2587 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2588 self.assertEqual(d[cistr('one')], 1)
2589 self.assertEqual(d[cistr('tWo')], 2)
2590 self.assertEqual(d[cistr('THrEE')], 3)
Benjamin Peterson577473f2010-01-19 00:09:57 +00002591 self.assertIn(cistr('ONe'), d)
Georg Brandl479a7e72008-02-05 18:13:15 +00002592 self.assertEqual(d.get(cistr('thrEE')), 3)
2593
2594 def test_classic_comparisons(self):
2595 # Testing classic comparisons...
2596 class classic:
2597 pass
2598
2599 for base in (classic, int, object):
2600 class C(base):
2601 def __init__(self, value):
2602 self.value = int(value)
2603 def __eq__(self, other):
2604 if isinstance(other, C):
2605 return self.value == other.value
2606 if isinstance(other, int) or isinstance(other, int):
2607 return self.value == other
2608 return NotImplemented
2609 def __ne__(self, other):
2610 if isinstance(other, C):
2611 return self.value != other.value
2612 if isinstance(other, int) or isinstance(other, int):
2613 return self.value != other
2614 return NotImplemented
2615 def __lt__(self, other):
2616 if isinstance(other, C):
2617 return self.value < other.value
2618 if isinstance(other, int) or isinstance(other, int):
2619 return self.value < other
2620 return NotImplemented
2621 def __le__(self, other):
2622 if isinstance(other, C):
2623 return self.value <= other.value
2624 if isinstance(other, int) or isinstance(other, int):
2625 return self.value <= other
2626 return NotImplemented
2627 def __gt__(self, other):
2628 if isinstance(other, C):
2629 return self.value > other.value
2630 if isinstance(other, int) or isinstance(other, int):
2631 return self.value > other
2632 return NotImplemented
2633 def __ge__(self, other):
2634 if isinstance(other, C):
2635 return self.value >= other.value
2636 if isinstance(other, int) or isinstance(other, int):
2637 return self.value >= other
2638 return NotImplemented
2639
2640 c1 = C(1)
2641 c2 = C(2)
2642 c3 = C(3)
2643 self.assertEqual(c1, 1)
2644 c = {1: c1, 2: c2, 3: c3}
2645 for x in 1, 2, 3:
2646 for y in 1, 2, 3:
Georg Brandl479a7e72008-02-05 18:13:15 +00002647 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002648 self.assertTrue(eval("c[x] %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002649 eval("x %s y" % op),
2650 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002651 self.assertTrue(eval("c[x] %s y" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002652 eval("x %s y" % op),
2653 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002654 self.assertTrue(eval("x %s c[y]" % op) ==
Mark Dickinsona56c4672009-01-27 18:17:45 +00002655 eval("x %s y" % op),
2656 "x=%d, y=%d" % (x, y))
Georg Brandl479a7e72008-02-05 18:13:15 +00002657
2658 def test_rich_comparisons(self):
2659 # Testing rich comparisons...
2660 class Z(complex):
2661 pass
2662 z = Z(1)
2663 self.assertEqual(z, 1+0j)
2664 self.assertEqual(1+0j, z)
2665 class ZZ(complex):
2666 def __eq__(self, other):
2667 try:
2668 return abs(self - other) <= 1e-6
2669 except:
2670 return NotImplemented
2671 zz = ZZ(1.0000003)
2672 self.assertEqual(zz, 1+0j)
2673 self.assertEqual(1+0j, zz)
2674
2675 class classic:
2676 pass
2677 for base in (classic, int, object, list):
2678 class C(base):
2679 def __init__(self, value):
2680 self.value = int(value)
2681 def __cmp__(self_, other):
2682 self.fail("shouldn't call __cmp__")
2683 def __eq__(self, other):
2684 if isinstance(other, C):
2685 return self.value == other.value
2686 if isinstance(other, int) or isinstance(other, int):
2687 return self.value == other
2688 return NotImplemented
2689 def __ne__(self, other):
2690 if isinstance(other, C):
2691 return self.value != other.value
2692 if isinstance(other, int) or isinstance(other, int):
2693 return self.value != other
2694 return NotImplemented
2695 def __lt__(self, other):
2696 if isinstance(other, C):
2697 return self.value < other.value
2698 if isinstance(other, int) or isinstance(other, int):
2699 return self.value < other
2700 return NotImplemented
2701 def __le__(self, other):
2702 if isinstance(other, C):
2703 return self.value <= other.value
2704 if isinstance(other, int) or isinstance(other, int):
2705 return self.value <= other
2706 return NotImplemented
2707 def __gt__(self, other):
2708 if isinstance(other, C):
2709 return self.value > other.value
2710 if isinstance(other, int) or isinstance(other, int):
2711 return self.value > other
2712 return NotImplemented
2713 def __ge__(self, other):
2714 if isinstance(other, C):
2715 return self.value >= other.value
2716 if isinstance(other, int) or isinstance(other, int):
2717 return self.value >= other
2718 return NotImplemented
2719 c1 = C(1)
2720 c2 = C(2)
2721 c3 = C(3)
2722 self.assertEqual(c1, 1)
2723 c = {1: c1, 2: c2, 3: c3}
2724 for x in 1, 2, 3:
2725 for y in 1, 2, 3:
2726 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002727 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002728 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002729 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002730 "x=%d, y=%d" % (x, y))
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002731 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl479a7e72008-02-05 18:13:15 +00002732 "x=%d, y=%d" % (x, y))
2733
2734 def test_descrdoc(self):
2735 # Testing descriptor doc strings...
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002736 from _io import FileIO
Georg Brandl479a7e72008-02-05 18:13:15 +00002737 def check(descr, what):
2738 self.assertEqual(descr.__doc__, what)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00002739 check(FileIO.closed, "True if the file is closed") # getset descriptor
Georg Brandl479a7e72008-02-05 18:13:15 +00002740 check(complex.real, "the real part of a complex number") # member descriptor
2741
2742 def test_doc_descriptor(self):
2743 # Testing __doc__ descriptor...
2744 # SF bug 542984
2745 class DocDescr(object):
2746 def __get__(self, object, otype):
2747 if object:
2748 object = object.__class__.__name__ + ' instance'
2749 if otype:
2750 otype = otype.__name__
2751 return 'object=%s; type=%s' % (object, otype)
2752 class OldClass:
2753 __doc__ = DocDescr()
2754 class NewClass(object):
2755 __doc__ = DocDescr()
2756 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
2757 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
2758 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
2759 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
2760
2761 def test_set_class(self):
2762 # Testing __class__ assignment...
2763 class C(object): pass
2764 class D(object): pass
2765 class E(object): pass
2766 class F(D, E): pass
2767 for cls in C, D, E, F:
2768 for cls2 in C, D, E, F:
2769 x = cls()
2770 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002771 self.assertTrue(x.__class__ is cls2)
Georg Brandl479a7e72008-02-05 18:13:15 +00002772 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002773 self.assertTrue(x.__class__ is cls)
Georg Brandl479a7e72008-02-05 18:13:15 +00002774 def cant(x, C):
2775 try:
2776 x.__class__ = C
2777 except TypeError:
2778 pass
2779 else:
2780 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
2781 try:
2782 delattr(x, "__class__")
Benjamin Petersone549ead2009-03-28 21:42:05 +00002783 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00002784 pass
2785 else:
2786 self.fail("shouldn't allow del %r.__class__" % x)
2787 cant(C(), list)
2788 cant(list(), C)
2789 cant(C(), 1)
2790 cant(C(), object)
2791 cant(object(), list)
2792 cant(list(), object)
2793 class Int(int): __slots__ = []
2794 cant(2, Int)
2795 cant(Int(), int)
2796 cant(True, int)
2797 cant(2, bool)
2798 o = object()
2799 cant(o, type(1))
2800 cant(o, type(None))
2801 del o
2802 class G(object):
2803 __slots__ = ["a", "b"]
2804 class H(object):
2805 __slots__ = ["b", "a"]
2806 class I(object):
2807 __slots__ = ["a", "b"]
2808 class J(object):
2809 __slots__ = ["c", "b"]
2810 class K(object):
2811 __slots__ = ["a", "b", "d"]
2812 class L(H):
2813 __slots__ = ["e"]
2814 class M(I):
2815 __slots__ = ["e"]
2816 class N(J):
2817 __slots__ = ["__weakref__"]
2818 class P(J):
2819 __slots__ = ["__dict__"]
2820 class Q(J):
2821 pass
2822 class R(J):
2823 __slots__ = ["__dict__", "__weakref__"]
2824
2825 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
2826 x = cls()
2827 x.a = 1
2828 x.__class__ = cls2
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002829 self.assertTrue(x.__class__ is cls2,
Georg Brandl479a7e72008-02-05 18:13:15 +00002830 "assigning %r as __class__ for %r silently failed" % (cls2, x))
2831 self.assertEqual(x.a, 1)
2832 x.__class__ = cls
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00002833 self.assertTrue(x.__class__ is cls,
Georg Brandl479a7e72008-02-05 18:13:15 +00002834 "assigning %r as __class__ for %r silently failed" % (cls, x))
2835 self.assertEqual(x.a, 1)
2836 for cls in G, J, K, L, M, N, P, R, list, Int:
2837 for cls2 in G, J, K, L, M, N, P, R, list, Int:
2838 if cls is cls2:
2839 continue
2840 cant(cls(), cls2)
2841
Benjamin Peterson193152c2009-04-25 01:08:45 +00002842 # Issue5283: when __class__ changes in __del__, the wrong
2843 # type gets DECREF'd.
2844 class O(object):
2845 pass
2846 class A(object):
2847 def __del__(self):
2848 self.__class__ = O
2849 l = [A() for x in range(100)]
2850 del l
2851
Georg Brandl479a7e72008-02-05 18:13:15 +00002852 def test_set_dict(self):
2853 # Testing __dict__ assignment...
2854 class C(object): pass
2855 a = C()
2856 a.__dict__ = {'b': 1}
2857 self.assertEqual(a.b, 1)
2858 def cant(x, dict):
2859 try:
2860 x.__dict__ = dict
2861 except (AttributeError, TypeError):
2862 pass
2863 else:
2864 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
2865 cant(a, None)
2866 cant(a, [])
2867 cant(a, 1)
2868 del a.__dict__ # Deleting __dict__ is allowed
2869
2870 class Base(object):
2871 pass
2872 def verify_dict_readonly(x):
2873 """
2874 x has to be an instance of a class inheriting from Base.
2875 """
2876 cant(x, {})
2877 try:
2878 del x.__dict__
2879 except (AttributeError, TypeError):
2880 pass
2881 else:
2882 self.fail("shouldn't allow del %r.__dict__" % x)
2883 dict_descr = Base.__dict__["__dict__"]
2884 try:
2885 dict_descr.__set__(x, {})
2886 except (AttributeError, TypeError):
2887 pass
2888 else:
2889 self.fail("dict_descr allowed access to %r's dict" % x)
2890
2891 # Classes don't allow __dict__ assignment and have readonly dicts
2892 class Meta1(type, Base):
2893 pass
2894 class Meta2(Base, type):
2895 pass
2896 class D(object, metaclass=Meta1):
2897 pass
2898 class E(object, metaclass=Meta2):
2899 pass
2900 for cls in C, D, E:
2901 verify_dict_readonly(cls)
2902 class_dict = cls.__dict__
2903 try:
2904 class_dict["spam"] = "eggs"
2905 except TypeError:
2906 pass
2907 else:
2908 self.fail("%r's __dict__ can be modified" % cls)
2909
2910 # Modules also disallow __dict__ assignment
2911 class Module1(types.ModuleType, Base):
2912 pass
2913 class Module2(Base, types.ModuleType):
2914 pass
2915 for ModuleType in Module1, Module2:
2916 mod = ModuleType("spam")
2917 verify_dict_readonly(mod)
2918 mod.__dict__["spam"] = "eggs"
2919
2920 # Exception's __dict__ can be replaced, but not deleted
Benjamin Petersone549ead2009-03-28 21:42:05 +00002921 # (at least not any more than regular exception's __dict__ can
2922 # be deleted; on CPython it is not the case, whereas on PyPy they
2923 # can, just like any other new-style instance's __dict__.)
2924 def can_delete_dict(e):
2925 try:
2926 del e.__dict__
2927 except (TypeError, AttributeError):
2928 return False
2929 else:
2930 return True
Georg Brandl479a7e72008-02-05 18:13:15 +00002931 class Exception1(Exception, Base):
2932 pass
2933 class Exception2(Base, Exception):
2934 pass
2935 for ExceptionType in Exception, Exception1, Exception2:
2936 e = ExceptionType()
2937 e.__dict__ = {"a": 1}
2938 self.assertEqual(e.a, 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00002939 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl479a7e72008-02-05 18:13:15 +00002940
2941 def test_pickles(self):
2942 # Testing pickling and copying new-style classes and objects...
2943 import pickle
2944
2945 def sorteditems(d):
2946 L = list(d.items())
2947 L.sort()
2948 return L
2949
2950 global C
2951 class C(object):
2952 def __init__(self, a, b):
2953 super(C, self).__init__()
2954 self.a = a
2955 self.b = b
2956 def __repr__(self):
2957 return "C(%r, %r)" % (self.a, self.b)
2958
2959 global C1
2960 class C1(list):
2961 def __new__(cls, a, b):
2962 return super(C1, cls).__new__(cls)
2963 def __getnewargs__(self):
2964 return (self.a, self.b)
2965 def __init__(self, a, b):
2966 self.a = a
2967 self.b = b
2968 def __repr__(self):
2969 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
2970
2971 global C2
2972 class C2(int):
2973 def __new__(cls, a, b, val=0):
2974 return super(C2, cls).__new__(cls, val)
2975 def __getnewargs__(self):
2976 return (self.a, self.b, int(self))
2977 def __init__(self, a, b, val=0):
2978 self.a = a
2979 self.b = b
2980 def __repr__(self):
2981 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
2982
2983 global C3
2984 class C3(object):
2985 def __init__(self, foo):
2986 self.foo = foo
2987 def __getstate__(self):
2988 return self.foo
2989 def __setstate__(self, foo):
2990 self.foo = foo
2991
2992 global C4classic, C4
2993 class C4classic: # classic
2994 pass
2995 class C4(C4classic, object): # mixed inheritance
2996 pass
2997
Guido van Rossum3926a632001-09-25 16:25:58 +00002998 for bin in 0, 1:
Guido van Rossum3926a632001-09-25 16:25:58 +00002999 for cls in C, C1, C2:
Georg Brandl479a7e72008-02-05 18:13:15 +00003000 s = pickle.dumps(cls, bin)
3001 cls2 = pickle.loads(s)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003002 self.assertTrue(cls2 is cls)
Guido van Rossum3926a632001-09-25 16:25:58 +00003003
3004 a = C1(1, 2); a.append(42); a.append(24)
3005 b = C2("hello", "world", 42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003006 s = pickle.dumps((a, b), bin)
3007 x, y = pickle.loads(s)
3008 self.assertEqual(x.__class__, a.__class__)
3009 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3010 self.assertEqual(y.__class__, b.__class__)
3011 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3012 self.assertEqual(repr(x), repr(a))
3013 self.assertEqual(repr(y), repr(b))
Guido van Rossum90c45142001-11-24 21:07:01 +00003014 # Test for __getstate__ and __setstate__ on new style class
3015 u = C3(42)
Georg Brandl479a7e72008-02-05 18:13:15 +00003016 s = pickle.dumps(u, bin)
3017 v = pickle.loads(s)
3018 self.assertEqual(u.__class__, v.__class__)
3019 self.assertEqual(u.foo, v.foo)
Guido van Rossum90c45142001-11-24 21:07:01 +00003020 # Test for picklability of hybrid class
3021 u = C4()
3022 u.foo = 42
Georg Brandl479a7e72008-02-05 18:13:15 +00003023 s = pickle.dumps(u, bin)
3024 v = pickle.loads(s)
3025 self.assertEqual(u.__class__, v.__class__)
3026 self.assertEqual(u.foo, v.foo)
Guido van Rossum3926a632001-09-25 16:25:58 +00003027
Georg Brandl479a7e72008-02-05 18:13:15 +00003028 # Testing copy.deepcopy()
3029 import copy
3030 for cls in C, C1, C2:
3031 cls2 = copy.deepcopy(cls)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003032 self.assertTrue(cls2 is cls)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003033
Georg Brandl479a7e72008-02-05 18:13:15 +00003034 a = C1(1, 2); a.append(42); a.append(24)
3035 b = C2("hello", "world", 42)
3036 x, y = copy.deepcopy((a, b))
3037 self.assertEqual(x.__class__, a.__class__)
3038 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3039 self.assertEqual(y.__class__, b.__class__)
3040 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3041 self.assertEqual(repr(x), repr(a))
3042 self.assertEqual(repr(y), repr(b))
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003043
Georg Brandl479a7e72008-02-05 18:13:15 +00003044 def test_pickle_slots(self):
3045 # Testing pickling of classes with __slots__ ...
3046 import pickle
3047 # Pickling of classes with __slots__ but without __getstate__ should fail
3048 # (if using protocol 0 or 1)
3049 global B, C, D, E
3050 class B(object):
Guido van Rossum8c842552002-03-14 23:05:54 +00003051 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003052 for base in [object, B]:
3053 class C(base):
3054 __slots__ = ['a']
3055 class D(C):
3056 pass
3057 try:
3058 pickle.dumps(C(), 0)
3059 except TypeError:
3060 pass
3061 else:
3062 self.fail("should fail: pickle C instance - %s" % base)
3063 try:
3064 pickle.dumps(C(), 0)
3065 except TypeError:
3066 pass
3067 else:
3068 self.fail("should fail: pickle D instance - %s" % base)
3069 # Give C a nice generic __getstate__ and __setstate__
3070 class C(base):
3071 __slots__ = ['a']
3072 def __getstate__(self):
3073 try:
3074 d = self.__dict__.copy()
3075 except AttributeError:
3076 d = {}
3077 for cls in self.__class__.__mro__:
3078 for sn in cls.__dict__.get('__slots__', ()):
3079 try:
3080 d[sn] = getattr(self, sn)
3081 except AttributeError:
3082 pass
3083 return d
3084 def __setstate__(self, d):
3085 for k, v in list(d.items()):
3086 setattr(self, k, v)
3087 class D(C):
3088 pass
3089 # Now it should work
3090 x = C()
3091 y = pickle.loads(pickle.dumps(x))
3092 self.assertEqual(hasattr(y, 'a'), 0)
3093 x.a = 42
3094 y = pickle.loads(pickle.dumps(x))
3095 self.assertEqual(y.a, 42)
3096 x = D()
3097 x.a = 42
3098 x.b = 100
3099 y = pickle.loads(pickle.dumps(x))
3100 self.assertEqual(y.a + y.b, 142)
3101 # A subclass that adds a slot should also work
3102 class E(C):
3103 __slots__ = ['b']
3104 x = E()
3105 x.a = 42
3106 x.b = "foo"
3107 y = pickle.loads(pickle.dumps(x))
3108 self.assertEqual(y.a, x.a)
3109 self.assertEqual(y.b, x.b)
3110
3111 def test_binary_operator_override(self):
3112 # Testing overrides of binary operations...
3113 class I(int):
3114 def __repr__(self):
3115 return "I(%r)" % int(self)
3116 def __add__(self, other):
3117 return I(int(self) + int(other))
3118 __radd__ = __add__
3119 def __pow__(self, other, mod=None):
3120 if mod is None:
3121 return I(pow(int(self), int(other)))
3122 else:
3123 return I(pow(int(self), int(other), int(mod)))
3124 def __rpow__(self, other, mod=None):
3125 if mod is None:
3126 return I(pow(int(other), int(self), mod))
3127 else:
3128 return I(pow(int(other), int(self), int(mod)))
3129
3130 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3131 self.assertEqual(repr(I(1) + 2), "I(3)")
3132 self.assertEqual(repr(1 + I(2)), "I(3)")
3133 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3134 self.assertEqual(repr(2 ** I(3)), "I(8)")
3135 self.assertEqual(repr(I(2) ** 3), "I(8)")
3136 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3137 class S(str):
3138 def __eq__(self, other):
3139 return self.lower() == other.lower()
3140
3141 def test_subclass_propagation(self):
3142 # Testing propagation of slot functions to subclasses...
3143 class A(object):
3144 pass
3145 class B(A):
3146 pass
3147 class C(A):
3148 pass
3149 class D(B, C):
3150 pass
3151 d = D()
3152 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3153 A.__hash__ = lambda self: 42
3154 self.assertEqual(hash(d), 42)
3155 C.__hash__ = lambda self: 314
3156 self.assertEqual(hash(d), 314)
3157 B.__hash__ = lambda self: 144
3158 self.assertEqual(hash(d), 144)
3159 D.__hash__ = lambda self: 100
3160 self.assertEqual(hash(d), 100)
Nick Coghland1abd252008-07-15 15:46:38 +00003161 D.__hash__ = None
3162 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003163 del D.__hash__
3164 self.assertEqual(hash(d), 144)
Nick Coghland1abd252008-07-15 15:46:38 +00003165 B.__hash__ = None
3166 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003167 del B.__hash__
3168 self.assertEqual(hash(d), 314)
Nick Coghland1abd252008-07-15 15:46:38 +00003169 C.__hash__ = None
3170 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003171 del C.__hash__
3172 self.assertEqual(hash(d), 42)
Nick Coghland1abd252008-07-15 15:46:38 +00003173 A.__hash__ = None
3174 self.assertRaises(TypeError, hash, d)
Georg Brandl479a7e72008-02-05 18:13:15 +00003175 del A.__hash__
3176 self.assertEqual(hash(d), orig_hash)
3177 d.foo = 42
3178 d.bar = 42
3179 self.assertEqual(d.foo, 42)
3180 self.assertEqual(d.bar, 42)
3181 def __getattribute__(self, name):
3182 if name == "foo":
3183 return 24
3184 return object.__getattribute__(self, name)
3185 A.__getattribute__ = __getattribute__
3186 self.assertEqual(d.foo, 24)
3187 self.assertEqual(d.bar, 42)
3188 def __getattr__(self, name):
3189 if name in ("spam", "foo", "bar"):
3190 return "hello"
3191 raise AttributeError(name)
3192 B.__getattr__ = __getattr__
3193 self.assertEqual(d.spam, "hello")
3194 self.assertEqual(d.foo, 24)
3195 self.assertEqual(d.bar, 42)
3196 del A.__getattribute__
3197 self.assertEqual(d.foo, 42)
3198 del d.foo
3199 self.assertEqual(d.foo, "hello")
3200 self.assertEqual(d.bar, 42)
3201 del B.__getattr__
Guido van Rossum8c842552002-03-14 23:05:54 +00003202 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003203 d.foo
3204 except AttributeError:
3205 pass
3206 else:
3207 self.fail("d.foo should be undefined now")
3208
3209 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl479a7e72008-02-05 18:13:15 +00003210 class A(object):
3211 pass
3212 class B(A):
3213 pass
3214 del B
Benjamin Petersone549ead2009-03-28 21:42:05 +00003215 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003216 A.__setitem__ = lambda *a: None # crash
3217
3218 def test_buffer_inheritance(self):
3219 # Testing that buffer interface is inherited ...
3220
3221 import binascii
3222 # SF bug [#470040] ParseTuple t# vs subclasses.
3223
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003224 class MyBytes(bytes):
Georg Brandl479a7e72008-02-05 18:13:15 +00003225 pass
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003226 base = b'abc'
3227 m = MyBytes(base)
Georg Brandl479a7e72008-02-05 18:13:15 +00003228 # b2a_hex uses the buffer interface to get its argument's value, via
3229 # PyArg_ParseTuple 't#' code.
3230 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3231
Georg Brandl479a7e72008-02-05 18:13:15 +00003232 class MyInt(int):
3233 pass
3234 m = MyInt(42)
3235 try:
3236 binascii.b2a_hex(m)
3237 self.fail('subclass of int should not have a buffer interface')
3238 except TypeError:
3239 pass
3240
3241 def test_str_of_str_subclass(self):
3242 # Testing __str__ defined in subclass of str ...
3243 import binascii
3244 import io
3245
3246 class octetstring(str):
3247 def __str__(self):
Martin v. Löwis15b16a32008-12-02 06:00:15 +00003248 return binascii.b2a_hex(self.encode('ascii')).decode("ascii")
Georg Brandl479a7e72008-02-05 18:13:15 +00003249 def __repr__(self):
3250 return self + " repr"
3251
3252 o = octetstring('A')
3253 self.assertEqual(type(o), octetstring)
3254 self.assertEqual(type(str(o)), str)
3255 self.assertEqual(type(repr(o)), str)
3256 self.assertEqual(ord(o), 0x41)
3257 self.assertEqual(str(o), '41')
3258 self.assertEqual(repr(o), 'A repr')
3259 self.assertEqual(o.__str__(), '41')
3260 self.assertEqual(o.__repr__(), 'A repr')
3261
3262 capture = io.StringIO()
3263 # Calling str() or not exercises different internal paths.
3264 print(o, file=capture)
3265 print(str(o), file=capture)
3266 self.assertEqual(capture.getvalue(), '41\n41\n')
3267 capture.close()
3268
3269 def test_keyword_arguments(self):
3270 # Testing keyword arguments to __init__, __call__...
3271 def f(a): return a
3272 self.assertEqual(f.__call__(a=42), 42)
3273 a = []
3274 list.__init__(a, sequence=[0, 1, 2])
3275 self.assertEqual(a, [0, 1, 2])
3276
3277 def test_recursive_call(self):
3278 # Testing recursive __call__() by setting to instance of class...
3279 class A(object):
3280 pass
3281
3282 A.__call__ = A()
3283 try:
3284 A()()
3285 except RuntimeError:
3286 pass
3287 else:
3288 self.fail("Recursion limit should have been reached for __call__()")
3289
3290 def test_delete_hook(self):
3291 # Testing __del__ hook...
3292 log = []
3293 class C(object):
3294 def __del__(self):
3295 log.append(1)
3296 c = C()
3297 self.assertEqual(log, [])
3298 del c
Benjamin Petersone549ead2009-03-28 21:42:05 +00003299 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003300 self.assertEqual(log, [1])
3301
3302 class D(object): pass
3303 d = D()
3304 try: del d[0]
3305 except TypeError: pass
3306 else: self.fail("invalid del() didn't raise TypeError")
3307
3308 def test_hash_inheritance(self):
3309 # Testing hash of mutable subclasses...
3310
3311 class mydict(dict):
3312 pass
3313 d = mydict()
3314 try:
3315 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003316 except TypeError:
3317 pass
3318 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003319 self.fail("hash() of dict subclass should fail")
3320
3321 class mylist(list):
3322 pass
3323 d = mylist()
Guido van Rossum8c842552002-03-14 23:05:54 +00003324 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003325 hash(d)
Guido van Rossum8c842552002-03-14 23:05:54 +00003326 except TypeError:
3327 pass
3328 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003329 self.fail("hash() of list subclass should fail")
3330
3331 def test_str_operations(self):
3332 try: 'a' + 5
3333 except TypeError: pass
3334 else: self.fail("'' + 5 doesn't raise TypeError")
3335
3336 try: ''.split('')
3337 except ValueError: pass
3338 else: self.fail("''.split('') doesn't raise ValueError")
3339
3340 try: ''.join([0])
3341 except TypeError: pass
3342 else: self.fail("''.join([0]) doesn't raise TypeError")
3343
3344 try: ''.rindex('5')
3345 except ValueError: pass
3346 else: self.fail("''.rindex('5') doesn't raise ValueError")
3347
3348 try: '%(n)s' % None
3349 except TypeError: pass
3350 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3351
3352 try: '%(n' % {}
3353 except ValueError: pass
3354 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3355
3356 try: '%*s' % ('abc')
3357 except TypeError: pass
3358 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3359
3360 try: '%*.*s' % ('abc', 5)
3361 except TypeError: pass
3362 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3363
3364 try: '%s' % (1, 2)
3365 except TypeError: pass
3366 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3367
3368 try: '%' % None
3369 except ValueError: pass
3370 else: self.fail("'%' % None doesn't raise ValueError")
3371
3372 self.assertEqual('534253'.isdigit(), 1)
3373 self.assertEqual('534253x'.isdigit(), 0)
3374 self.assertEqual('%c' % 5, '\x05')
3375 self.assertEqual('%c' % '5', '5')
3376
3377 def test_deepcopy_recursive(self):
3378 # Testing deepcopy of recursive objects...
3379 class Node:
Guido van Rossum8c842552002-03-14 23:05:54 +00003380 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003381 a = Node()
3382 b = Node()
3383 a.b = b
3384 b.a = a
3385 z = deepcopy(a) # This blew up before
3386
3387 def test_unintialized_modules(self):
3388 # Testing uninitialized module objects...
3389 from types import ModuleType as M
3390 m = M.__new__(M)
3391 str(m)
3392 self.assertEqual(hasattr(m, "__name__"), 0)
3393 self.assertEqual(hasattr(m, "__file__"), 0)
3394 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003395 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl479a7e72008-02-05 18:13:15 +00003396 m.foo = 1
3397 self.assertEqual(m.__dict__, {"foo": 1})
3398
3399 def test_funny_new(self):
3400 # Testing __new__ returning something unexpected...
3401 class C(object):
3402 def __new__(cls, arg):
3403 if isinstance(arg, str): return [1, 2, 3]
3404 elif isinstance(arg, int): return object.__new__(D)
3405 else: return object.__new__(cls)
3406 class D(C):
3407 def __init__(self, arg):
3408 self.foo = arg
3409 self.assertEqual(C("1"), [1, 2, 3])
3410 self.assertEqual(D("1"), [1, 2, 3])
3411 d = D(None)
3412 self.assertEqual(d.foo, None)
3413 d = C(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003414 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003415 self.assertEqual(d.foo, 1)
3416 d = D(1)
Ezio Melottie9615932010-01-24 19:26:24 +00003417 self.assertIsInstance(d, D)
Georg Brandl479a7e72008-02-05 18:13:15 +00003418 self.assertEqual(d.foo, 1)
3419
3420 def test_imul_bug(self):
3421 # Testing for __imul__ problems...
3422 # SF bug 544647
3423 class C(object):
3424 def __imul__(self, other):
3425 return (self, other)
Guido van Rossum8c842552002-03-14 23:05:54 +00003426 x = C()
Georg Brandl479a7e72008-02-05 18:13:15 +00003427 y = x
3428 y *= 1.0
3429 self.assertEqual(y, (x, 1.0))
3430 y = x
3431 y *= 2
3432 self.assertEqual(y, (x, 2))
3433 y = x
3434 y *= 3
3435 self.assertEqual(y, (x, 3))
3436 y = x
3437 y *= 1<<100
3438 self.assertEqual(y, (x, 1<<100))
3439 y = x
3440 y *= None
3441 self.assertEqual(y, (x, None))
3442 y = x
3443 y *= "foo"
3444 self.assertEqual(y, (x, "foo"))
Guido van Rossum8c842552002-03-14 23:05:54 +00003445
Georg Brandl479a7e72008-02-05 18:13:15 +00003446 def test_copy_setstate(self):
3447 # Testing that copy.*copy() correctly uses __setstate__...
3448 import copy
3449 class C(object):
3450 def __init__(self, foo=None):
3451 self.foo = foo
3452 self.__foo = foo
3453 def setfoo(self, foo=None):
3454 self.foo = foo
3455 def getfoo(self):
3456 return self.__foo
3457 def __getstate__(self):
3458 return [self.foo]
3459 def __setstate__(self_, lst):
3460 self.assertEqual(len(lst), 1)
3461 self_.__foo = self_.foo = lst[0]
3462 a = C(42)
3463 a.setfoo(24)
3464 self.assertEqual(a.foo, 24)
3465 self.assertEqual(a.getfoo(), 42)
3466 b = copy.copy(a)
3467 self.assertEqual(b.foo, 24)
3468 self.assertEqual(b.getfoo(), 24)
3469 b = copy.deepcopy(a)
3470 self.assertEqual(b.foo, 24)
3471 self.assertEqual(b.getfoo(), 24)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003472
Georg Brandl479a7e72008-02-05 18:13:15 +00003473 def test_slices(self):
3474 # Testing cases with slices and overridden __getitem__ ...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003475
Georg Brandl479a7e72008-02-05 18:13:15 +00003476 # Strings
3477 self.assertEqual("hello"[:4], "hell")
3478 self.assertEqual("hello"[slice(4)], "hell")
3479 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3480 class S(str):
3481 def __getitem__(self, x):
3482 return str.__getitem__(self, x)
3483 self.assertEqual(S("hello")[:4], "hell")
3484 self.assertEqual(S("hello")[slice(4)], "hell")
3485 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3486 # Tuples
3487 self.assertEqual((1,2,3)[:2], (1,2))
3488 self.assertEqual((1,2,3)[slice(2)], (1,2))
3489 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3490 class T(tuple):
3491 def __getitem__(self, x):
3492 return tuple.__getitem__(self, x)
3493 self.assertEqual(T((1,2,3))[:2], (1,2))
3494 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3495 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3496 # Lists
3497 self.assertEqual([1,2,3][:2], [1,2])
3498 self.assertEqual([1,2,3][slice(2)], [1,2])
3499 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3500 class L(list):
3501 def __getitem__(self, x):
3502 return list.__getitem__(self, x)
3503 self.assertEqual(L([1,2,3])[:2], [1,2])
3504 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3505 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3506 # Now do lists and __setitem__
3507 a = L([1,2,3])
3508 a[slice(1, 3)] = [3,2]
3509 self.assertEqual(a, [1,3,2])
3510 a[slice(0, 2, 1)] = [3,1]
3511 self.assertEqual(a, [3,1,2])
3512 a.__setitem__(slice(1, 3), [2,1])
3513 self.assertEqual(a, [3,2,1])
3514 a.__setitem__(slice(0, 2, 1), [2,3])
3515 self.assertEqual(a, [2,3,1])
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003516
Georg Brandl479a7e72008-02-05 18:13:15 +00003517 def test_subtype_resurrection(self):
3518 # Testing resurrection of new-style instance...
Guido van Rossum6cef6d52001-09-28 18:13:29 +00003519
Georg Brandl479a7e72008-02-05 18:13:15 +00003520 class C(object):
3521 container = []
Tim Peters2f93e282001-10-04 05:27:00 +00003522
Georg Brandl479a7e72008-02-05 18:13:15 +00003523 def __del__(self):
3524 # resurrect the instance
3525 C.container.append(self)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00003526
Georg Brandl479a7e72008-02-05 18:13:15 +00003527 c = C()
3528 c.attr = 42
Tim Petersfc57ccb2001-10-12 02:38:24 +00003529
Benjamin Petersone549ead2009-03-28 21:42:05 +00003530 # The most interesting thing here is whether this blows up, due to
3531 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3532 # bug).
Georg Brandl479a7e72008-02-05 18:13:15 +00003533 del c
Guido van Rossume7f3e242002-06-14 02:35:45 +00003534
Georg Brandl479a7e72008-02-05 18:13:15 +00003535 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Petersone549ead2009-03-28 21:42:05 +00003536 # the last container slot works: that will attempt to delete c again,
3537 # which will cause c to get appended back to the container again
3538 # "during" the del. (On non-CPython implementations, however, __del__
3539 # is typically not called again.)
3540 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00003541 self.assertEqual(len(C.container), 1)
Benjamin Petersone549ead2009-03-28 21:42:05 +00003542 del C.container[-1]
3543 if support.check_impl_detail():
3544 support.gc_collect()
3545 self.assertEqual(len(C.container), 1)
3546 self.assertEqual(C.container[-1].attr, 42)
Tim Petersfc57ccb2001-10-12 02:38:24 +00003547
Georg Brandl479a7e72008-02-05 18:13:15 +00003548 # Make c mortal again, so that the test framework with -l doesn't report
3549 # it as a leak.
3550 del C.__del__
Tim Petersfc57ccb2001-10-12 02:38:24 +00003551
Georg Brandl479a7e72008-02-05 18:13:15 +00003552 def test_slots_trash(self):
3553 # Testing slot trash...
3554 # Deallocating deeply nested slotted trash caused stack overflows
3555 class trash(object):
3556 __slots__ = ['x']
3557 def __init__(self, x):
3558 self.x = x
3559 o = None
3560 for i in range(50000):
3561 o = trash(o)
3562 del o
Tim Petersfc57ccb2001-10-12 02:38:24 +00003563
Georg Brandl479a7e72008-02-05 18:13:15 +00003564 def test_slots_multiple_inheritance(self):
3565 # SF bug 575229, multiple inheritance w/ slots dumps core
3566 class A(object):
3567 __slots__=()
3568 class B(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003569 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003570 class C(A,B) :
3571 __slots__=()
Benjamin Petersone549ead2009-03-28 21:42:05 +00003572 if support.check_impl_detail():
3573 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00003574 self.assertTrue(hasattr(C, '__dict__'))
3575 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl479a7e72008-02-05 18:13:15 +00003576 C().x = 2
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003577
Georg Brandl479a7e72008-02-05 18:13:15 +00003578 def test_rmul(self):
3579 # Testing correct invocation of __rmul__...
3580 # SF patch 592646
3581 class C(object):
3582 def __mul__(self, other):
3583 return "mul"
3584 def __rmul__(self, other):
3585 return "rmul"
3586 a = C()
3587 self.assertEqual(a*2, "mul")
3588 self.assertEqual(a*2.2, "mul")
3589 self.assertEqual(2*a, "rmul")
3590 self.assertEqual(2.2*a, "rmul")
3591
3592 def test_ipow(self):
3593 # Testing correct invocation of __ipow__...
3594 # [SF bug 620179]
3595 class C(object):
3596 def __ipow__(self, other):
3597 pass
3598 a = C()
3599 a **= 2
3600
3601 def test_mutable_bases(self):
3602 # Testing mutable bases...
3603
3604 # stuff that should work:
3605 class C(object):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003606 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003607 class C2(object):
3608 def __getattribute__(self, attr):
3609 if attr == 'a':
3610 return 2
3611 else:
3612 return super(C2, self).__getattribute__(attr)
3613 def meth(self):
3614 return 1
3615 class D(C):
Walter Dörwalddbd2d252002-03-25 18:36:32 +00003616 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003617 class E(D):
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003618 pass
Georg Brandl479a7e72008-02-05 18:13:15 +00003619 d = D()
3620 e = E()
3621 D.__bases__ = (C,)
3622 D.__bases__ = (C2,)
3623 self.assertEqual(d.meth(), 1)
3624 self.assertEqual(e.meth(), 1)
3625 self.assertEqual(d.a, 2)
3626 self.assertEqual(e.a, 2)
3627 self.assertEqual(C2.__subclasses__(), [D])
Guido van Rossum6e5680f2002-10-15 01:01:53 +00003628
Georg Brandl479a7e72008-02-05 18:13:15 +00003629 try:
3630 del D.__bases__
Benjamin Petersone549ead2009-03-28 21:42:05 +00003631 except (TypeError, AttributeError):
Georg Brandl479a7e72008-02-05 18:13:15 +00003632 pass
3633 else:
3634 self.fail("shouldn't be able to delete .__bases__")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003635
Georg Brandl479a7e72008-02-05 18:13:15 +00003636 try:
3637 D.__bases__ = ()
3638 except TypeError as msg:
3639 if str(msg) == "a new-style class can't have only classic bases":
3640 self.fail("wrong error message for .__bases__ = ()")
3641 else:
3642 self.fail("shouldn't be able to set .__bases__ to ()")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003643
Georg Brandl479a7e72008-02-05 18:13:15 +00003644 try:
3645 D.__bases__ = (D,)
3646 except TypeError:
3647 pass
3648 else:
3649 # actually, we'll have crashed by here...
3650 self.fail("shouldn't be able to create inheritance cycles")
Thomas Wouters89f507f2006-12-13 04:49:30 +00003651
Georg Brandl479a7e72008-02-05 18:13:15 +00003652 try:
3653 D.__bases__ = (C, C)
3654 except TypeError:
3655 pass
3656 else:
3657 self.fail("didn't detect repeated base classes")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003658
Georg Brandl479a7e72008-02-05 18:13:15 +00003659 try:
3660 D.__bases__ = (E,)
3661 except TypeError:
3662 pass
3663 else:
3664 self.fail("shouldn't be able to create inheritance cycles")
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00003665
Benjamin Petersonae937c02009-04-18 20:54:08 +00003666 def test_builtin_bases(self):
3667 # Make sure all the builtin types can have their base queried without
3668 # segfaulting. See issue #5787.
3669 builtin_types = [tp for tp in builtins.__dict__.values()
3670 if isinstance(tp, type)]
3671 for tp in builtin_types:
3672 object.__getattribute__(tp, "__bases__")
3673 if tp is not object:
3674 self.assertEqual(len(tp.__bases__), 1, tp)
3675
Benjamin Peterson25c95f12009-05-08 20:42:26 +00003676 class L(list):
3677 pass
3678
3679 class C(object):
3680 pass
3681
3682 class D(C):
3683 pass
3684
3685 try:
3686 L.__bases__ = (dict,)
3687 except TypeError:
3688 pass
3689 else:
3690 self.fail("shouldn't turn list subclass into dict subclass")
3691
3692 try:
3693 list.__bases__ = (dict,)
3694 except TypeError:
3695 pass
3696 else:
3697 self.fail("shouldn't be able to assign to list.__bases__")
3698
3699 try:
3700 D.__bases__ = (C, list)
3701 except TypeError:
3702 pass
3703 else:
3704 assert 0, "best_base calculation found wanting"
3705
Benjamin Petersonae937c02009-04-18 20:54:08 +00003706
Georg Brandl479a7e72008-02-05 18:13:15 +00003707 def test_mutable_bases_with_failing_mro(self):
3708 # Testing mutable bases with failing mro...
3709 class WorkOnce(type):
3710 def __new__(self, name, bases, ns):
3711 self.flag = 0
3712 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
3713 def mro(self):
3714 if self.flag > 0:
3715 raise RuntimeError("bozo")
3716 else:
3717 self.flag += 1
3718 return type.mro(self)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00003719
Georg Brandl479a7e72008-02-05 18:13:15 +00003720 class WorkAlways(type):
3721 def mro(self):
3722 # this is here to make sure that .mro()s aren't called
3723 # with an exception set (which was possible at one point).
3724 # An error message will be printed in a debug build.
3725 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003726 return type.mro(self)
3727
Georg Brandl479a7e72008-02-05 18:13:15 +00003728 class C(object):
3729 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003730
Georg Brandl479a7e72008-02-05 18:13:15 +00003731 class C2(object):
3732 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003733
Georg Brandl479a7e72008-02-05 18:13:15 +00003734 class D(C):
3735 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003736
Georg Brandl479a7e72008-02-05 18:13:15 +00003737 class E(D):
3738 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003739
Georg Brandl479a7e72008-02-05 18:13:15 +00003740 class F(D, metaclass=WorkOnce):
3741 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003742
Georg Brandl479a7e72008-02-05 18:13:15 +00003743 class G(D, metaclass=WorkAlways):
3744 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003745
Georg Brandl479a7e72008-02-05 18:13:15 +00003746 # Immediate subclasses have their mro's adjusted in alphabetical
3747 # order, so E's will get adjusted before adjusting F's fails. We
3748 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00003749
Georg Brandl479a7e72008-02-05 18:13:15 +00003750 E_mro_before = E.__mro__
3751 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00003752
Armin Rigofd163f92005-12-29 15:59:19 +00003753 try:
Georg Brandl479a7e72008-02-05 18:13:15 +00003754 D.__bases__ = (C2,)
3755 except RuntimeError:
3756 self.assertEqual(E.__mro__, E_mro_before)
3757 self.assertEqual(D.__mro__, D_mro_before)
3758 else:
3759 self.fail("exception not propagated")
3760
3761 def test_mutable_bases_catch_mro_conflict(self):
3762 # Testing mutable bases catch mro conflict...
3763 class A(object):
3764 pass
3765
3766 class B(object):
3767 pass
3768
3769 class C(A, B):
3770 pass
3771
3772 class D(A, B):
3773 pass
3774
3775 class E(C, D):
3776 pass
3777
3778 try:
3779 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00003780 except TypeError:
3781 pass
3782 else:
Georg Brandl479a7e72008-02-05 18:13:15 +00003783 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00003784
Georg Brandl479a7e72008-02-05 18:13:15 +00003785 def test_mutable_names(self):
3786 # Testing mutable names...
3787 class C(object):
3788 pass
3789
3790 # C.__module__ could be 'test_descr' or '__main__'
3791 mod = C.__module__
3792
3793 C.__name__ = 'D'
3794 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
3795
3796 C.__name__ = 'D.E'
3797 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
3798
3799 def test_subclass_right_op(self):
3800 # Testing correct dispatch of subclass overloading __r<op>__...
3801
3802 # This code tests various cases where right-dispatch of a subclass
3803 # should be preferred over left-dispatch of a base class.
3804
3805 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
3806
3807 class B(int):
3808 def __floordiv__(self, other):
3809 return "B.__floordiv__"
3810 def __rfloordiv__(self, other):
3811 return "B.__rfloordiv__"
3812
3813 self.assertEqual(B(1) // 1, "B.__floordiv__")
3814 self.assertEqual(1 // B(1), "B.__rfloordiv__")
3815
3816 # Case 2: subclass of object; this is just the baseline for case 3
3817
3818 class C(object):
3819 def __floordiv__(self, other):
3820 return "C.__floordiv__"
3821 def __rfloordiv__(self, other):
3822 return "C.__rfloordiv__"
3823
3824 self.assertEqual(C() // 1, "C.__floordiv__")
3825 self.assertEqual(1 // C(), "C.__rfloordiv__")
3826
3827 # Case 3: subclass of new-style class; here it gets interesting
3828
3829 class D(C):
3830 def __floordiv__(self, other):
3831 return "D.__floordiv__"
3832 def __rfloordiv__(self, other):
3833 return "D.__rfloordiv__"
3834
3835 self.assertEqual(D() // C(), "D.__floordiv__")
3836 self.assertEqual(C() // D(), "D.__rfloordiv__")
3837
3838 # Case 4: this didn't work right in 2.2.2 and 2.3a1
3839
3840 class E(C):
3841 pass
3842
3843 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
3844
3845 self.assertEqual(E() // 1, "C.__floordiv__")
3846 self.assertEqual(1 // E(), "C.__rfloordiv__")
3847 self.assertEqual(E() // C(), "C.__floordiv__")
3848 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
3849
Benjamin Petersone549ead2009-03-28 21:42:05 +00003850 @support.impl_detail("testing an internal kind of method object")
Georg Brandl479a7e72008-02-05 18:13:15 +00003851 def test_meth_class_get(self):
3852 # Testing __get__ method of METH_CLASS C methods...
3853 # Full coverage of descrobject.c::classmethod_get()
3854
3855 # Baseline
3856 arg = [1, 2, 3]
3857 res = {1: None, 2: None, 3: None}
3858 self.assertEqual(dict.fromkeys(arg), res)
3859 self.assertEqual({}.fromkeys(arg), res)
3860
3861 # Now get the descriptor
3862 descr = dict.__dict__["fromkeys"]
3863
3864 # More baseline using the descriptor directly
3865 self.assertEqual(descr.__get__(None, dict)(arg), res)
3866 self.assertEqual(descr.__get__({})(arg), res)
3867
3868 # Now check various error cases
3869 try:
3870 descr.__get__(None, None)
3871 except TypeError:
3872 pass
3873 else:
3874 self.fail("shouldn't have allowed descr.__get__(None, None)")
3875 try:
3876 descr.__get__(42)
3877 except TypeError:
3878 pass
3879 else:
3880 self.fail("shouldn't have allowed descr.__get__(42)")
3881 try:
3882 descr.__get__(None, 42)
3883 except TypeError:
3884 pass
3885 else:
3886 self.fail("shouldn't have allowed descr.__get__(None, 42)")
3887 try:
3888 descr.__get__(None, int)
3889 except TypeError:
3890 pass
3891 else:
3892 self.fail("shouldn't have allowed descr.__get__(None, int)")
3893
3894 def test_isinst_isclass(self):
3895 # Testing proxy isinstance() and isclass()...
3896 class Proxy(object):
3897 def __init__(self, obj):
3898 self.__obj = obj
3899 def __getattribute__(self, name):
3900 if name.startswith("_Proxy__"):
3901 return object.__getattribute__(self, name)
3902 else:
3903 return getattr(self.__obj, name)
3904 # Test with a classic class
3905 class C:
3906 pass
3907 a = C()
3908 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003909 self.assertIsInstance(a, C) # Baseline
3910 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003911 # Test with a classic subclass
3912 class D(C):
3913 pass
3914 a = D()
3915 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003916 self.assertIsInstance(a, C) # Baseline
3917 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003918 # Test with a new-style class
3919 class C(object):
3920 pass
3921 a = C()
3922 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003923 self.assertIsInstance(a, C) # Baseline
3924 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003925 # Test with a new-style subclass
3926 class D(C):
3927 pass
3928 a = D()
3929 pa = Proxy(a)
Ezio Melottie9615932010-01-24 19:26:24 +00003930 self.assertIsInstance(a, C) # Baseline
3931 self.assertIsInstance(pa, C) # Test
Georg Brandl479a7e72008-02-05 18:13:15 +00003932
3933 def test_proxy_super(self):
3934 # Testing super() for a proxy object...
3935 class Proxy(object):
3936 def __init__(self, obj):
3937 self.__obj = obj
3938 def __getattribute__(self, name):
3939 if name.startswith("_Proxy__"):
3940 return object.__getattribute__(self, name)
3941 else:
3942 return getattr(self.__obj, name)
3943
3944 class B(object):
3945 def f(self):
3946 return "B.f"
3947
3948 class C(B):
3949 def f(self):
3950 return super(C, self).f() + "->C.f"
3951
3952 obj = C()
3953 p = Proxy(obj)
3954 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
3955
3956 def test_carloverre(self):
3957 # Testing prohibition of Carlo Verre's hack...
3958 try:
3959 object.__setattr__(str, "foo", 42)
3960 except TypeError:
3961 pass
3962 else:
Ezio Melotti13925002011-03-16 11:05:33 +02003963 self.fail("Carlo Verre __setattr__ succeeded!")
Georg Brandl479a7e72008-02-05 18:13:15 +00003964 try:
3965 object.__delattr__(str, "lower")
3966 except TypeError:
3967 pass
3968 else:
3969 self.fail("Carlo Verre __delattr__ succeeded!")
3970
3971 def test_weakref_segfault(self):
3972 # Testing weakref segfault...
3973 # SF 742911
3974 import weakref
3975
3976 class Provoker:
3977 def __init__(self, referrent):
3978 self.ref = weakref.ref(referrent)
3979
3980 def __del__(self):
3981 x = self.ref()
3982
3983 class Oops(object):
3984 pass
3985
3986 o = Oops()
3987 o.whatever = Provoker(o)
3988 del o
3989
3990 def test_wrapper_segfault(self):
3991 # SF 927248: deeply nested wrappers could cause stack overflow
3992 f = lambda:None
3993 for i in range(1000000):
3994 f = f.__call__
3995 f = None
3996
3997 def test_file_fault(self):
3998 # Testing sys.stdout is changed in getattr...
Nick Coghlan6ead5522009-10-18 13:19:33 +00003999 test_stdout = sys.stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004000 class StdoutGuard:
4001 def __getattr__(self, attr):
4002 sys.stdout = sys.__stdout__
4003 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4004 sys.stdout = StdoutGuard()
4005 try:
4006 print("Oops!")
4007 except RuntimeError:
4008 pass
Nick Coghlan6ead5522009-10-18 13:19:33 +00004009 finally:
4010 sys.stdout = test_stdout
Georg Brandl479a7e72008-02-05 18:13:15 +00004011
4012 def test_vicious_descriptor_nonsense(self):
4013 # Testing vicious_descriptor_nonsense...
4014
4015 # A potential segfault spotted by Thomas Wouters in mail to
4016 # python-dev 2003-04-17, turned into an example & fixed by Michael
4017 # Hudson just less than four months later...
4018
4019 class Evil(object):
4020 def __hash__(self):
4021 return hash('attr')
4022 def __eq__(self, other):
4023 del C.attr
4024 return 0
4025
4026 class Descr(object):
4027 def __get__(self, ob, type=None):
4028 return 1
4029
4030 class C(object):
4031 attr = Descr()
4032
4033 c = C()
4034 c.__dict__[Evil()] = 0
4035
4036 self.assertEqual(c.attr, 1)
4037 # this makes a crash more likely:
Benjamin Petersone549ead2009-03-28 21:42:05 +00004038 support.gc_collect()
Georg Brandl479a7e72008-02-05 18:13:15 +00004039 self.assertEqual(hasattr(c, 'attr'), False)
4040
4041 def test_init(self):
4042 # SF 1155938
4043 class Foo(object):
4044 def __init__(self):
4045 return 10
4046 try:
4047 Foo()
4048 except TypeError:
4049 pass
4050 else:
4051 self.fail("did not test __init__() for None return")
4052
4053 def test_method_wrapper(self):
4054 # Testing method-wrapper objects...
4055 # <type 'method-wrapper'> did not support any reflection before 2.5
4056
Mark Dickinson211c6252009-02-01 10:28:51 +00004057 # XXX should methods really support __eq__?
Georg Brandl479a7e72008-02-05 18:13:15 +00004058
4059 l = []
4060 self.assertEqual(l.__add__, l.__add__)
4061 self.assertEqual(l.__add__, [].__add__)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004062 self.assertTrue(l.__add__ != [5].__add__)
4063 self.assertTrue(l.__add__ != l.__mul__)
4064 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Petersone549ead2009-03-28 21:42:05 +00004065 if hasattr(l.__add__, '__self__'):
4066 # CPython
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004067 self.assertTrue(l.__add__.__self__ is l)
4068 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Petersone549ead2009-03-28 21:42:05 +00004069 else:
4070 # Python implementations where [].__add__ is a normal bound method
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00004071 self.assertTrue(l.__add__.im_self is l)
4072 self.assertTrue(l.__add__.im_class is list)
Georg Brandl479a7e72008-02-05 18:13:15 +00004073 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4074 try:
4075 hash(l.__add__)
4076 except TypeError:
4077 pass
4078 else:
4079 self.fail("no TypeError from hash([].__add__)")
4080
4081 t = ()
4082 t += (7,)
4083 self.assertEqual(t.__add__, (7,).__add__)
4084 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4085
4086 def test_not_implemented(self):
4087 # Testing NotImplemented...
4088 # all binary methods should be able to return a NotImplemented
Georg Brandl479a7e72008-02-05 18:13:15 +00004089 import operator
4090
4091 def specialmethod(self, other):
4092 return NotImplemented
4093
4094 def check(expr, x, y):
4095 try:
4096 exec(expr, {'x': x, 'y': y, 'operator': operator})
4097 except TypeError:
4098 pass
4099 else:
4100 self.fail("no TypeError from %r" % (expr,))
4101
4102 N1 = sys.maxsize + 1 # might trigger OverflowErrors instead of
4103 # TypeErrors
4104 N2 = sys.maxsize # if sizeof(int) < sizeof(long), might trigger
4105 # ValueErrors instead of TypeErrors
Armin Rigofd163f92005-12-29 15:59:19 +00004106 for name, expr, iexpr in [
4107 ('__add__', 'x + y', 'x += y'),
4108 ('__sub__', 'x - y', 'x -= y'),
4109 ('__mul__', 'x * y', 'x *= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004110 ('__truediv__', 'operator.truediv(x, y)', None),
4111 ('__floordiv__', 'operator.floordiv(x, y)', None),
4112 ('__div__', 'x / y', 'x /= y'),
Armin Rigofd163f92005-12-29 15:59:19 +00004113 ('__mod__', 'x % y', 'x %= y'),
4114 ('__divmod__', 'divmod(x, y)', None),
4115 ('__pow__', 'x ** y', 'x **= y'),
4116 ('__lshift__', 'x << y', 'x <<= y'),
4117 ('__rshift__', 'x >> y', 'x >>= y'),
4118 ('__and__', 'x & y', 'x &= y'),
4119 ('__or__', 'x | y', 'x |= y'),
Georg Brandl479a7e72008-02-05 18:13:15 +00004120 ('__xor__', 'x ^ y', 'x ^= y')]:
Neal Norwitz4886cc32006-08-21 17:06:07 +00004121 rname = '__r' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004122 A = type('A', (), {name: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004123 a = A()
Armin Rigofd163f92005-12-29 15:59:19 +00004124 check(expr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004125 check(expr, a, N1)
4126 check(expr, a, N2)
Armin Rigofd163f92005-12-29 15:59:19 +00004127 if iexpr:
4128 check(iexpr, a, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004129 check(iexpr, a, N1)
4130 check(iexpr, a, N2)
4131 iname = '__i' + name[2:]
Georg Brandl479a7e72008-02-05 18:13:15 +00004132 C = type('C', (), {iname: specialmethod})
Armin Rigofd163f92005-12-29 15:59:19 +00004133 c = C()
4134 check(iexpr, c, a)
Armin Rigofd163f92005-12-29 15:59:19 +00004135 check(iexpr, c, N1)
4136 check(iexpr, c, N2)
4137
Georg Brandl479a7e72008-02-05 18:13:15 +00004138 def test_assign_slice(self):
4139 # ceval.c's assign_slice used to check for
4140 # tp->tp_as_sequence->sq_slice instead of
4141 # tp->tp_as_sequence->sq_ass_slice
Guido van Rossumd8faa362007-04-27 19:54:29 +00004142
Georg Brandl479a7e72008-02-05 18:13:15 +00004143 class C(object):
4144 def __setitem__(self, idx, value):
4145 self.value = value
Guido van Rossumd8faa362007-04-27 19:54:29 +00004146
Georg Brandl479a7e72008-02-05 18:13:15 +00004147 c = C()
4148 c[1:2] = 3
4149 self.assertEqual(c.value, 3)
Guido van Rossumd8faa362007-04-27 19:54:29 +00004150
Benjamin Peterson5e55b3e2010-02-03 02:35:45 +00004151 def test_set_and_no_get(self):
4152 # See
4153 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4154 class Descr(object):
4155
4156 def __init__(self, name):
4157 self.name = name
4158
4159 def __set__(self, obj, value):
4160 obj.__dict__[self.name] = value
4161 descr = Descr("a")
4162
4163 class X(object):
4164 a = descr
4165
4166 x = X()
4167 self.assertIs(x.a, descr)
4168 x.a = 42
4169 self.assertEqual(x.a, 42)
4170
Benjamin Peterson21896a32010-03-21 22:03:03 +00004171 # Also check type_getattro for correctness.
4172 class Meta(type):
4173 pass
4174 class X(object):
4175 __metaclass__ = Meta
4176 X.a = 42
4177 Meta.a = Descr("a")
4178 self.assertEqual(X.a, 42)
4179
Benjamin Peterson9262b842008-11-17 22:45:50 +00004180 def test_getattr_hooks(self):
4181 # issue 4230
4182
4183 class Descriptor(object):
4184 counter = 0
4185 def __get__(self, obj, objtype=None):
4186 def getter(name):
4187 self.counter += 1
4188 raise AttributeError(name)
4189 return getter
4190
4191 descr = Descriptor()
4192 class A(object):
4193 __getattribute__ = descr
4194 class B(object):
4195 __getattr__ = descr
4196 class C(object):
4197 __getattribute__ = descr
4198 __getattr__ = descr
4199
4200 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004201 self.assertEqual(descr.counter, 1)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004202 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004203 self.assertEqual(descr.counter, 2)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004204 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melottib3aedd42010-11-20 19:04:17 +00004205 self.assertEqual(descr.counter, 4)
Benjamin Peterson9262b842008-11-17 22:45:50 +00004206
4207 import gc
4208 class EvilGetattribute(object):
4209 # This used to segfault
4210 def __getattr__(self, name):
4211 raise AttributeError(name)
4212 def __getattribute__(self, name):
4213 del EvilGetattribute.__getattr__
4214 for i in range(5):
4215 gc.collect()
4216 raise AttributeError(name)
4217
4218 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4219
Benjamin Peterson477ba912011-01-12 15:34:01 +00004220 def test_abstractmethods(self):
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004221 # type pretends not to have __abstractmethods__.
4222 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4223 class meta(type):
4224 pass
4225 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
Benjamin Peterson477ba912011-01-12 15:34:01 +00004226 class X(object):
4227 pass
4228 with self.assertRaises(AttributeError):
4229 del X.__abstractmethods__
Benjamin Peterson5e8dada2011-01-12 15:25:02 +00004230
Victor Stinner3249dec2011-05-01 23:19:15 +02004231 def test_proxy_call(self):
4232 class FakeStr:
4233 __class__ = str
4234
4235 fake_str = FakeStr()
4236 # isinstance() reads __class__
4237 self.assertTrue(isinstance(fake_str, str))
4238
4239 # call a method descriptor
4240 with self.assertRaises(TypeError):
4241 str.split(fake_str)
4242
4243 # call a slot wrapper descriptor
4244 with self.assertRaises(TypeError):
4245 str.__add__(fake_str, "abc")
4246
Antoine Pitrou8cdc40e2011-07-15 21:15:07 +02004247 def test_repr_as_str(self):
4248 # Issue #11603: crash or infinite loop when rebinding __str__ as
4249 # __repr__.
4250 class Foo:
4251 pass
4252 Foo.__repr__ = Foo.__str__
4253 foo = Foo()
4254 str(foo)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004255
Benjamin Petersonaf3dcd22011-08-17 11:48:23 -05004256 def test_slot_shadows_class_variable(self):
Benjamin Petersonc4085c82011-08-16 18:53:26 -05004257 with self.assertRaises(ValueError) as cm:
4258 class X:
4259 __slots__ = ["foo"]
4260 foo = None
4261 m = str(cm.exception)
4262 self.assertEqual("'foo' in __slots__ conflicts with class variable", m)
4263
Benjamin Peterson01fc6cd2011-08-17 12:03:47 -05004264 def test_set_doc(self):
4265 class X:
4266 "elephant"
4267 X.__doc__ = "banana"
4268 self.assertEqual(X.__doc__, "banana")
4269 with self.assertRaises(TypeError) as cm:
4270 type(list).__dict__["__doc__"].__set__(list, "blah")
4271 self.assertIn("can't set list.__doc__", str(cm.exception))
4272 with self.assertRaises(TypeError) as cm:
4273 type(X).__dict__["__doc__"].__delete__(X)
4274 self.assertIn("can't delete X.__doc__", str(cm.exception))
4275 self.assertEqual(X.__doc__, "banana")
4276
Georg Brandl479a7e72008-02-05 18:13:15 +00004277class DictProxyTests(unittest.TestCase):
4278 def setUp(self):
4279 class C(object):
4280 def meth(self):
4281 pass
4282 self.C = C
Christian Heimesbbffeb62008-01-24 09:42:52 +00004283
Brett Cannon7a540732011-02-22 03:04:06 +00004284 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4285 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004286 def test_iter_keys(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004287 # Testing dict-proxy keys...
4288 it = self.C.__dict__.keys()
4289 self.assertNotIsInstance(it, list)
4290 keys = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004291 keys.sort()
Ezio Melottib3aedd42010-11-20 19:04:17 +00004292 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl479a7e72008-02-05 18:13:15 +00004293 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004294
Brett Cannon7a540732011-02-22 03:04:06 +00004295 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4296 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004297 def test_iter_values(self):
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004298 # Testing dict-proxy values...
4299 it = self.C.__dict__.values()
4300 self.assertNotIsInstance(it, list)
4301 values = list(it)
Georg Brandl479a7e72008-02-05 18:13:15 +00004302 self.assertEqual(len(values), 5)
Christian Heimesbbffeb62008-01-24 09:42:52 +00004303
Brett Cannon7a540732011-02-22 03:04:06 +00004304 @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
4305 'trace function introduces __local__')
Georg Brandl479a7e72008-02-05 18:13:15 +00004306 def test_iter_items(self):
4307 # Testing dict-proxy iteritems...
Benjamin Peterson0eb7f862010-12-07 03:46:27 +00004308 it = self.C.__dict__.items()
4309 self.assertNotIsInstance(it, list)
4310 keys = [item[0] for item in it]
Georg Brandl479a7e72008-02-05 18:13:15 +00004311 keys.sort()
4312 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4313 '__weakref__', 'meth'])
Christian Heimesbbffeb62008-01-24 09:42:52 +00004314
Georg Brandl479a7e72008-02-05 18:13:15 +00004315 def test_dict_type_with_metaclass(self):
4316 # Testing type of __dict__ when metaclass set...
4317 class B(object):
4318 pass
4319 class M(type):
4320 pass
4321 class C(metaclass=M):
4322 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4323 pass
4324 self.assertEqual(type(C.__dict__), type(B.__dict__))
Christian Heimesbbffeb62008-01-24 09:42:52 +00004325
Ezio Melottiac53ab62010-12-18 14:59:43 +00004326 def test_repr(self):
4327 # Testing dict_proxy.__repr__
4328 dict_ = {k: v for k, v in self.C.__dict__.items()}
4329 self.assertEqual(repr(self.C.__dict__), 'dict_proxy({!r})'.format(dict_))
4330
Christian Heimesbbffeb62008-01-24 09:42:52 +00004331
Georg Brandl479a7e72008-02-05 18:13:15 +00004332class PTypesLongInitTest(unittest.TestCase):
4333 # This is in its own TestCase so that it can be run before any other tests.
4334 def test_pytype_long_ready(self):
4335 # Testing SF bug 551412 ...
Christian Heimesbbffeb62008-01-24 09:42:52 +00004336
Georg Brandl479a7e72008-02-05 18:13:15 +00004337 # This dumps core when SF bug 551412 isn't fixed --
4338 # but only when test_descr.py is run separately.
4339 # (That can't be helped -- as soon as PyType_Ready()
4340 # is called for PyLong_Type, the bug is gone.)
4341 class UserLong(object):
4342 def __pow__(self, *args):
4343 pass
4344 try:
4345 pow(0, UserLong(), 0)
4346 except:
4347 pass
Christian Heimesbbffeb62008-01-24 09:42:52 +00004348
Georg Brandl479a7e72008-02-05 18:13:15 +00004349 # Another segfault only when run early
4350 # (before PyType_Ready(tuple) is called)
4351 type.mro(tuple)
Christian Heimes969fe572008-01-25 11:23:10 +00004352
4353
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004354def test_main():
Georg Brandl479a7e72008-02-05 18:13:15 +00004355 # Run all local test cases, with PTypesLongInitTest first.
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004356 support.run_unittest(PTypesLongInitTest, OperatorsTest,
Georg Brandl479a7e72008-02-05 18:13:15 +00004357 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004358
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004359if __name__ == "__main__":
4360 test_main()