blob: c482cacc2bf08118a390b7f91b079f80284cfc4b [file] [log] [blame]
Benjamin Petersond4d400c2009-04-18 20:12:47 +00001import __builtin__
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00002import sys
Armin Rigo9790a272007-05-02 19:23:31 +00003import types
Georg Brandl48545522008-02-02 10:12:36 +00004import unittest
Tim Peters4d9b4662002-04-16 01:59:17 +00005
Georg Brandl48545522008-02-02 10:12:36 +00006from copy import deepcopy
7from test import test_support
Tim Peters6d6c1a32001-08-02 04:15:00 +00008
Guido van Rossum875eeaa2001-10-11 18:33:53 +00009
Georg Brandl48545522008-02-02 10:12:36 +000010class OperatorsTest(unittest.TestCase):
Tim Peters6d6c1a32001-08-02 04:15:00 +000011
Georg Brandl48545522008-02-02 10:12:36 +000012 def __init__(self, *args, **kwargs):
13 unittest.TestCase.__init__(self, *args, **kwargs)
14 self.binops = {
15 'add': '+',
16 'sub': '-',
17 'mul': '*',
18 'div': '/',
19 'divmod': 'divmod',
20 'pow': '**',
21 'lshift': '<<',
22 'rshift': '>>',
23 'and': '&',
24 'xor': '^',
25 'or': '|',
26 'cmp': 'cmp',
27 'lt': '<',
28 'le': '<=',
29 'eq': '==',
30 'ne': '!=',
31 'gt': '>',
32 'ge': '>=',
33 }
Tim Peters3caca232001-12-06 06:23:26 +000034
Georg Brandl48545522008-02-02 10:12:36 +000035 for name, expr in self.binops.items():
36 if expr.islower():
37 expr = expr + "(a, b)"
38 else:
39 expr = 'a %s b' % expr
40 self.binops[name] = expr
Tim Peters3caca232001-12-06 06:23:26 +000041
Georg Brandl48545522008-02-02 10:12:36 +000042 self.unops = {
43 'pos': '+',
44 'neg': '-',
45 'abs': 'abs',
46 'invert': '~',
47 'int': 'int',
48 'long': 'long',
49 'float': 'float',
50 'oct': 'oct',
51 'hex': 'hex',
52 }
Tim Peters6d6c1a32001-08-02 04:15:00 +000053
Georg Brandl48545522008-02-02 10:12:36 +000054 for name, expr in 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 Brandl48545522008-02-02 10:12:36 +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 Brandl48545522008-02-02 10:12:36 +000067 # Find method in parent class
68 while meth not in t.__dict__:
69 t = t.__bases__[0]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +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 Brandl48545522008-02-02 10:12:36 +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 Brandl48545522008-02-02 10:12:36 +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 Brandl48545522008-02-02 10:12:36 +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 Brandl48545522008-02-02 10:12:36 +000084 if meth == '__divmod__': pass
Tim Peters2f93e282001-10-04 05:27:00 +000085
Georg Brandl48545522008-02-02 10:12:36 +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 Peterson21f6aac2009-03-26 20:17:27 +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 Brandl48545522008-02-02 10:12:36 +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 Brandl48545522008-02-02 10:12:36 +000098 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
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 Peterson21f6aac2009-03-26 20:17:27 +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 Brandl48545522008-02-02 10:12:36 +0000108 self.assertEqual(m(a, b, c), res)
109 bm = getattr(a, meth)
110 self.assertEqual(bm(b, c), res)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000111
Georg Brandl48545522008-02-02 10:12:36 +0000112 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
113 d = {'a': deepcopy(a), 'b': b}
114 exec stmt in 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 Peterson21f6aac2009-03-26 20:17:27 +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 Brandl48545522008-02-02 10:12:36 +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 Brandl48545522008-02-02 10:12:36 +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 in 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 Peterson21f6aac2009-03-26 20:17:27 +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 Brandl48545522008-02-02 10:12:36 +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 set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
151 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
152 exec stmt in 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 Peterson21f6aac2009-03-26 20:17:27 +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 Brandl48545522008-02-02 10:12:36 +0000161 dictionary['a'] = deepcopy(a)
162 m(dictionary['a'], b, c, d)
163 self.assertEqual(dictionary['a'], res)
164 dictionary['a'] = deepcopy(a)
165 bm = getattr(dictionary['a'], meth)
166 bm(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.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
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.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
184 "__setslice__")
185
186 def test_dicts(self):
187 # Testing dict operations...
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000188 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
189 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
190 else:
191 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
Georg Brandl48545522008-02-02 10:12:36 +0000192 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
193 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
194 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
195
196 d = {1:2, 3:4}
197 l1 = []
198 for i in d.keys():
199 l1.append(i)
200 l = []
201 for i in iter(d):
202 l.append(i)
203 self.assertEqual(l, l1)
204 l = []
205 for i in d.__iter__():
206 l.append(i)
207 self.assertEqual(l, l1)
208 l = []
209 for i in dict.__iter__(d):
210 l.append(i)
211 self.assertEqual(l, l1)
212 d = {1:2, 3:4}
213 self.unop_test(d, 2, "len(a)", "__len__")
214 self.assertEqual(eval(repr(d), {}), d)
215 self.assertEqual(eval(d.__repr__(), {}), d)
216 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
217 "__setitem__")
218
219 # Tests for unary and binary operators
220 def number_operators(self, a, b, skip=[]):
221 dict = {'a': a, 'b': b}
222
223 for name, expr in self.binops.items():
224 if name not in skip:
225 name = "__%s__" % name
226 if hasattr(a, name):
227 res = eval(expr, dict)
228 self.binop_test(a, b, res, expr, name)
229
230 for name, expr in self.unops.items():
231 if name not in skip:
232 name = "__%s__" % name
233 if hasattr(a, name):
234 res = eval(expr, dict)
235 self.unop_test(a, res, expr, name)
236
237 def test_ints(self):
238 # Testing int operations...
239 self.number_operators(100, 3)
240 # The following crashes in Python 2.2
241 self.assertEqual((1).__nonzero__(), 1)
242 self.assertEqual((0).__nonzero__(), 0)
243 # This returns 'NotImplemented' in Python 2.2
244 class C(int):
245 def __add__(self, other):
246 return NotImplemented
247 self.assertEqual(C(5L), 5)
Tim Peters25786c02001-09-02 08:22:48 +0000248 try:
Georg Brandl48545522008-02-02 10:12:36 +0000249 C() + ""
Tim Peters25786c02001-09-02 08:22:48 +0000250 except TypeError:
251 pass
252 else:
Georg Brandl48545522008-02-02 10:12:36 +0000253 self.fail("NotImplemented should have caused TypeError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000254 try:
Georg Brandl48545522008-02-02 10:12:36 +0000255 C(sys.maxint+1)
256 except OverflowError:
Tim Peters1fc240e2001-10-26 05:06:50 +0000257 pass
258 else:
Georg Brandl48545522008-02-02 10:12:36 +0000259 self.fail("should have raised OverflowError")
Tim Peters1fc240e2001-10-26 05:06:50 +0000260
Georg Brandl48545522008-02-02 10:12:36 +0000261 def test_longs(self):
262 # Testing long operations...
263 self.number_operators(100L, 3L)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000264
Georg Brandl48545522008-02-02 10:12:36 +0000265 def test_floats(self):
266 # Testing float operations...
267 self.number_operators(100.0, 3.0)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000268
Georg Brandl48545522008-02-02 10:12:36 +0000269 def test_complexes(self):
270 # Testing complex operations...
271 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
272 'int', 'long', 'float'])
Tim Peters5d2b77c2001-09-03 05:47:38 +0000273
Georg Brandl48545522008-02-02 10:12:36 +0000274 class Number(complex):
275 __slots__ = ['prec']
276 def __new__(cls, *args, **kwds):
277 result = complex.__new__(cls, *args)
278 result.prec = kwds.get('prec', 12)
279 return result
280 def __repr__(self):
281 prec = self.prec
282 if self.imag == 0.0:
283 return "%.*g" % (prec, self.real)
284 if self.real == 0.0:
285 return "%.*gj" % (prec, self.imag)
286 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
287 __str__ = __repr__
Tim Peters5d2b77c2001-09-03 05:47:38 +0000288
Georg Brandl48545522008-02-02 10:12:36 +0000289 a = Number(3.14, prec=6)
290 self.assertEqual(repr(a), "3.14")
291 self.assertEqual(a.prec, 6)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000292
Georg Brandl48545522008-02-02 10:12:36 +0000293 a = Number(a, prec=2)
294 self.assertEqual(repr(a), "3.1")
295 self.assertEqual(a.prec, 2)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000296
Georg Brandl48545522008-02-02 10:12:36 +0000297 a = Number(234.5)
298 self.assertEqual(repr(a), "234.5")
299 self.assertEqual(a.prec, 12)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000300
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000301 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000302 def test_spam_lists(self):
303 # Testing spamlist operations...
304 import copy, xxsubtype as spam
Tim Peters37a309d2001-09-04 01:20:04 +0000305
Georg Brandl48545522008-02-02 10:12:36 +0000306 def spamlist(l, memo=None):
307 import xxsubtype as spam
308 return spam.spamlist(l)
Tim Peters37a309d2001-09-04 01:20:04 +0000309
Georg Brandl48545522008-02-02 10:12:36 +0000310 # This is an ugly hack:
311 copy._deepcopy_dispatch[spam.spamlist] = spamlist
Tim Peters37a309d2001-09-04 01:20:04 +0000312
Georg Brandl48545522008-02-02 10:12:36 +0000313 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
314 "__add__")
315 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
316 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
317 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
318 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
319 "__getslice__")
320 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
321 "__iadd__")
322 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
323 "__imul__")
324 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
325 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
326 "__mul__")
327 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
328 "__rmul__")
329 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
330 "__setitem__")
331 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
332 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
333 # Test subclassing
334 class C(spam.spamlist):
335 def foo(self): return 1
336 a = C()
337 self.assertEqual(a, [])
338 self.assertEqual(a.foo(), 1)
339 a.append(100)
340 self.assertEqual(a, [100])
341 self.assertEqual(a.getstate(), 0)
342 a.setstate(42)
343 self.assertEqual(a.getstate(), 42)
Tim Peters37a309d2001-09-04 01:20:04 +0000344
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000345 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +0000346 def test_spam_dicts(self):
347 # Testing spamdict operations...
348 import copy, xxsubtype as spam
349 def spamdict(d, memo=None):
350 import xxsubtype as spam
351 sd = spam.spamdict()
352 for k, v in d.items():
353 sd[k] = v
354 return sd
355 # This is an ugly hack:
356 copy._deepcopy_dispatch[spam.spamdict] = spamdict
Tim Peters37a309d2001-09-04 01:20:04 +0000357
Georg Brandl48545522008-02-02 10:12:36 +0000358 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
359 "__cmp__")
360 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
361 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
362 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
363 d = spamdict({1:2,3:4})
364 l1 = []
365 for i in d.keys():
366 l1.append(i)
367 l = []
368 for i in iter(d):
369 l.append(i)
370 self.assertEqual(l, l1)
371 l = []
372 for i in d.__iter__():
373 l.append(i)
374 self.assertEqual(l, l1)
375 l = []
376 for i in type(spamdict({})).__iter__(d):
377 l.append(i)
378 self.assertEqual(l, l1)
379 straightd = {1:2, 3:4}
380 spamd = spamdict(straightd)
381 self.unop_test(spamd, 2, "len(a)", "__len__")
382 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
383 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
384 "a[b]=c", "__setitem__")
385 # Test subclassing
386 class C(spam.spamdict):
387 def foo(self): return 1
388 a = C()
389 self.assertEqual(a.items(), [])
390 self.assertEqual(a.foo(), 1)
391 a['foo'] = 'bar'
392 self.assertEqual(a.items(), [('foo', 'bar')])
393 self.assertEqual(a.getstate(), 0)
394 a.setstate(100)
395 self.assertEqual(a.getstate(), 100)
Tim Peters37a309d2001-09-04 01:20:04 +0000396
Georg Brandl48545522008-02-02 10:12:36 +0000397class ClassPropertiesAndMethods(unittest.TestCase):
Tim Peters37a309d2001-09-04 01:20:04 +0000398
Georg Brandl48545522008-02-02 10:12:36 +0000399 def test_python_dicts(self):
400 # Testing Python subclass of dict...
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000401 self.assertTrue(issubclass(dict, dict))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000402 self.assertIsInstance({}, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000403 d = dict()
404 self.assertEqual(d, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000405 self.assertTrue(d.__class__ is dict)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000406 self.assertIsInstance(d, dict)
Georg Brandl48545522008-02-02 10:12:36 +0000407 class C(dict):
408 state = -1
409 def __init__(self_local, *a, **kw):
410 if a:
411 self.assertEqual(len(a), 1)
412 self_local.state = a[0]
413 if kw:
414 for k, v in kw.items():
415 self_local[v] = k
416 def __getitem__(self, key):
417 return self.get(key, 0)
418 def __setitem__(self_local, key, value):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000419 self.assertIsInstance(key, type(0))
Georg Brandl48545522008-02-02 10:12:36 +0000420 dict.__setitem__(self_local, key, value)
421 def setstate(self, state):
422 self.state = state
423 def getstate(self):
424 return self.state
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000425 self.assertTrue(issubclass(C, dict))
Georg Brandl48545522008-02-02 10:12:36 +0000426 a1 = C(12)
427 self.assertEqual(a1.state, 12)
428 a2 = C(foo=1, bar=2)
429 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
430 a = C()
431 self.assertEqual(a.state, -1)
432 self.assertEqual(a.getstate(), -1)
433 a.setstate(0)
434 self.assertEqual(a.state, 0)
435 self.assertEqual(a.getstate(), 0)
436 a.setstate(10)
437 self.assertEqual(a.state, 10)
438 self.assertEqual(a.getstate(), 10)
439 self.assertEqual(a[42], 0)
440 a[42] = 24
441 self.assertEqual(a[42], 24)
442 N = 50
443 for i in range(N):
444 a[i] = C()
445 for j in range(N):
446 a[i][j] = i*j
447 for i in range(N):
448 for j in range(N):
449 self.assertEqual(a[i][j], i*j)
Tim Peters5d2b77c2001-09-03 05:47:38 +0000450
Georg Brandl48545522008-02-02 10:12:36 +0000451 def test_python_lists(self):
452 # Testing Python subclass of list...
453 class C(list):
454 def __getitem__(self, i):
455 return list.__getitem__(self, i) + 100
456 def __getslice__(self, i, j):
457 return (i, j)
458 a = C()
459 a.extend([0,1,2])
460 self.assertEqual(a[0], 100)
461 self.assertEqual(a[1], 101)
462 self.assertEqual(a[2], 102)
463 self.assertEqual(a[100:200], (100,200))
Tim Peterscaaff8d2001-09-10 23:12:14 +0000464
Georg Brandl48545522008-02-02 10:12:36 +0000465 def test_metaclass(self):
466 # Testing __metaclass__...
467 class C:
Guido van Rossume54616c2001-12-14 04:19:56 +0000468 __metaclass__ = type
Georg Brandl48545522008-02-02 10:12:36 +0000469 def __init__(self):
470 self.__state = 0
471 def getstate(self):
472 return self.__state
473 def setstate(self, state):
474 self.__state = state
475 a = C()
476 self.assertEqual(a.getstate(), 0)
477 a.setstate(10)
478 self.assertEqual(a.getstate(), 10)
479 class D:
480 class __metaclass__(type):
481 def myself(cls): return cls
482 self.assertEqual(D.myself(), D)
483 d = D()
484 self.assertEqual(d.__class__, D)
485 class M1(type):
486 def __new__(cls, name, bases, dict):
487 dict['__spam__'] = 1
488 return type.__new__(cls, name, bases, dict)
489 class C:
490 __metaclass__ = M1
491 self.assertEqual(C.__spam__, 1)
492 c = C()
493 self.assertEqual(c.__spam__, 1)
Guido van Rossume54616c2001-12-14 04:19:56 +0000494
Georg Brandl48545522008-02-02 10:12:36 +0000495 class _instance(object):
496 pass
497 class M2(object):
498 @staticmethod
499 def __new__(cls, name, bases, dict):
500 self = object.__new__(cls)
501 self.name = name
502 self.bases = bases
503 self.dict = dict
504 return self
505 def __call__(self):
506 it = _instance()
507 # Early binding of methods
508 for key in self.dict:
509 if key.startswith("__"):
510 continue
511 setattr(it, key, self.dict[key].__get__(it, self))
512 return it
513 class C:
514 __metaclass__ = M2
515 def spam(self):
516 return 42
517 self.assertEqual(C.name, 'C')
518 self.assertEqual(C.bases, ())
Ezio Melottiaa980582010-01-23 23:04:36 +0000519 self.assertIn('spam', C.dict)
Georg Brandl48545522008-02-02 10:12:36 +0000520 c = C()
521 self.assertEqual(c.spam(), 42)
Guido van Rossum9a818922002-11-14 19:50:14 +0000522
Georg Brandl48545522008-02-02 10:12:36 +0000523 # More metaclass examples
Guido van Rossum9a818922002-11-14 19:50:14 +0000524
Georg Brandl48545522008-02-02 10:12:36 +0000525 class autosuper(type):
526 # Automatically add __super to the class
527 # This trick only works for dynamic classes
528 def __new__(metaclass, name, bases, dict):
529 cls = super(autosuper, metaclass).__new__(metaclass,
530 name, bases, dict)
531 # Name mangling for __super removes leading underscores
532 while name[:1] == "_":
533 name = name[1:]
534 if name:
535 name = "_%s__super" % name
536 else:
537 name = "__super"
538 setattr(cls, name, super(cls))
539 return cls
540 class A:
541 __metaclass__ = autosuper
542 def meth(self):
543 return "A"
544 class B(A):
545 def meth(self):
546 return "B" + self.__super.meth()
547 class C(A):
548 def meth(self):
549 return "C" + self.__super.meth()
550 class D(C, B):
551 def meth(self):
552 return "D" + self.__super.meth()
553 self.assertEqual(D().meth(), "DCBA")
554 class E(B, C):
555 def meth(self):
556 return "E" + self.__super.meth()
557 self.assertEqual(E().meth(), "EBCA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000558
Georg Brandl48545522008-02-02 10:12:36 +0000559 class autoproperty(type):
560 # Automatically create property attributes when methods
561 # named _get_x and/or _set_x are found
562 def __new__(metaclass, name, bases, dict):
563 hits = {}
564 for key, val in dict.iteritems():
565 if key.startswith("_get_"):
566 key = key[5:]
567 get, set = hits.get(key, (None, None))
568 get = val
569 hits[key] = get, set
570 elif key.startswith("_set_"):
571 key = key[5:]
572 get, set = hits.get(key, (None, None))
573 set = val
574 hits[key] = get, set
575 for key, (get, set) in hits.iteritems():
576 dict[key] = property(get, set)
577 return super(autoproperty, metaclass).__new__(metaclass,
578 name, bases, dict)
579 class A:
580 __metaclass__ = autoproperty
581 def _get_x(self):
582 return -self.__x
583 def _set_x(self, x):
584 self.__x = -x
585 a = A()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000586 self.assertTrue(not hasattr(a, "x"))
Georg Brandl48545522008-02-02 10:12:36 +0000587 a.x = 12
588 self.assertEqual(a.x, 12)
589 self.assertEqual(a._A__x, -12)
Guido van Rossum9a818922002-11-14 19:50:14 +0000590
Georg Brandl48545522008-02-02 10:12:36 +0000591 class multimetaclass(autoproperty, autosuper):
592 # Merge of multiple cooperating metaclasses
593 pass
594 class A:
595 __metaclass__ = multimetaclass
596 def _get_x(self):
597 return "A"
598 class B(A):
599 def _get_x(self):
600 return "B" + self.__super._get_x()
601 class C(A):
602 def _get_x(self):
603 return "C" + self.__super._get_x()
604 class D(C, B):
605 def _get_x(self):
606 return "D" + self.__super._get_x()
607 self.assertEqual(D().x, "DCBA")
Guido van Rossum9a818922002-11-14 19:50:14 +0000608
Georg Brandl48545522008-02-02 10:12:36 +0000609 # Make sure type(x) doesn't call x.__class__.__init__
610 class T(type):
611 counter = 0
612 def __init__(self, *args):
613 T.counter += 1
614 class C:
615 __metaclass__ = T
616 self.assertEqual(T.counter, 1)
617 a = C()
618 self.assertEqual(type(a), C)
619 self.assertEqual(T.counter, 1)
Guido van Rossum9a818922002-11-14 19:50:14 +0000620
Georg Brandl48545522008-02-02 10:12:36 +0000621 class C(object): pass
622 c = C()
623 try: c()
624 except TypeError: pass
625 else: self.fail("calling object w/o call method should raise "
626 "TypeError")
Guido van Rossum9a818922002-11-14 19:50:14 +0000627
Georg Brandl48545522008-02-02 10:12:36 +0000628 # Testing code to find most derived baseclass
629 class A(type):
630 def __new__(*args, **kwargs):
631 return type.__new__(*args, **kwargs)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000632
Georg Brandl48545522008-02-02 10:12:36 +0000633 class B(object):
634 pass
635
636 class C(object):
637 __metaclass__ = A
638
639 # The most derived metaclass of D is A rather than type.
640 class D(B, C):
641 pass
642
643 def test_module_subclasses(self):
644 # Testing Python subclass of module...
645 log = []
Georg Brandl48545522008-02-02 10:12:36 +0000646 MT = type(sys)
647 class MM(MT):
648 def __init__(self, name):
649 MT.__init__(self, name)
650 def __getattribute__(self, name):
651 log.append(("getattr", name))
652 return MT.__getattribute__(self, name)
653 def __setattr__(self, name, value):
654 log.append(("setattr", name, value))
655 MT.__setattr__(self, name, value)
656 def __delattr__(self, name):
657 log.append(("delattr", name))
658 MT.__delattr__(self, name)
659 a = MM("a")
660 a.foo = 12
661 x = a.foo
662 del a.foo
663 self.assertEqual(log, [("setattr", "foo", 12),
664 ("getattr", "foo"),
665 ("delattr", "foo")])
666
667 # http://python.org/sf/1174712
668 try:
669 class Module(types.ModuleType, str):
670 pass
671 except TypeError:
672 pass
673 else:
674 self.fail("inheriting from ModuleType and str at the same time "
675 "should fail")
676
677 def test_multiple_inheritence(self):
678 # Testing multiple inheritance...
679 class C(object):
680 def __init__(self):
681 self.__state = 0
682 def getstate(self):
683 return self.__state
684 def setstate(self, state):
685 self.__state = state
686 a = C()
687 self.assertEqual(a.getstate(), 0)
688 a.setstate(10)
689 self.assertEqual(a.getstate(), 10)
690 class D(dict, C):
691 def __init__(self):
692 type({}).__init__(self)
693 C.__init__(self)
694 d = D()
695 self.assertEqual(d.keys(), [])
696 d["hello"] = "world"
697 self.assertEqual(d.items(), [("hello", "world")])
698 self.assertEqual(d["hello"], "world")
699 self.assertEqual(d.getstate(), 0)
700 d.setstate(10)
701 self.assertEqual(d.getstate(), 10)
702 self.assertEqual(D.__mro__, (D, dict, C, object))
703
704 # SF bug #442833
705 class Node(object):
706 def __int__(self):
707 return int(self.foo())
708 def foo(self):
709 return "23"
710 class Frag(Node, list):
711 def foo(self):
712 return "42"
713 self.assertEqual(Node().__int__(), 23)
714 self.assertEqual(int(Node()), 23)
715 self.assertEqual(Frag().__int__(), 42)
716 self.assertEqual(int(Frag()), 42)
717
718 # MI mixing classic and new-style classes.
719
720 class A:
721 x = 1
722
723 class B(A):
724 pass
725
726 class C(A):
727 x = 2
728
729 class D(B, C):
730 pass
731 self.assertEqual(D.x, 1)
732
733 # Classic MRO is preserved for a classic base class.
734 class E(D, object):
735 pass
736 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
737 self.assertEqual(E.x, 1)
738
739 # But with a mix of classic bases, their MROs are combined using
740 # new-style MRO.
741 class F(B, C, object):
742 pass
743 self.assertEqual(F.__mro__, (F, B, C, A, object))
744 self.assertEqual(F.x, 2)
745
746 # Try something else.
747 class C:
748 def cmethod(self):
749 return "C a"
750 def all_method(self):
751 return "C b"
752
753 class M1(C, object):
754 def m1method(self):
755 return "M1 a"
756 def all_method(self):
757 return "M1 b"
758
759 self.assertEqual(M1.__mro__, (M1, C, object))
760 m = M1()
761 self.assertEqual(m.cmethod(), "C a")
762 self.assertEqual(m.m1method(), "M1 a")
763 self.assertEqual(m.all_method(), "M1 b")
764
765 class D(C):
766 def dmethod(self):
767 return "D a"
768 def all_method(self):
769 return "D b"
770
771 class M2(D, object):
772 def m2method(self):
773 return "M2 a"
774 def all_method(self):
775 return "M2 b"
776
777 self.assertEqual(M2.__mro__, (M2, D, C, object))
778 m = M2()
779 self.assertEqual(m.cmethod(), "C a")
780 self.assertEqual(m.dmethod(), "D a")
781 self.assertEqual(m.m2method(), "M2 a")
782 self.assertEqual(m.all_method(), "M2 b")
783
784 class M3(M1, M2, object):
785 def m3method(self):
786 return "M3 a"
787 def all_method(self):
788 return "M3 b"
789 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
790 m = M3()
791 self.assertEqual(m.cmethod(), "C a")
792 self.assertEqual(m.dmethod(), "D a")
793 self.assertEqual(m.m1method(), "M1 a")
794 self.assertEqual(m.m2method(), "M2 a")
795 self.assertEqual(m.m3method(), "M3 a")
796 self.assertEqual(m.all_method(), "M3 b")
797
798 class Classic:
799 pass
800 try:
801 class New(Classic):
802 __metaclass__ = type
803 except TypeError:
804 pass
805 else:
806 self.fail("new class with only classic bases - shouldn't be")
807
808 def test_diamond_inheritence(self):
809 # Testing multiple inheritance special cases...
810 class A(object):
811 def spam(self): return "A"
812 self.assertEqual(A().spam(), "A")
813 class B(A):
814 def boo(self): return "B"
815 def spam(self): return "B"
816 self.assertEqual(B().spam(), "B")
817 self.assertEqual(B().boo(), "B")
818 class C(A):
819 def boo(self): return "C"
820 self.assertEqual(C().spam(), "A")
821 self.assertEqual(C().boo(), "C")
822 class D(B, C): pass
823 self.assertEqual(D().spam(), "B")
824 self.assertEqual(D().boo(), "B")
825 self.assertEqual(D.__mro__, (D, B, C, A, object))
826 class E(C, B): pass
827 self.assertEqual(E().spam(), "B")
828 self.assertEqual(E().boo(), "C")
829 self.assertEqual(E.__mro__, (E, C, B, A, object))
830 # MRO order disagreement
831 try:
832 class F(D, E): pass
833 except TypeError:
834 pass
835 else:
836 self.fail("expected MRO order disagreement (F)")
837 try:
838 class G(E, D): pass
839 except TypeError:
840 pass
841 else:
842 self.fail("expected MRO order disagreement (G)")
843
844 # see thread python-dev/2002-October/029035.html
845 def test_ex5_from_c3_switch(self):
846 # Testing ex5 from C3 switch discussion...
847 class A(object): pass
848 class B(object): pass
849 class C(object): pass
850 class X(A): pass
851 class Y(A): pass
852 class Z(X,B,Y,C): pass
853 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
854
855 # see "A Monotonic Superclass Linearization for Dylan",
856 # by Kim Barrett et al. (OOPSLA 1996)
857 def test_monotonicity(self):
858 # Testing MRO monotonicity...
859 class Boat(object): pass
860 class DayBoat(Boat): pass
861 class WheelBoat(Boat): pass
862 class EngineLess(DayBoat): pass
863 class SmallMultihull(DayBoat): pass
864 class PedalWheelBoat(EngineLess,WheelBoat): pass
865 class SmallCatamaran(SmallMultihull): pass
866 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
867
868 self.assertEqual(PedalWheelBoat.__mro__,
869 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
870 self.assertEqual(SmallCatamaran.__mro__,
871 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
872 self.assertEqual(Pedalo.__mro__,
873 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
874 SmallMultihull, DayBoat, WheelBoat, Boat, object))
875
876 # see "A Monotonic Superclass Linearization for Dylan",
877 # by Kim Barrett et al. (OOPSLA 1996)
878 def test_consistency_with_epg(self):
879 # Testing consistentcy with EPG...
880 class Pane(object): pass
881 class ScrollingMixin(object): pass
882 class EditingMixin(object): pass
883 class ScrollablePane(Pane,ScrollingMixin): pass
884 class EditablePane(Pane,EditingMixin): pass
885 class EditableScrollablePane(ScrollablePane,EditablePane): pass
886
887 self.assertEqual(EditableScrollablePane.__mro__,
888 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
889 ScrollingMixin, EditingMixin, object))
890
891 def test_mro_disagreement(self):
892 # Testing error messages for MRO disagreement...
893 mro_err_msg = """Cannot create a consistent method resolution
Raymond Hettingerf394df42003-04-06 19:13:41 +0000894order (MRO) for bases """
Raymond Hettinger83245b52003-03-12 04:25:42 +0000895
Georg Brandl48545522008-02-02 10:12:36 +0000896 def raises(exc, expected, callable, *args):
897 try:
898 callable(*args)
899 except exc, msg:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +0000900 # the exact msg is generally considered an impl detail
901 if test_support.check_impl_detail():
902 if not str(msg).startswith(expected):
903 self.fail("Message %r, expected %r" %
904 (str(msg), expected))
Georg Brandl48545522008-02-02 10:12:36 +0000905 else:
906 self.fail("Expected %s" % exc)
907
908 class A(object): pass
909 class B(A): pass
910 class C(object): pass
911
912 # Test some very simple errors
913 raises(TypeError, "duplicate base class A",
914 type, "X", (A, A), {})
915 raises(TypeError, mro_err_msg,
916 type, "X", (A, B), {})
917 raises(TypeError, mro_err_msg,
918 type, "X", (A, C, B), {})
919 # Test a slightly more complex error
920 class GridLayout(object): pass
921 class HorizontalGrid(GridLayout): pass
922 class VerticalGrid(GridLayout): pass
923 class HVGrid(HorizontalGrid, VerticalGrid): pass
924 class VHGrid(VerticalGrid, HorizontalGrid): pass
925 raises(TypeError, mro_err_msg,
926 type, "ConfusedGrid", (HVGrid, VHGrid), {})
927
928 def test_object_class(self):
929 # Testing object class...
930 a = object()
931 self.assertEqual(a.__class__, object)
932 self.assertEqual(type(a), object)
933 b = object()
934 self.assertNotEqual(a, b)
935 self.assertFalse(hasattr(a, "foo"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000936 try:
Georg Brandl48545522008-02-02 10:12:36 +0000937 a.foo = 12
938 except (AttributeError, TypeError):
939 pass
Guido van Rossumd32047f2002-11-25 21:38:52 +0000940 else:
Georg Brandl48545522008-02-02 10:12:36 +0000941 self.fail("object() should not allow setting a foo attribute")
942 self.assertFalse(hasattr(object(), "__dict__"))
Guido van Rossumd32047f2002-11-25 21:38:52 +0000943
Georg Brandl48545522008-02-02 10:12:36 +0000944 class Cdict(object):
945 pass
946 x = Cdict()
947 self.assertEqual(x.__dict__, {})
948 x.foo = 1
949 self.assertEqual(x.foo, 1)
950 self.assertEqual(x.__dict__, {'foo': 1})
Guido van Rossum37202612001-08-09 19:45:21 +0000951
Georg Brandl48545522008-02-02 10:12:36 +0000952 def test_slots(self):
953 # Testing __slots__...
954 class C0(object):
955 __slots__ = []
956 x = C0()
957 self.assertFalse(hasattr(x, "__dict__"))
958 self.assertFalse(hasattr(x, "foo"))
Guido van Rossum37202612001-08-09 19:45:21 +0000959
Georg Brandl48545522008-02-02 10:12:36 +0000960 class C1(object):
961 __slots__ = ['a']
962 x = C1()
963 self.assertFalse(hasattr(x, "__dict__"))
964 self.assertFalse(hasattr(x, "a"))
965 x.a = 1
966 self.assertEqual(x.a, 1)
967 x.a = None
968 self.assertEqual(x.a, None)
969 del x.a
970 self.assertFalse(hasattr(x, "a"))
Tim Peters6d6c1a32001-08-02 04:15:00 +0000971
Georg Brandl48545522008-02-02 10:12:36 +0000972 class C3(object):
973 __slots__ = ['a', 'b', 'c']
974 x = C3()
975 self.assertFalse(hasattr(x, "__dict__"))
976 self.assertFalse(hasattr(x, 'a'))
977 self.assertFalse(hasattr(x, 'b'))
978 self.assertFalse(hasattr(x, 'c'))
979 x.a = 1
980 x.b = 2
981 x.c = 3
982 self.assertEqual(x.a, 1)
983 self.assertEqual(x.b, 2)
984 self.assertEqual(x.c, 3)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000985
Georg Brandl48545522008-02-02 10:12:36 +0000986 class C4(object):
987 """Validate name mangling"""
988 __slots__ = ['__a']
989 def __init__(self, value):
990 self.__a = value
991 def get(self):
992 return self.__a
993 x = C4(5)
994 self.assertFalse(hasattr(x, '__dict__'))
995 self.assertFalse(hasattr(x, '__a'))
996 self.assertEqual(x.get(), 5)
997 try:
998 x.__a = 6
999 except AttributeError:
1000 pass
1001 else:
1002 self.fail("Double underscored names not mangled")
Tim Peters6d6c1a32001-08-02 04:15:00 +00001003
Georg Brandl48545522008-02-02 10:12:36 +00001004 # Make sure slot names are proper identifiers
Žiga Seilnacht71436f02007-03-14 12:24:09 +00001005 try:
1006 class C(object):
Georg Brandl48545522008-02-02 10:12:36 +00001007 __slots__ = [None]
Guido van Rossum843daa82001-09-18 20:04:26 +00001008 except TypeError:
1009 pass
1010 else:
Georg Brandl48545522008-02-02 10:12:36 +00001011 self.fail("[None] slots not caught")
Tim Peters66c1a522001-09-24 21:17:50 +00001012 try:
Georg Brandl48545522008-02-02 10:12:36 +00001013 class C(object):
1014 __slots__ = ["foo bar"]
1015 except TypeError:
Georg Brandl533ff6f2006-03-08 18:09:27 +00001016 pass
Georg Brandl48545522008-02-02 10:12:36 +00001017 else:
1018 self.fail("['foo bar'] slots not caught")
1019 try:
1020 class C(object):
1021 __slots__ = ["foo\0bar"]
1022 except TypeError:
1023 pass
1024 else:
1025 self.fail("['foo\\0bar'] slots not caught")
1026 try:
1027 class C(object):
1028 __slots__ = ["1"]
1029 except TypeError:
1030 pass
1031 else:
1032 self.fail("['1'] slots not caught")
1033 try:
1034 class C(object):
1035 __slots__ = [""]
1036 except TypeError:
1037 pass
1038 else:
1039 self.fail("[''] slots not caught")
1040 class C(object):
1041 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1042 # XXX(nnorwitz): was there supposed to be something tested
1043 # from the class above?
Georg Brandl533ff6f2006-03-08 18:09:27 +00001044
Georg Brandl48545522008-02-02 10:12:36 +00001045 # Test a single string is not expanded as a sequence.
1046 class C(object):
1047 __slots__ = "abc"
1048 c = C()
1049 c.abc = 5
1050 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001051
Georg Brandl48545522008-02-02 10:12:36 +00001052 # Test unicode slot names
1053 try:
1054 unicode
1055 except NameError:
1056 pass
1057 else:
1058 # Test a single unicode string is not expanded as a sequence.
1059 class C(object):
1060 __slots__ = unicode("abc")
1061 c = C()
1062 c.abc = 5
1063 self.assertEqual(c.abc, 5)
Georg Brandle9462c72006-08-04 18:03:37 +00001064
Georg Brandl48545522008-02-02 10:12:36 +00001065 # _unicode_to_string used to modify slots in certain circumstances
1066 slots = (unicode("foo"), unicode("bar"))
1067 class C(object):
1068 __slots__ = slots
1069 x = C()
1070 x.foo = 5
1071 self.assertEqual(x.foo, 5)
1072 self.assertEqual(type(slots[0]), unicode)
1073 # this used to leak references
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001074 try:
Georg Brandl48545522008-02-02 10:12:36 +00001075 class C(object):
1076 __slots__ = [unichr(128)]
1077 except (TypeError, UnicodeEncodeError):
Guido van Rossumd1ef7892007-11-10 22:12:24 +00001078 pass
Tim Peters8fa45672001-09-13 21:01:29 +00001079 else:
Georg Brandl48545522008-02-02 10:12:36 +00001080 self.fail("[unichr(128)] slots not caught")
Tim Peters8fa45672001-09-13 21:01:29 +00001081
Georg Brandl48545522008-02-02 10:12:36 +00001082 # Test leaks
1083 class Counted(object):
1084 counter = 0 # counts the number of instances alive
1085 def __init__(self):
1086 Counted.counter += 1
1087 def __del__(self):
1088 Counted.counter -= 1
1089 class C(object):
1090 __slots__ = ['a', 'b', 'c']
Guido van Rossum8c842552002-03-14 23:05:54 +00001091 x = C()
Georg Brandl48545522008-02-02 10:12:36 +00001092 x.a = Counted()
1093 x.b = Counted()
1094 x.c = Counted()
1095 self.assertEqual(Counted.counter, 3)
1096 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001097 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001098 self.assertEqual(Counted.counter, 0)
1099 class D(C):
1100 pass
Guido van Rossum8c842552002-03-14 23:05:54 +00001101 x = D()
Georg Brandl48545522008-02-02 10:12:36 +00001102 x.a = Counted()
1103 x.z = Counted()
1104 self.assertEqual(Counted.counter, 2)
1105 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001106 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001107 self.assertEqual(Counted.counter, 0)
1108 class E(D):
1109 __slots__ = ['e']
Guido van Rossum3f50cdc2003-02-10 21:31:27 +00001110 x = E()
Georg Brandl48545522008-02-02 10:12:36 +00001111 x.a = Counted()
1112 x.z = Counted()
1113 x.e = Counted()
1114 self.assertEqual(Counted.counter, 3)
1115 del x
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001116 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001117 self.assertEqual(Counted.counter, 0)
Guido van Rossum8c842552002-03-14 23:05:54 +00001118
Georg Brandl48545522008-02-02 10:12:36 +00001119 # Test cyclical leaks [SF bug 519621]
1120 class F(object):
1121 __slots__ = ['a', 'b']
Georg Brandl48545522008-02-02 10:12:36 +00001122 s = F()
1123 s.a = [Counted(), s]
1124 self.assertEqual(Counted.counter, 1)
1125 s = None
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001126 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001127 self.assertEqual(Counted.counter, 0)
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001128
Georg Brandl48545522008-02-02 10:12:36 +00001129 # Test lookup leaks [SF bug 572567]
Georg Brandla4f46e12010-02-07 17:03:15 +00001130 import gc
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001131 if hasattr(gc, 'get_objects'):
1132 class G(object):
1133 def __cmp__(self, other):
1134 return 0
1135 __hash__ = None # Silence Py3k warning
1136 g = G()
1137 orig_objects = len(gc.get_objects())
1138 for i in xrange(10):
1139 g==g
1140 new_objects = len(gc.get_objects())
1141 self.assertEqual(orig_objects, new_objects)
1142
Georg Brandl48545522008-02-02 10:12:36 +00001143 class H(object):
1144 __slots__ = ['a', 'b']
1145 def __init__(self):
1146 self.a = 1
1147 self.b = 2
1148 def __del__(self_):
1149 self.assertEqual(self_.a, 1)
1150 self.assertEqual(self_.b, 2)
Armin Rigo581eb1e2008-10-28 17:01:21 +00001151 with test_support.captured_output('stderr') as s:
1152 h = H()
Georg Brandl48545522008-02-02 10:12:36 +00001153 del h
Armin Rigo581eb1e2008-10-28 17:01:21 +00001154 self.assertEqual(s.getvalue(), '')
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001155
Benjamin Peterson0f02d392009-12-30 19:34:10 +00001156 class X(object):
1157 __slots__ = "a"
1158 with self.assertRaises(AttributeError):
1159 del X().a
1160
Georg Brandl48545522008-02-02 10:12:36 +00001161 def test_slots_special(self):
1162 # Testing __dict__ and __weakref__ in __slots__...
1163 class D(object):
1164 __slots__ = ["__dict__"]
1165 a = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001166 self.assertTrue(hasattr(a, "__dict__"))
Georg Brandl48545522008-02-02 10:12:36 +00001167 self.assertFalse(hasattr(a, "__weakref__"))
1168 a.foo = 42
1169 self.assertEqual(a.__dict__, {"foo": 42})
Guido van Rossum6cef6d52001-09-28 18:13:29 +00001170
Georg Brandl48545522008-02-02 10:12:36 +00001171 class W(object):
1172 __slots__ = ["__weakref__"]
1173 a = W()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001174 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001175 self.assertFalse(hasattr(a, "__dict__"))
1176 try:
1177 a.foo = 42
1178 except AttributeError:
1179 pass
1180 else:
1181 self.fail("shouldn't be allowed to set a.foo")
1182
1183 class C1(W, D):
1184 __slots__ = []
1185 a = C1()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001186 self.assertTrue(hasattr(a, "__dict__"))
1187 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001188 a.foo = 42
1189 self.assertEqual(a.__dict__, {"foo": 42})
1190
1191 class C2(D, W):
1192 __slots__ = []
1193 a = C2()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001194 self.assertTrue(hasattr(a, "__dict__"))
1195 self.assertTrue(hasattr(a, "__weakref__"))
Georg Brandl48545522008-02-02 10:12:36 +00001196 a.foo = 42
1197 self.assertEqual(a.__dict__, {"foo": 42})
1198
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001199 def test_slots_descriptor(self):
1200 # Issue2115: slot descriptors did not correctly check
1201 # the type of the given object
1202 import abc
1203 class MyABC:
1204 __metaclass__ = abc.ABCMeta
1205 __slots__ = "a"
1206
1207 class Unrelated(object):
1208 pass
1209 MyABC.register(Unrelated)
1210
1211 u = Unrelated()
Ezio Melottib0f5adc2010-01-24 16:58:36 +00001212 self.assertIsInstance(u, MyABC)
Amaury Forgeot d'Arc60d6c7f2008-02-15 21:22:45 +00001213
1214 # This used to crash
1215 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1216
Benjamin Peterson4895af42009-12-13 16:36:53 +00001217 def test_metaclass_cmp(self):
1218 # See bug 7491.
1219 class M(type):
1220 def __cmp__(self, other):
1221 return -1
1222 class X(object):
1223 __metaclass__ = M
1224 self.assertTrue(X < M)
1225
Georg Brandl48545522008-02-02 10:12:36 +00001226 def test_dynamics(self):
1227 # Testing class attribute propagation...
1228 class D(object):
1229 pass
1230 class E(D):
1231 pass
1232 class F(D):
1233 pass
1234 D.foo = 1
1235 self.assertEqual(D.foo, 1)
1236 # Test that dynamic attributes are inherited
1237 self.assertEqual(E.foo, 1)
1238 self.assertEqual(F.foo, 1)
1239 # Test dynamic instances
1240 class C(object):
1241 pass
1242 a = C()
1243 self.assertFalse(hasattr(a, "foobar"))
1244 C.foobar = 2
1245 self.assertEqual(a.foobar, 2)
1246 C.method = lambda self: 42
1247 self.assertEqual(a.method(), 42)
1248 C.__repr__ = lambda self: "C()"
1249 self.assertEqual(repr(a), "C()")
1250 C.__int__ = lambda self: 100
1251 self.assertEqual(int(a), 100)
1252 self.assertEqual(a.foobar, 2)
1253 self.assertFalse(hasattr(a, "spam"))
1254 def mygetattr(self, name):
1255 if name == "spam":
1256 return "spam"
1257 raise AttributeError
1258 C.__getattr__ = mygetattr
1259 self.assertEqual(a.spam, "spam")
1260 a.new = 12
1261 self.assertEqual(a.new, 12)
1262 def mysetattr(self, name, value):
1263 if name == "spam":
1264 raise AttributeError
1265 return object.__setattr__(self, name, value)
1266 C.__setattr__ = mysetattr
1267 try:
1268 a.spam = "not spam"
1269 except AttributeError:
1270 pass
1271 else:
1272 self.fail("expected AttributeError")
1273 self.assertEqual(a.spam, "spam")
1274 class D(C):
1275 pass
1276 d = D()
1277 d.foo = 1
1278 self.assertEqual(d.foo, 1)
1279
1280 # Test handling of int*seq and seq*int
1281 class I(int):
1282 pass
1283 self.assertEqual("a"*I(2), "aa")
1284 self.assertEqual(I(2)*"a", "aa")
1285 self.assertEqual(2*I(3), 6)
1286 self.assertEqual(I(3)*2, 6)
1287 self.assertEqual(I(3)*I(2), 6)
1288
1289 # Test handling of long*seq and seq*long
1290 class L(long):
1291 pass
1292 self.assertEqual("a"*L(2L), "aa")
1293 self.assertEqual(L(2L)*"a", "aa")
1294 self.assertEqual(2*L(3), 6)
1295 self.assertEqual(L(3)*2, 6)
1296 self.assertEqual(L(3)*L(2), 6)
1297
1298 # Test comparison of classes with dynamic metaclasses
1299 class dynamicmetaclass(type):
1300 pass
1301 class someclass:
1302 __metaclass__ = dynamicmetaclass
1303 self.assertNotEqual(someclass, object)
1304
1305 def test_errors(self):
1306 # Testing errors...
1307 try:
1308 class C(list, dict):
1309 pass
1310 except TypeError:
1311 pass
1312 else:
1313 self.fail("inheritance from both list and dict should be illegal")
1314
1315 try:
1316 class C(object, None):
1317 pass
1318 except TypeError:
1319 pass
1320 else:
1321 self.fail("inheritance from non-type should be illegal")
1322 class Classic:
1323 pass
1324
1325 try:
1326 class C(type(len)):
1327 pass
1328 except TypeError:
1329 pass
1330 else:
1331 self.fail("inheritance from CFunction should be illegal")
1332
1333 try:
1334 class C(object):
1335 __slots__ = 1
1336 except TypeError:
1337 pass
1338 else:
1339 self.fail("__slots__ = 1 should be illegal")
1340
1341 try:
1342 class C(object):
1343 __slots__ = [1]
1344 except TypeError:
1345 pass
1346 else:
1347 self.fail("__slots__ = [1] should be illegal")
1348
1349 class M1(type):
1350 pass
1351 class M2(type):
1352 pass
1353 class A1(object):
1354 __metaclass__ = M1
1355 class A2(object):
1356 __metaclass__ = M2
1357 try:
1358 class B(A1, A2):
1359 pass
1360 except TypeError:
1361 pass
1362 else:
1363 self.fail("finding the most derived metaclass should have failed")
1364
1365 def test_classmethods(self):
1366 # Testing class methods...
1367 class C(object):
1368 def foo(*a): return a
1369 goo = classmethod(foo)
1370 c = C()
1371 self.assertEqual(C.goo(1), (C, 1))
1372 self.assertEqual(c.goo(1), (C, 1))
1373 self.assertEqual(c.foo(1), (c, 1))
1374 class D(C):
1375 pass
1376 d = D()
1377 self.assertEqual(D.goo(1), (D, 1))
1378 self.assertEqual(d.goo(1), (D, 1))
1379 self.assertEqual(d.foo(1), (d, 1))
1380 self.assertEqual(D.foo(d, 1), (d, 1))
1381 # Test for a specific crash (SF bug 528132)
1382 def f(cls, arg): return (cls, arg)
1383 ff = classmethod(f)
1384 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1385 self.assertEqual(ff.__get__(0)(42), (int, 42))
1386
1387 # Test super() with classmethods (SF bug 535444)
1388 self.assertEqual(C.goo.im_self, C)
1389 self.assertEqual(D.goo.im_self, D)
1390 self.assertEqual(super(D,D).goo.im_self, D)
1391 self.assertEqual(super(D,d).goo.im_self, D)
1392 self.assertEqual(super(D,D).goo(), (D,))
1393 self.assertEqual(super(D,d).goo(), (D,))
1394
Benjamin Peterson6fcf9b52009-09-01 22:27:57 +00001395 # Verify that a non-callable will raise
1396 meth = classmethod(1).__get__(1)
1397 self.assertRaises(TypeError, meth)
Georg Brandl48545522008-02-02 10:12:36 +00001398
1399 # Verify that classmethod() doesn't allow keyword args
1400 try:
1401 classmethod(f, kw=1)
1402 except TypeError:
1403 pass
1404 else:
1405 self.fail("classmethod shouldn't accept keyword args")
1406
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001407 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001408 def test_classmethods_in_c(self):
1409 # Testing C-based class methods...
1410 import xxsubtype as spam
1411 a = (1, 2, 3)
1412 d = {'abc': 123}
1413 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1414 self.assertEqual(x, spam.spamlist)
1415 self.assertEqual(a, a1)
1416 self.assertEqual(d, d1)
1417 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1418 self.assertEqual(x, spam.spamlist)
1419 self.assertEqual(a, a1)
1420 self.assertEqual(d, d1)
1421
1422 def test_staticmethods(self):
1423 # Testing static methods...
1424 class C(object):
1425 def foo(*a): return a
1426 goo = staticmethod(foo)
1427 c = C()
1428 self.assertEqual(C.goo(1), (1,))
1429 self.assertEqual(c.goo(1), (1,))
1430 self.assertEqual(c.foo(1), (c, 1,))
1431 class D(C):
1432 pass
1433 d = D()
1434 self.assertEqual(D.goo(1), (1,))
1435 self.assertEqual(d.goo(1), (1,))
1436 self.assertEqual(d.foo(1), (d, 1))
1437 self.assertEqual(D.foo(d, 1), (d, 1))
1438
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001439 @test_support.impl_detail("the module 'xxsubtype' is internal")
Georg Brandl48545522008-02-02 10:12:36 +00001440 def test_staticmethods_in_c(self):
1441 # Testing C-based static methods...
1442 import xxsubtype as spam
1443 a = (1, 2, 3)
1444 d = {"abc": 123}
1445 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1446 self.assertEqual(x, None)
1447 self.assertEqual(a, a1)
1448 self.assertEqual(d, d1)
1449 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1450 self.assertEqual(x, None)
1451 self.assertEqual(a, a1)
1452 self.assertEqual(d, d1)
1453
1454 def test_classic(self):
1455 # Testing classic classes...
1456 class C:
1457 def foo(*a): return a
1458 goo = classmethod(foo)
1459 c = C()
1460 self.assertEqual(C.goo(1), (C, 1))
1461 self.assertEqual(c.goo(1), (C, 1))
1462 self.assertEqual(c.foo(1), (c, 1))
1463 class D(C):
1464 pass
1465 d = D()
1466 self.assertEqual(D.goo(1), (D, 1))
1467 self.assertEqual(d.goo(1), (D, 1))
1468 self.assertEqual(d.foo(1), (d, 1))
1469 self.assertEqual(D.foo(d, 1), (d, 1))
1470 class E: # *not* subclassing from C
1471 foo = C.foo
1472 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001473 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001474
1475 def test_compattr(self):
1476 # Testing computed attributes...
1477 class C(object):
1478 class computed_attribute(object):
1479 def __init__(self, get, set=None, delete=None):
1480 self.__get = get
1481 self.__set = set
1482 self.__delete = delete
1483 def __get__(self, obj, type=None):
1484 return self.__get(obj)
1485 def __set__(self, obj, value):
1486 return self.__set(obj, value)
1487 def __delete__(self, obj):
1488 return self.__delete(obj)
1489 def __init__(self):
1490 self.__x = 0
1491 def __get_x(self):
1492 x = self.__x
1493 self.__x = x+1
1494 return x
1495 def __set_x(self, x):
1496 self.__x = x
1497 def __delete_x(self):
1498 del self.__x
1499 x = computed_attribute(__get_x, __set_x, __delete_x)
1500 a = C()
1501 self.assertEqual(a.x, 0)
1502 self.assertEqual(a.x, 1)
1503 a.x = 10
1504 self.assertEqual(a.x, 10)
1505 self.assertEqual(a.x, 11)
1506 del a.x
1507 self.assertEqual(hasattr(a, 'x'), 0)
1508
1509 def test_newslots(self):
1510 # Testing __new__ slot override...
1511 class C(list):
1512 def __new__(cls):
1513 self = list.__new__(cls)
1514 self.foo = 1
1515 return self
1516 def __init__(self):
1517 self.foo = self.foo + 2
1518 a = C()
1519 self.assertEqual(a.foo, 3)
1520 self.assertEqual(a.__class__, C)
1521 class D(C):
1522 pass
1523 b = D()
1524 self.assertEqual(b.foo, 3)
1525 self.assertEqual(b.__class__, D)
1526
1527 def test_altmro(self):
1528 # Testing mro() and overriding it...
1529 class A(object):
1530 def f(self): return "A"
1531 class B(A):
1532 pass
1533 class C(A):
1534 def f(self): return "C"
1535 class D(B, C):
1536 pass
1537 self.assertEqual(D.mro(), [D, B, C, A, object])
1538 self.assertEqual(D.__mro__, (D, B, C, A, object))
1539 self.assertEqual(D().f(), "C")
1540
1541 class PerverseMetaType(type):
1542 def mro(cls):
1543 L = type.mro(cls)
1544 L.reverse()
1545 return L
1546 class X(D,B,C,A):
1547 __metaclass__ = PerverseMetaType
1548 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1549 self.assertEqual(X().f(), "A")
1550
1551 try:
1552 class X(object):
1553 class __metaclass__(type):
1554 def mro(self):
1555 return [self, dict, object]
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001556 # In CPython, the class creation above already raises
1557 # TypeError, as a protection against the fact that
1558 # instances of X would segfault it. In other Python
1559 # implementations it would be ok to let the class X
1560 # be created, but instead get a clean TypeError on the
1561 # __setitem__ below.
1562 x = object.__new__(X)
1563 x[5] = 6
Georg Brandl48545522008-02-02 10:12:36 +00001564 except TypeError:
1565 pass
1566 else:
1567 self.fail("devious mro() return not caught")
1568
1569 try:
1570 class X(object):
1571 class __metaclass__(type):
1572 def mro(self):
1573 return [1]
1574 except TypeError:
1575 pass
1576 else:
1577 self.fail("non-class mro() return not caught")
1578
1579 try:
1580 class X(object):
1581 class __metaclass__(type):
1582 def mro(self):
1583 return 1
1584 except TypeError:
1585 pass
1586 else:
1587 self.fail("non-sequence mro() return not caught")
1588
1589 def test_overloading(self):
1590 # Testing operator overloading...
1591
1592 class B(object):
1593 "Intermediate class because object doesn't have a __setattr__"
1594
1595 class C(B):
1596 def __getattr__(self, name):
1597 if name == "foo":
1598 return ("getattr", name)
1599 else:
1600 raise AttributeError
1601 def __setattr__(self, name, value):
1602 if name == "foo":
1603 self.setattr = (name, value)
1604 else:
1605 return B.__setattr__(self, name, value)
1606 def __delattr__(self, name):
1607 if name == "foo":
1608 self.delattr = name
1609 else:
1610 return B.__delattr__(self, name)
1611
1612 def __getitem__(self, key):
1613 return ("getitem", key)
1614 def __setitem__(self, key, value):
1615 self.setitem = (key, value)
1616 def __delitem__(self, key):
1617 self.delitem = key
1618
1619 def __getslice__(self, i, j):
1620 return ("getslice", i, j)
1621 def __setslice__(self, i, j, value):
1622 self.setslice = (i, j, value)
1623 def __delslice__(self, i, j):
1624 self.delslice = (i, j)
1625
1626 a = C()
1627 self.assertEqual(a.foo, ("getattr", "foo"))
1628 a.foo = 12
1629 self.assertEqual(a.setattr, ("foo", 12))
1630 del a.foo
1631 self.assertEqual(a.delattr, "foo")
1632
1633 self.assertEqual(a[12], ("getitem", 12))
1634 a[12] = 21
1635 self.assertEqual(a.setitem, (12, 21))
1636 del a[12]
1637 self.assertEqual(a.delitem, 12)
1638
1639 self.assertEqual(a[0:10], ("getslice", 0, 10))
1640 a[0:10] = "foo"
1641 self.assertEqual(a.setslice, (0, 10, "foo"))
1642 del a[0:10]
1643 self.assertEqual(a.delslice, (0, 10))
1644
1645 def test_methods(self):
1646 # Testing methods...
1647 class C(object):
1648 def __init__(self, x):
1649 self.x = x
1650 def foo(self):
1651 return self.x
1652 c1 = C(1)
1653 self.assertEqual(c1.foo(), 1)
1654 class D(C):
1655 boo = C.foo
1656 goo = c1.foo
1657 d2 = D(2)
1658 self.assertEqual(d2.foo(), 2)
1659 self.assertEqual(d2.boo(), 2)
1660 self.assertEqual(d2.goo(), 1)
1661 class E(object):
1662 foo = C.foo
1663 self.assertEqual(E().foo, C.foo) # i.e., unbound
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001664 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
Georg Brandl48545522008-02-02 10:12:36 +00001665
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001666 def test_special_method_lookup(self):
1667 # The lookup of special methods bypasses __getattr__ and
1668 # __getattribute__, but they still can be descriptors.
1669
1670 def run_context(manager):
1671 with manager:
1672 pass
1673 def iden(self):
1674 return self
1675 def hello(self):
1676 return "hello"
Benjamin Peterson809e2252009-05-09 02:07:04 +00001677 def empty_seq(self):
1678 return []
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001679 def zero(self):
1680 return 0
Benjamin Petersonecdae192010-01-04 00:43:01 +00001681 def complex_num(self):
1682 return 1j
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001683 def stop(self):
1684 raise StopIteration
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001685 def return_true(self, thing=None):
1686 return True
1687 def do_isinstance(obj):
1688 return isinstance(int, obj)
1689 def do_issubclass(obj):
1690 return issubclass(int, obj)
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001691 def swallow(*args):
1692 pass
1693 def do_dict_missing(checker):
1694 class DictSub(checker.__class__, dict):
1695 pass
1696 self.assertEqual(DictSub()["hi"], 4)
1697 def some_number(self_, key):
1698 self.assertEqual(key, "hi")
1699 return 4
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001700 def format_impl(self, spec):
1701 return "hello"
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001702
1703 # It would be nice to have every special method tested here, but I'm
1704 # only listing the ones I can remember outside of typeobject.c, since it
1705 # does it right.
1706 specials = [
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001707 ("__unicode__", unicode, hello, set(), {}),
1708 ("__reversed__", reversed, empty_seq, set(), {}),
1709 ("__length_hint__", list, zero, set(),
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001710 {"__iter__" : iden, "next" : stop}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001711 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1712 ("__instancecheck__", do_isinstance, return_true, set(), {}),
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001713 ("__missing__", do_dict_missing, some_number,
1714 set(("__class__",)), {}),
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001715 ("__subclasscheck__", do_issubclass, return_true,
1716 set(("__bases__",)), {}),
Benjamin Peterson1880d8b2009-05-25 13:13:44 +00001717 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1718 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
Benjamin Petersonecdae192010-01-04 00:43:01 +00001719 ("__complex__", complex, complex_num, set(), {}),
Benjamin Peterson2aa6c382010-06-05 00:32:50 +00001720 ("__format__", format, format_impl, set(), {}),
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001721 ]
1722
1723 class Checker(object):
1724 def __getattr__(self, attr, test=self):
1725 test.fail("__getattr__ called with {0}".format(attr))
1726 def __getattribute__(self, attr, test=self):
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001727 if attr not in ok:
1728 test.fail("__getattribute__ called with {0}".format(attr))
Benjamin Peterson39d43b42009-05-27 02:43:46 +00001729 return object.__getattribute__(self, attr)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001730 class SpecialDescr(object):
1731 def __init__(self, impl):
1732 self.impl = impl
1733 def __get__(self, obj, owner):
1734 record.append(1)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001735 return self.impl.__get__(obj, owner)
Benjamin Peterson87e50062009-05-25 02:40:21 +00001736 class MyException(Exception):
1737 pass
1738 class ErrDescr(object):
1739 def __get__(self, obj, owner):
1740 raise MyException
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001741
Benjamin Petersonfb6fb062009-05-16 21:44:25 +00001742 for name, runner, meth_impl, ok, env in specials:
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001743 class X(Checker):
1744 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001745 for attr, obj in env.iteritems():
1746 setattr(X, attr, obj)
Benjamin Petersondb7ebcf2009-05-08 17:59:29 +00001747 setattr(X, name, meth_impl)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001748 runner(X())
1749
1750 record = []
1751 class X(Checker):
1752 pass
Benjamin Petersonaf1692a2009-05-09 16:36:39 +00001753 for attr, obj in env.iteritems():
1754 setattr(X, attr, obj)
Benjamin Peterson399e4c42009-05-08 03:06:00 +00001755 setattr(X, name, SpecialDescr(meth_impl))
1756 runner(X())
1757 self.assertEqual(record, [1], name)
1758
Benjamin Peterson87e50062009-05-25 02:40:21 +00001759 class X(Checker):
1760 pass
1761 for attr, obj in env.iteritems():
1762 setattr(X, attr, obj)
1763 setattr(X, name, ErrDescr())
1764 try:
1765 runner(X())
1766 except MyException:
1767 pass
1768 else:
1769 self.fail("{0!r} didn't raise".format(name))
1770
Georg Brandl48545522008-02-02 10:12:36 +00001771 def test_specials(self):
1772 # Testing special operators...
1773 # Test operators like __hash__ for which a built-in default exists
1774
1775 # Test the default behavior for static classes
1776 class C(object):
1777 def __getitem__(self, i):
1778 if 0 <= i < 10: return i
1779 raise IndexError
1780 c1 = C()
1781 c2 = C()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001782 self.assertTrue(not not c1) # What?
Georg Brandl48545522008-02-02 10:12:36 +00001783 self.assertNotEqual(id(c1), id(c2))
1784 hash(c1)
1785 hash(c2)
1786 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1787 self.assertEqual(c1, c1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001788 self.assertTrue(c1 != c2)
1789 self.assertTrue(not c1 != c1)
1790 self.assertTrue(not c1 == c2)
Georg Brandl48545522008-02-02 10:12:36 +00001791 # Note that the module name appears in str/repr, and that varies
1792 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001793 self.assertTrue(str(c1).find('C object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001794 self.assertEqual(str(c1), repr(c1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001795 self.assertNotIn(-1, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001796 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001797 self.assertIn(i, c1)
1798 self.assertNotIn(10, c1)
Georg Brandl48545522008-02-02 10:12:36 +00001799 # Test the default behavior for dynamic classes
1800 class D(object):
1801 def __getitem__(self, i):
1802 if 0 <= i < 10: return i
1803 raise IndexError
1804 d1 = D()
1805 d2 = D()
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001806 self.assertTrue(not not d1)
Georg Brandl48545522008-02-02 10:12:36 +00001807 self.assertNotEqual(id(d1), id(d2))
1808 hash(d1)
1809 hash(d2)
1810 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1811 self.assertEqual(d1, d1)
1812 self.assertNotEqual(d1, d2)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001813 self.assertTrue(not d1 != d1)
1814 self.assertTrue(not d1 == d2)
Georg Brandl48545522008-02-02 10:12:36 +00001815 # Note that the module name appears in str/repr, and that varies
1816 # depending on whether this test is run standalone or from a framework.
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001817 self.assertTrue(str(d1).find('D object at ') >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001818 self.assertEqual(str(d1), repr(d1))
Ezio Melottiaa980582010-01-23 23:04:36 +00001819 self.assertNotIn(-1, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001820 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001821 self.assertIn(i, d1)
1822 self.assertNotIn(10, d1)
Georg Brandl48545522008-02-02 10:12:36 +00001823 # Test overridden behavior for static classes
1824 class Proxy(object):
1825 def __init__(self, x):
1826 self.x = x
1827 def __nonzero__(self):
1828 return not not self.x
1829 def __hash__(self):
1830 return hash(self.x)
1831 def __eq__(self, other):
1832 return self.x == other
1833 def __ne__(self, other):
1834 return self.x != other
1835 def __cmp__(self, other):
1836 return cmp(self.x, other.x)
1837 def __str__(self):
1838 return "Proxy:%s" % self.x
1839 def __repr__(self):
1840 return "Proxy(%r)" % self.x
1841 def __contains__(self, value):
1842 return value in self.x
1843 p0 = Proxy(0)
1844 p1 = Proxy(1)
1845 p_1 = Proxy(-1)
1846 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001847 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001848 self.assertEqual(hash(p0), hash(0))
1849 self.assertEqual(p0, p0)
1850 self.assertNotEqual(p0, p1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001851 self.assertTrue(not p0 != p0)
Georg Brandl48545522008-02-02 10:12:36 +00001852 self.assertEqual(not p0, p1)
1853 self.assertEqual(cmp(p0, p1), -1)
1854 self.assertEqual(cmp(p0, p0), 0)
1855 self.assertEqual(cmp(p0, p_1), 1)
1856 self.assertEqual(str(p0), "Proxy:0")
1857 self.assertEqual(repr(p0), "Proxy(0)")
1858 p10 = Proxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001859 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001860 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001861 self.assertIn(i, p10)
1862 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001863 # Test overridden behavior for dynamic classes
1864 class DProxy(object):
1865 def __init__(self, x):
1866 self.x = x
1867 def __nonzero__(self):
1868 return not not self.x
1869 def __hash__(self):
1870 return hash(self.x)
1871 def __eq__(self, other):
1872 return self.x == other
1873 def __ne__(self, other):
1874 return self.x != other
1875 def __cmp__(self, other):
1876 return cmp(self.x, other.x)
1877 def __str__(self):
1878 return "DProxy:%s" % self.x
1879 def __repr__(self):
1880 return "DProxy(%r)" % self.x
1881 def __contains__(self, value):
1882 return value in self.x
1883 p0 = DProxy(0)
1884 p1 = DProxy(1)
1885 p_1 = DProxy(-1)
1886 self.assertFalse(p0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001887 self.assertTrue(not not p1)
Georg Brandl48545522008-02-02 10:12:36 +00001888 self.assertEqual(hash(p0), hash(0))
1889 self.assertEqual(p0, p0)
1890 self.assertNotEqual(p0, p1)
1891 self.assertNotEqual(not p0, p0)
1892 self.assertEqual(not p0, p1)
1893 self.assertEqual(cmp(p0, p1), -1)
1894 self.assertEqual(cmp(p0, p0), 0)
1895 self.assertEqual(cmp(p0, p_1), 1)
1896 self.assertEqual(str(p0), "DProxy:0")
1897 self.assertEqual(repr(p0), "DProxy(0)")
1898 p10 = DProxy(range(10))
Ezio Melottiaa980582010-01-23 23:04:36 +00001899 self.assertNotIn(-1, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001900 for i in range(10):
Ezio Melottiaa980582010-01-23 23:04:36 +00001901 self.assertIn(i, p10)
1902 self.assertNotIn(10, p10)
Georg Brandl48545522008-02-02 10:12:36 +00001903
1904 # Safety test for __cmp__
1905 def unsafecmp(a, b):
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001906 if not hasattr(a, '__cmp__'):
1907 return # some types don't have a __cmp__ any more (so the
1908 # test doesn't make sense any more), or maybe they
1909 # never had a __cmp__ at all, e.g. in PyPy
Georg Brandl48545522008-02-02 10:12:36 +00001910 try:
1911 a.__class__.__cmp__(a, b)
1912 except TypeError:
1913 pass
Guido van Rossum4bb1e362001-09-28 23:49:48 +00001914 else:
Georg Brandl48545522008-02-02 10:12:36 +00001915 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1916 a.__class__, a, b))
1917
1918 unsafecmp(u"123", "123")
1919 unsafecmp("123", u"123")
1920 unsafecmp(1, 1.0)
1921 unsafecmp(1.0, 1)
1922 unsafecmp(1, 1L)
1923 unsafecmp(1L, 1)
1924
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001925 @test_support.impl_detail("custom logic for printing to real file objects")
1926 def test_recursions_1(self):
Georg Brandl48545522008-02-02 10:12:36 +00001927 # Testing recursion checks ...
1928 class Letter(str):
1929 def __new__(cls, letter):
1930 if letter == 'EPS':
1931 return str.__new__(cls)
1932 return str.__new__(cls, letter)
1933 def __str__(self):
1934 if not self:
1935 return 'EPS'
1936 return self
1937 # sys.stdout needs to be the original to trigger the recursion bug
Georg Brandl48545522008-02-02 10:12:36 +00001938 test_stdout = sys.stdout
1939 sys.stdout = test_support.get_original_stdout()
1940 try:
1941 # nothing should actually be printed, this should raise an exception
1942 print Letter('w')
1943 except RuntimeError:
1944 pass
1945 else:
1946 self.fail("expected a RuntimeError for print recursion")
1947 finally:
1948 sys.stdout = test_stdout
1949
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001950 def test_recursions_2(self):
Georg Brandl48545522008-02-02 10:12:36 +00001951 # Bug #1202533.
1952 class A(object):
1953 pass
1954 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
1955 try:
1956 A()*2
1957 except RuntimeError:
1958 pass
1959 else:
1960 self.fail("expected a RuntimeError")
1961
1962 def test_weakrefs(self):
1963 # Testing weak references...
1964 import weakref
1965 class C(object):
1966 pass
1967 c = C()
1968 r = weakref.ref(c)
1969 self.assertEqual(r(), c)
1970 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001971 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001972 self.assertEqual(r(), None)
1973 del r
1974 class NoWeak(object):
1975 __slots__ = ['foo']
1976 no = NoWeak()
1977 try:
1978 weakref.ref(no)
1979 except TypeError, msg:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00001980 self.assertTrue(str(msg).find("weak reference") >= 0)
Georg Brandl48545522008-02-02 10:12:36 +00001981 else:
1982 self.fail("weakref.ref(no) should be illegal")
1983 class Weak(object):
1984 __slots__ = ['foo', '__weakref__']
1985 yes = Weak()
1986 r = weakref.ref(yes)
1987 self.assertEqual(r(), yes)
1988 del yes
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00001989 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00001990 self.assertEqual(r(), None)
1991 del r
1992
1993 def test_properties(self):
1994 # Testing property...
1995 class C(object):
1996 def getx(self):
1997 return self.__x
1998 def setx(self, value):
1999 self.__x = value
2000 def delx(self):
2001 del self.__x
2002 x = property(getx, setx, delx, doc="I'm the x property.")
2003 a = C()
2004 self.assertFalse(hasattr(a, "x"))
2005 a.x = 42
2006 self.assertEqual(a._C__x, 42)
2007 self.assertEqual(a.x, 42)
2008 del a.x
2009 self.assertFalse(hasattr(a, "x"))
2010 self.assertFalse(hasattr(a, "_C__x"))
2011 C.x.__set__(a, 100)
2012 self.assertEqual(C.x.__get__(a), 100)
2013 C.x.__delete__(a)
2014 self.assertFalse(hasattr(a, "x"))
2015
2016 raw = C.__dict__['x']
Ezio Melottib0f5adc2010-01-24 16:58:36 +00002017 self.assertIsInstance(raw, property)
Georg Brandl48545522008-02-02 10:12:36 +00002018
2019 attrs = dir(raw)
Ezio Melottiaa980582010-01-23 23:04:36 +00002020 self.assertIn("__doc__", attrs)
2021 self.assertIn("fget", attrs)
2022 self.assertIn("fset", attrs)
2023 self.assertIn("fdel", attrs)
Georg Brandl48545522008-02-02 10:12:36 +00002024
2025 self.assertEqual(raw.__doc__, "I'm the x property.")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002026 self.assertTrue(raw.fget is C.__dict__['getx'])
2027 self.assertTrue(raw.fset is C.__dict__['setx'])
2028 self.assertTrue(raw.fdel is C.__dict__['delx'])
Georg Brandl48545522008-02-02 10:12:36 +00002029
2030 for attr in "__doc__", "fget", "fset", "fdel":
2031 try:
2032 setattr(raw, attr, 42)
2033 except TypeError, msg:
2034 if str(msg).find('readonly') < 0:
2035 self.fail("when setting readonly attr %r on a property, "
2036 "got unexpected TypeError msg %r" % (attr, str(msg)))
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002037 else:
Georg Brandl48545522008-02-02 10:12:36 +00002038 self.fail("expected TypeError from trying to set readonly %r "
2039 "attr on a property" % attr)
Tim Peters2f93e282001-10-04 05:27:00 +00002040
Georg Brandl48545522008-02-02 10:12:36 +00002041 class D(object):
2042 __getitem__ = property(lambda s: 1/0)
Guido van Rossum4bb1e362001-09-28 23:49:48 +00002043
Georg Brandl48545522008-02-02 10:12:36 +00002044 d = D()
2045 try:
2046 for i in d:
2047 str(i)
2048 except ZeroDivisionError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002049 pass
Georg Brandl48545522008-02-02 10:12:36 +00002050 else:
2051 self.fail("expected ZeroDivisionError from bad property")
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002052
R. David Murrayf28fd242010-02-23 00:24:49 +00002053 @unittest.skipIf(sys.flags.optimize >= 2,
2054 "Docstrings are omitted with -O2 and above")
2055 def test_properties_doc_attrib(self):
Georg Brandl48545522008-02-02 10:12:36 +00002056 class E(object):
2057 def getter(self):
2058 "getter method"
2059 return 0
2060 def setter(self_, value):
2061 "setter method"
2062 pass
2063 prop = property(getter)
2064 self.assertEqual(prop.__doc__, "getter method")
2065 prop2 = property(fset=setter)
2066 self.assertEqual(prop2.__doc__, None)
2067
R. David Murrayf28fd242010-02-23 00:24:49 +00002068 def test_testcapi_no_segfault(self):
Georg Brandl48545522008-02-02 10:12:36 +00002069 # this segfaulted in 2.5b2
2070 try:
2071 import _testcapi
2072 except ImportError:
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002073 pass
Georg Brandl48545522008-02-02 10:12:36 +00002074 else:
2075 class X(object):
2076 p = property(_testcapi.test_with_docstring)
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002077
Georg Brandl48545522008-02-02 10:12:36 +00002078 def test_properties_plus(self):
2079 class C(object):
2080 foo = property(doc="hello")
2081 @foo.getter
2082 def foo(self):
2083 return self._foo
2084 @foo.setter
2085 def foo(self, value):
2086 self._foo = abs(value)
2087 @foo.deleter
2088 def foo(self):
2089 del self._foo
2090 c = C()
2091 self.assertEqual(C.foo.__doc__, "hello")
2092 self.assertFalse(hasattr(c, "foo"))
2093 c.foo = -42
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002094 self.assertTrue(hasattr(c, '_foo'))
Georg Brandl48545522008-02-02 10:12:36 +00002095 self.assertEqual(c._foo, 42)
2096 self.assertEqual(c.foo, 42)
2097 del c.foo
2098 self.assertFalse(hasattr(c, '_foo'))
2099 self.assertFalse(hasattr(c, "foo"))
Walter Dörwalddbd2d252002-03-25 18:36:32 +00002100
Georg Brandl48545522008-02-02 10:12:36 +00002101 class D(C):
2102 @C.foo.deleter
2103 def foo(self):
2104 try:
2105 del self._foo
2106 except AttributeError:
2107 pass
2108 d = D()
2109 d.foo = 24
2110 self.assertEqual(d.foo, 24)
2111 del d.foo
2112 del d.foo
Guido van Rossum8ace1ab2002-04-06 01:05:01 +00002113
Georg Brandl48545522008-02-02 10:12:36 +00002114 class E(object):
2115 @property
2116 def foo(self):
2117 return self._foo
2118 @foo.setter
2119 def foo(self, value):
2120 raise RuntimeError
2121 @foo.setter
2122 def foo(self, value):
2123 self._foo = abs(value)
2124 @foo.deleter
2125 def foo(self, value=None):
2126 del self._foo
Guido van Rossume8fc6402002-04-16 16:44:51 +00002127
Georg Brandl48545522008-02-02 10:12:36 +00002128 e = E()
2129 e.foo = -42
2130 self.assertEqual(e.foo, 42)
2131 del e.foo
Guido van Rossumd99b3e72002-04-18 00:27:33 +00002132
Georg Brandl48545522008-02-02 10:12:36 +00002133 class F(E):
2134 @E.foo.deleter
2135 def foo(self):
2136 del self._foo
2137 @foo.setter
2138 def foo(self, value):
2139 self._foo = max(0, value)
2140 f = F()
2141 f.foo = -10
2142 self.assertEqual(f.foo, 0)
2143 del f.foo
Guido van Rossuma48cb8f2002-06-06 17:53:03 +00002144
Georg Brandl48545522008-02-02 10:12:36 +00002145 def test_dict_constructors(self):
2146 # Testing dict constructor ...
2147 d = dict()
2148 self.assertEqual(d, {})
2149 d = dict({})
2150 self.assertEqual(d, {})
2151 d = dict({1: 2, 'a': 'b'})
2152 self.assertEqual(d, {1: 2, 'a': 'b'})
2153 self.assertEqual(d, dict(d.items()))
2154 self.assertEqual(d, dict(d.iteritems()))
2155 d = dict({'one':1, 'two':2})
2156 self.assertEqual(d, dict(one=1, two=2))
2157 self.assertEqual(d, dict(**d))
2158 self.assertEqual(d, dict({"one": 1}, two=2))
2159 self.assertEqual(d, dict([("two", 2)], one=1))
2160 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2161 self.assertEqual(d, dict(**d))
Guido van Rossum09638c12002-06-13 19:17:46 +00002162
Georg Brandl48545522008-02-02 10:12:36 +00002163 for badarg in 0, 0L, 0j, "0", [0], (0,):
2164 try:
2165 dict(badarg)
2166 except TypeError:
2167 pass
2168 except ValueError:
2169 if badarg == "0":
2170 # It's a sequence, and its elements are also sequences (gotta
2171 # love strings <wink>), but they aren't of length 2, so this
2172 # one seemed better as a ValueError than a TypeError.
2173 pass
2174 else:
2175 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002176 else:
Georg Brandl48545522008-02-02 10:12:36 +00002177 self.fail("no TypeError from dict(%r)" % badarg)
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002178
Georg Brandl48545522008-02-02 10:12:36 +00002179 try:
2180 dict({}, {})
2181 except TypeError:
2182 pass
2183 else:
2184 self.fail("no TypeError from dict({}, {})")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002185
Georg Brandl48545522008-02-02 10:12:36 +00002186 class Mapping:
2187 # Lacks a .keys() method; will be added later.
2188 dict = {1:2, 3:4, 'a':1j}
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002189
Georg Brandl48545522008-02-02 10:12:36 +00002190 try:
2191 dict(Mapping())
2192 except TypeError:
2193 pass
2194 else:
2195 self.fail("no TypeError from dict(incomplete mapping)")
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002196
Georg Brandl48545522008-02-02 10:12:36 +00002197 Mapping.keys = lambda self: self.dict.keys()
2198 Mapping.__getitem__ = lambda self, i: self.dict[i]
2199 d = dict(Mapping())
2200 self.assertEqual(d, Mapping.dict)
Michael W. Hudsonf3904422006-11-23 13:54:04 +00002201
Georg Brandl48545522008-02-02 10:12:36 +00002202 # Init from sequence of iterable objects, each producing a 2-sequence.
2203 class AddressBookEntry:
2204 def __init__(self, first, last):
2205 self.first = first
2206 self.last = last
2207 def __iter__(self):
2208 return iter([self.first, self.last])
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002209
Georg Brandl48545522008-02-02 10:12:36 +00002210 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2211 AddressBookEntry('Barry', 'Peters'),
2212 AddressBookEntry('Tim', 'Peters'),
2213 AddressBookEntry('Barry', 'Warsaw')])
2214 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
Guido van Rossum3bbc0ee2002-12-13 17:49:38 +00002215
Georg Brandl48545522008-02-02 10:12:36 +00002216 d = dict(zip(range(4), range(1, 5)))
2217 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
Michael W. Hudson98bbc492002-11-26 14:47:27 +00002218
Georg Brandl48545522008-02-02 10:12:36 +00002219 # Bad sequence lengths.
2220 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2221 try:
2222 dict(bad)
2223 except ValueError:
2224 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00002225 else:
Georg Brandl48545522008-02-02 10:12:36 +00002226 self.fail("no ValueError from dict(%r)" % bad)
2227
2228 def test_dir(self):
2229 # Testing dir() ...
2230 junk = 12
2231 self.assertEqual(dir(), ['junk', 'self'])
2232 del junk
2233
2234 # Just make sure these don't blow up!
2235 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2236 dir(arg)
2237
2238 # Try classic classes.
2239 class C:
2240 Cdata = 1
2241 def Cmethod(self): pass
2242
2243 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2244 self.assertEqual(dir(C), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002245 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002246
2247 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2248 self.assertEqual(dir(c), cstuff)
2249
2250 c.cdata = 2
2251 c.cmethod = lambda self: 0
2252 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002253 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002254
2255 class A(C):
2256 Adata = 1
2257 def Amethod(self): pass
2258
2259 astuff = ['Adata', 'Amethod'] + cstuff
2260 self.assertEqual(dir(A), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002261 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002262 a = A()
2263 self.assertEqual(dir(a), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002264 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002265 a.adata = 42
2266 a.amethod = lambda self: 3
2267 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2268
2269 # The same, but with new-style classes. Since these have object as a
2270 # base class, a lot more gets sucked in.
2271 def interesting(strings):
2272 return [s for s in strings if not s.startswith('_')]
2273
2274 class C(object):
2275 Cdata = 1
2276 def Cmethod(self): pass
2277
2278 cstuff = ['Cdata', 'Cmethod']
2279 self.assertEqual(interesting(dir(C)), cstuff)
2280
2281 c = C()
2282 self.assertEqual(interesting(dir(c)), cstuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002283 self.assertIn('im_self', dir(C.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002284
2285 c.cdata = 2
2286 c.cmethod = lambda self: 0
2287 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002288 self.assertIn('im_self', dir(c.Cmethod))
Georg Brandl48545522008-02-02 10:12:36 +00002289
2290 class A(C):
2291 Adata = 1
2292 def Amethod(self): pass
2293
2294 astuff = ['Adata', 'Amethod'] + cstuff
2295 self.assertEqual(interesting(dir(A)), astuff)
Ezio Melottiaa980582010-01-23 23:04:36 +00002296 self.assertIn('im_self', dir(A.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002297 a = A()
2298 self.assertEqual(interesting(dir(a)), astuff)
2299 a.adata = 42
2300 a.amethod = lambda self: 3
2301 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
Ezio Melottiaa980582010-01-23 23:04:36 +00002302 self.assertIn('im_self', dir(a.Amethod))
Georg Brandl48545522008-02-02 10:12:36 +00002303
2304 # Try a module subclass.
Georg Brandl48545522008-02-02 10:12:36 +00002305 class M(type(sys)):
2306 pass
2307 minstance = M("m")
2308 minstance.b = 2
2309 minstance.a = 1
2310 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2311 self.assertEqual(names, ['a', 'b'])
2312
2313 class M2(M):
2314 def getdict(self):
2315 return "Not a dict!"
2316 __dict__ = property(getdict)
2317
2318 m2instance = M2("m2")
2319 m2instance.b = 2
2320 m2instance.a = 1
2321 self.assertEqual(m2instance.__dict__, "Not a dict!")
2322 try:
2323 dir(m2instance)
2324 except TypeError:
2325 pass
2326
2327 # Two essentially featureless objects, just inheriting stuff from
2328 # object.
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00002329 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2330 if test_support.check_impl_detail():
2331 # None differs in PyPy: it has a __nonzero__
2332 self.assertEqual(dir(None), dir(Ellipsis))
Georg Brandl48545522008-02-02 10:12:36 +00002333
2334 # Nasty test case for proxied objects
2335 class Wrapper(object):
2336 def __init__(self, obj):
2337 self.__obj = obj
2338 def __repr__(self):
2339 return "Wrapper(%s)" % repr(self.__obj)
2340 def __getitem__(self, key):
2341 return Wrapper(self.__obj[key])
2342 def __len__(self):
2343 return len(self.__obj)
2344 def __getattr__(self, name):
2345 return Wrapper(getattr(self.__obj, name))
2346
2347 class C(object):
2348 def __getclass(self):
2349 return Wrapper(type(self))
2350 __class__ = property(__getclass)
2351
2352 dir(C()) # This used to segfault
2353
2354 def test_supers(self):
2355 # Testing super...
2356
2357 class A(object):
2358 def meth(self, a):
2359 return "A(%r)" % a
2360
2361 self.assertEqual(A().meth(1), "A(1)")
2362
2363 class B(A):
2364 def __init__(self):
2365 self.__super = super(B, self)
2366 def meth(self, a):
2367 return "B(%r)" % a + self.__super.meth(a)
2368
2369 self.assertEqual(B().meth(2), "B(2)A(2)")
2370
2371 class C(A):
2372 def meth(self, a):
2373 return "C(%r)" % a + self.__super.meth(a)
2374 C._C__super = super(C)
2375
2376 self.assertEqual(C().meth(3), "C(3)A(3)")
2377
2378 class D(C, B):
2379 def meth(self, a):
2380 return "D(%r)" % a + super(D, self).meth(a)
2381
2382 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2383
2384 # Test for subclassing super
2385
2386 class mysuper(super):
2387 def __init__(self, *args):
2388 return super(mysuper, self).__init__(*args)
2389
2390 class E(D):
2391 def meth(self, a):
2392 return "E(%r)" % a + mysuper(E, self).meth(a)
2393
2394 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2395
2396 class F(E):
2397 def meth(self, a):
2398 s = self.__super # == mysuper(F, self)
2399 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2400 F._F__super = mysuper(F)
2401
2402 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2403
2404 # Make sure certain errors are raised
2405
2406 try:
2407 super(D, 42)
2408 except TypeError:
2409 pass
2410 else:
2411 self.fail("shouldn't allow super(D, 42)")
2412
2413 try:
2414 super(D, C())
2415 except TypeError:
2416 pass
2417 else:
2418 self.fail("shouldn't allow super(D, C())")
2419
2420 try:
2421 super(D).__get__(12)
2422 except TypeError:
2423 pass
2424 else:
2425 self.fail("shouldn't allow super(D).__get__(12)")
2426
2427 try:
2428 super(D).__get__(C())
2429 except TypeError:
2430 pass
2431 else:
2432 self.fail("shouldn't allow super(D).__get__(C())")
2433
2434 # Make sure data descriptors can be overridden and accessed via super
2435 # (new feature in Python 2.3)
2436
2437 class DDbase(object):
2438 def getx(self): return 42
2439 x = property(getx)
2440
2441 class DDsub(DDbase):
2442 def getx(self): return "hello"
2443 x = property(getx)
2444
2445 dd = DDsub()
2446 self.assertEqual(dd.x, "hello")
2447 self.assertEqual(super(DDsub, dd).x, 42)
2448
2449 # Ensure that super() lookup of descriptor from classmethod
2450 # works (SF ID# 743627)
2451
2452 class Base(object):
2453 aProp = property(lambda self: "foo")
2454
2455 class Sub(Base):
2456 @classmethod
2457 def test(klass):
2458 return super(Sub,klass).aProp
2459
2460 self.assertEqual(Sub.test(), Base.aProp)
2461
2462 # Verify that super() doesn't allow keyword args
2463 try:
2464 super(Base, kw=1)
2465 except TypeError:
2466 pass
2467 else:
2468 self.assertEqual("super shouldn't accept keyword args")
2469
2470 def test_basic_inheritance(self):
2471 # Testing inheritance from basic types...
2472
2473 class hexint(int):
2474 def __repr__(self):
2475 return hex(self)
2476 def __add__(self, other):
2477 return hexint(int.__add__(self, other))
2478 # (Note that overriding __radd__ doesn't work,
2479 # because the int type gets first dibs.)
2480 self.assertEqual(repr(hexint(7) + 9), "0x10")
2481 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2482 a = hexint(12345)
2483 self.assertEqual(a, 12345)
2484 self.assertEqual(int(a), 12345)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002485 self.assertTrue(int(a).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002486 self.assertEqual(hash(a), hash(12345))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002487 self.assertTrue((+a).__class__ is int)
2488 self.assertTrue((a >> 0).__class__ is int)
2489 self.assertTrue((a << 0).__class__ is int)
2490 self.assertTrue((hexint(0) << 12).__class__ is int)
2491 self.assertTrue((hexint(0) >> 12).__class__ is int)
Georg Brandl48545522008-02-02 10:12:36 +00002492
2493 class octlong(long):
2494 __slots__ = []
2495 def __str__(self):
2496 s = oct(self)
2497 if s[-1] == 'L':
2498 s = s[:-1]
2499 return s
2500 def __add__(self, other):
2501 return self.__class__(super(octlong, self).__add__(other))
2502 __radd__ = __add__
2503 self.assertEqual(str(octlong(3) + 5), "010")
2504 # (Note that overriding __radd__ here only seems to work
2505 # because the example uses a short int left argument.)
2506 self.assertEqual(str(5 + octlong(3000)), "05675")
2507 a = octlong(12345)
2508 self.assertEqual(a, 12345L)
2509 self.assertEqual(long(a), 12345L)
2510 self.assertEqual(hash(a), hash(12345L))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002511 self.assertTrue(long(a).__class__ is long)
2512 self.assertTrue((+a).__class__ is long)
2513 self.assertTrue((-a).__class__ is long)
2514 self.assertTrue((-octlong(0)).__class__ is long)
2515 self.assertTrue((a >> 0).__class__ is long)
2516 self.assertTrue((a << 0).__class__ is long)
2517 self.assertTrue((a - 0).__class__ is long)
2518 self.assertTrue((a * 1).__class__ is long)
2519 self.assertTrue((a ** 1).__class__ is long)
2520 self.assertTrue((a // 1).__class__ is long)
2521 self.assertTrue((1 * a).__class__ is long)
2522 self.assertTrue((a | 0).__class__ is long)
2523 self.assertTrue((a ^ 0).__class__ is long)
2524 self.assertTrue((a & -1L).__class__ is long)
2525 self.assertTrue((octlong(0) << 12).__class__ is long)
2526 self.assertTrue((octlong(0) >> 12).__class__ is long)
2527 self.assertTrue(abs(octlong(0)).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002528
2529 # Because octlong overrides __add__, we can't check the absence of +0
2530 # optimizations using octlong.
2531 class longclone(long):
2532 pass
2533 a = longclone(1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002534 self.assertTrue((a + 0).__class__ is long)
2535 self.assertTrue((0 + a).__class__ is long)
Georg Brandl48545522008-02-02 10:12:36 +00002536
2537 # Check that negative clones don't segfault
2538 a = longclone(-1)
2539 self.assertEqual(a.__dict__, {})
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002540 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
Georg Brandl48545522008-02-02 10:12:36 +00002541
2542 class precfloat(float):
2543 __slots__ = ['prec']
2544 def __init__(self, value=0.0, prec=12):
2545 self.prec = int(prec)
2546 def __repr__(self):
2547 return "%.*g" % (self.prec, self)
2548 self.assertEqual(repr(precfloat(1.1)), "1.1")
2549 a = precfloat(12345)
2550 self.assertEqual(a, 12345.0)
2551 self.assertEqual(float(a), 12345.0)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002552 self.assertTrue(float(a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002553 self.assertEqual(hash(a), hash(12345.0))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002554 self.assertTrue((+a).__class__ is float)
Georg Brandl48545522008-02-02 10:12:36 +00002555
2556 class madcomplex(complex):
2557 def __repr__(self):
2558 return "%.17gj%+.17g" % (self.imag, self.real)
2559 a = madcomplex(-3, 4)
2560 self.assertEqual(repr(a), "4j-3")
2561 base = complex(-3, 4)
2562 self.assertEqual(base.__class__, complex)
2563 self.assertEqual(a, base)
2564 self.assertEqual(complex(a), base)
2565 self.assertEqual(complex(a).__class__, complex)
2566 a = madcomplex(a) # just trying another form of the constructor
2567 self.assertEqual(repr(a), "4j-3")
2568 self.assertEqual(a, base)
2569 self.assertEqual(complex(a), base)
2570 self.assertEqual(complex(a).__class__, complex)
2571 self.assertEqual(hash(a), hash(base))
2572 self.assertEqual((+a).__class__, complex)
2573 self.assertEqual((a + 0).__class__, complex)
2574 self.assertEqual(a + 0, base)
2575 self.assertEqual((a - 0).__class__, complex)
2576 self.assertEqual(a - 0, base)
2577 self.assertEqual((a * 1).__class__, complex)
2578 self.assertEqual(a * 1, base)
2579 self.assertEqual((a / 1).__class__, complex)
2580 self.assertEqual(a / 1, base)
2581
2582 class madtuple(tuple):
2583 _rev = None
2584 def rev(self):
2585 if self._rev is not None:
2586 return self._rev
2587 L = list(self)
2588 L.reverse()
2589 self._rev = self.__class__(L)
2590 return self._rev
2591 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2592 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2593 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2594 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2595 for i in range(512):
2596 t = madtuple(range(i))
2597 u = t.rev()
2598 v = u.rev()
2599 self.assertEqual(v, t)
2600 a = madtuple((1,2,3,4,5))
2601 self.assertEqual(tuple(a), (1,2,3,4,5))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002602 self.assertTrue(tuple(a).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002603 self.assertEqual(hash(a), hash((1,2,3,4,5)))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002604 self.assertTrue(a[:].__class__ is tuple)
2605 self.assertTrue((a * 1).__class__ is tuple)
2606 self.assertTrue((a * 0).__class__ is tuple)
2607 self.assertTrue((a + ()).__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002608 a = madtuple(())
2609 self.assertEqual(tuple(a), ())
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002610 self.assertTrue(tuple(a).__class__ is tuple)
2611 self.assertTrue((a + a).__class__ is tuple)
2612 self.assertTrue((a * 0).__class__ is tuple)
2613 self.assertTrue((a * 1).__class__ is tuple)
2614 self.assertTrue((a * 2).__class__ is tuple)
2615 self.assertTrue(a[:].__class__ is tuple)
Georg Brandl48545522008-02-02 10:12:36 +00002616
2617 class madstring(str):
2618 _rev = None
2619 def rev(self):
2620 if self._rev is not None:
2621 return self._rev
2622 L = list(self)
2623 L.reverse()
2624 self._rev = self.__class__("".join(L))
2625 return self._rev
2626 s = madstring("abcdefghijklmnopqrstuvwxyz")
2627 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2628 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2629 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2630 for i in range(256):
2631 s = madstring("".join(map(chr, range(i))))
2632 t = s.rev()
2633 u = t.rev()
2634 self.assertEqual(u, s)
2635 s = madstring("12345")
2636 self.assertEqual(str(s), "12345")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002637 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002638
2639 base = "\x00" * 5
2640 s = madstring(base)
2641 self.assertEqual(s, base)
2642 self.assertEqual(str(s), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002643 self.assertTrue(str(s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002644 self.assertEqual(hash(s), hash(base))
2645 self.assertEqual({s: 1}[base], 1)
2646 self.assertEqual({base: 1}[s], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002647 self.assertTrue((s + "").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002648 self.assertEqual(s + "", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002649 self.assertTrue(("" + s).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002650 self.assertEqual("" + s, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002651 self.assertTrue((s * 0).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002652 self.assertEqual(s * 0, "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002653 self.assertTrue((s * 1).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002654 self.assertEqual(s * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002655 self.assertTrue((s * 2).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002656 self.assertEqual(s * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002657 self.assertTrue(s[:].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002658 self.assertEqual(s[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002659 self.assertTrue(s[0:0].__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002660 self.assertEqual(s[0:0], "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002661 self.assertTrue(s.strip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002662 self.assertEqual(s.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002663 self.assertTrue(s.lstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002664 self.assertEqual(s.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002665 self.assertTrue(s.rstrip().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002666 self.assertEqual(s.rstrip(), base)
2667 identitytab = ''.join([chr(i) for i in range(256)])
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002668 self.assertTrue(s.translate(identitytab).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002669 self.assertEqual(s.translate(identitytab), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002670 self.assertTrue(s.translate(identitytab, "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002671 self.assertEqual(s.translate(identitytab, "x"), base)
2672 self.assertEqual(s.translate(identitytab, "\x00"), "")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002673 self.assertTrue(s.replace("x", "x").__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002674 self.assertEqual(s.replace("x", "x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002675 self.assertTrue(s.ljust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002676 self.assertEqual(s.ljust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002677 self.assertTrue(s.rjust(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002678 self.assertEqual(s.rjust(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002679 self.assertTrue(s.center(len(s)).__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002680 self.assertEqual(s.center(len(s)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002681 self.assertTrue(s.lower().__class__ is str)
Georg Brandl48545522008-02-02 10:12:36 +00002682 self.assertEqual(s.lower(), base)
2683
2684 class madunicode(unicode):
2685 _rev = None
2686 def rev(self):
2687 if self._rev is not None:
2688 return self._rev
2689 L = list(self)
2690 L.reverse()
2691 self._rev = self.__class__(u"".join(L))
2692 return self._rev
2693 u = madunicode("ABCDEF")
2694 self.assertEqual(u, u"ABCDEF")
2695 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2696 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2697 base = u"12345"
2698 u = madunicode(base)
2699 self.assertEqual(unicode(u), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002700 self.assertTrue(unicode(u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002701 self.assertEqual(hash(u), hash(base))
2702 self.assertEqual({u: 1}[base], 1)
2703 self.assertEqual({base: 1}[u], 1)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002704 self.assertTrue(u.strip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002705 self.assertEqual(u.strip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002706 self.assertTrue(u.lstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002707 self.assertEqual(u.lstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002708 self.assertTrue(u.rstrip().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002709 self.assertEqual(u.rstrip(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002710 self.assertTrue(u.replace(u"x", u"x").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002711 self.assertEqual(u.replace(u"x", u"x"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002712 self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002713 self.assertEqual(u.replace(u"xy", u"xy"), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002714 self.assertTrue(u.center(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002715 self.assertEqual(u.center(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002716 self.assertTrue(u.ljust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002717 self.assertEqual(u.ljust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002718 self.assertTrue(u.rjust(len(u)).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002719 self.assertEqual(u.rjust(len(u)), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002720 self.assertTrue(u.lower().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002721 self.assertEqual(u.lower(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002722 self.assertTrue(u.upper().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002723 self.assertEqual(u.upper(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002724 self.assertTrue(u.capitalize().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002725 self.assertEqual(u.capitalize(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002726 self.assertTrue(u.title().__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002727 self.assertEqual(u.title(), base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002728 self.assertTrue((u + u"").__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002729 self.assertEqual(u + u"", base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002730 self.assertTrue((u"" + u).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002731 self.assertEqual(u"" + u, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002732 self.assertTrue((u * 0).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002733 self.assertEqual(u * 0, u"")
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002734 self.assertTrue((u * 1).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002735 self.assertEqual(u * 1, base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002736 self.assertTrue((u * 2).__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002737 self.assertEqual(u * 2, base + base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002738 self.assertTrue(u[:].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002739 self.assertEqual(u[:], base)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002740 self.assertTrue(u[0:0].__class__ is unicode)
Georg Brandl48545522008-02-02 10:12:36 +00002741 self.assertEqual(u[0:0], u"")
2742
2743 class sublist(list):
2744 pass
2745 a = sublist(range(5))
2746 self.assertEqual(a, range(5))
2747 a.append("hello")
2748 self.assertEqual(a, range(5) + ["hello"])
2749 a[5] = 5
2750 self.assertEqual(a, range(6))
2751 a.extend(range(6, 20))
2752 self.assertEqual(a, range(20))
2753 a[-5:] = []
2754 self.assertEqual(a, range(15))
2755 del a[10:15]
2756 self.assertEqual(len(a), 10)
2757 self.assertEqual(a, range(10))
2758 self.assertEqual(list(a), range(10))
2759 self.assertEqual(a[0], 0)
2760 self.assertEqual(a[9], 9)
2761 self.assertEqual(a[-10], 0)
2762 self.assertEqual(a[-1], 9)
2763 self.assertEqual(a[:5], range(5))
2764
2765 class CountedInput(file):
2766 """Counts lines read by self.readline().
2767
2768 self.lineno is the 0-based ordinal of the last line read, up to
2769 a maximum of one greater than the number of lines in the file.
2770
2771 self.ateof is true if and only if the final "" line has been read,
2772 at which point self.lineno stops incrementing, and further calls
2773 to readline() continue to return "".
2774 """
2775
2776 lineno = 0
2777 ateof = 0
2778 def readline(self):
2779 if self.ateof:
2780 return ""
2781 s = file.readline(self)
2782 # Next line works too.
2783 # s = super(CountedInput, self).readline()
2784 self.lineno += 1
2785 if s == "":
2786 self.ateof = 1
2787 return s
2788
2789 f = file(name=test_support.TESTFN, mode='w')
2790 lines = ['a\n', 'b\n', 'c\n']
2791 try:
2792 f.writelines(lines)
2793 f.close()
2794 f = CountedInput(test_support.TESTFN)
2795 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2796 got = f.readline()
2797 self.assertEqual(expected, got)
2798 self.assertEqual(f.lineno, i)
2799 self.assertEqual(f.ateof, (i > len(lines)))
2800 f.close()
2801 finally:
2802 try:
2803 f.close()
2804 except:
2805 pass
2806 test_support.unlink(test_support.TESTFN)
2807
2808 def test_keywords(self):
2809 # Testing keyword args to basic type constructors ...
2810 self.assertEqual(int(x=1), 1)
2811 self.assertEqual(float(x=2), 2.0)
2812 self.assertEqual(long(x=3), 3L)
2813 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2814 self.assertEqual(str(object=500), '500')
2815 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2816 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2817 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2818 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2819
2820 for constructor in (int, float, long, complex, str, unicode,
2821 tuple, list, file):
2822 try:
2823 constructor(bogus_keyword_arg=1)
2824 except TypeError:
2825 pass
2826 else:
2827 self.fail("expected TypeError from bogus keyword argument to %r"
2828 % constructor)
2829
2830 def test_str_subclass_as_dict_key(self):
2831 # Testing a str subclass used as dict key ..
2832
2833 class cistr(str):
2834 """Sublcass of str that computes __eq__ case-insensitively.
2835
2836 Also computes a hash code of the string in canonical form.
2837 """
2838
2839 def __init__(self, value):
2840 self.canonical = value.lower()
2841 self.hashcode = hash(self.canonical)
2842
2843 def __eq__(self, other):
2844 if not isinstance(other, cistr):
2845 other = cistr(other)
2846 return self.canonical == other.canonical
2847
2848 def __hash__(self):
2849 return self.hashcode
2850
2851 self.assertEqual(cistr('ABC'), 'abc')
2852 self.assertEqual('aBc', cistr('ABC'))
2853 self.assertEqual(str(cistr('ABC')), 'ABC')
2854
2855 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2856 self.assertEqual(d[cistr('one')], 1)
2857 self.assertEqual(d[cistr('tWo')], 2)
2858 self.assertEqual(d[cistr('THrEE')], 3)
Ezio Melottiaa980582010-01-23 23:04:36 +00002859 self.assertIn(cistr('ONe'), d)
Georg Brandl48545522008-02-02 10:12:36 +00002860 self.assertEqual(d.get(cistr('thrEE')), 3)
2861
2862 def test_classic_comparisons(self):
2863 # Testing classic comparisons...
2864 class classic:
2865 pass
2866
2867 for base in (classic, int, object):
2868 class C(base):
2869 def __init__(self, value):
2870 self.value = int(value)
2871 def __cmp__(self, other):
2872 if isinstance(other, C):
2873 return cmp(self.value, other.value)
2874 if isinstance(other, int) or isinstance(other, long):
2875 return cmp(self.value, other)
2876 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002877 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002878
2879 c1 = C(1)
2880 c2 = C(2)
2881 c3 = C(3)
2882 self.assertEqual(c1, 1)
2883 c = {1: c1, 2: c2, 3: c3}
2884 for x in 1, 2, 3:
2885 for y in 1, 2, 3:
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002886 self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002887 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002888 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002889 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002890 self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))
2891 self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))
Georg Brandl48545522008-02-02 10:12:36 +00002892
2893 def test_rich_comparisons(self):
2894 # Testing rich comparisons...
2895 class Z(complex):
2896 pass
2897 z = Z(1)
2898 self.assertEqual(z, 1+0j)
2899 self.assertEqual(1+0j, z)
2900 class ZZ(complex):
2901 def __eq__(self, other):
2902 try:
2903 return abs(self - other) <= 1e-6
2904 except:
2905 return NotImplemented
Nick Coghlan48361f52008-08-11 15:45:58 +00002906 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002907 zz = ZZ(1.0000003)
2908 self.assertEqual(zz, 1+0j)
2909 self.assertEqual(1+0j, zz)
2910
2911 class classic:
2912 pass
2913 for base in (classic, int, object, list):
2914 class C(base):
2915 def __init__(self, value):
2916 self.value = int(value)
2917 def __cmp__(self_, other):
2918 self.fail("shouldn't call __cmp__")
Nick Coghlan48361f52008-08-11 15:45:58 +00002919 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00002920 def __eq__(self, other):
2921 if isinstance(other, C):
2922 return self.value == other.value
2923 if isinstance(other, int) or isinstance(other, long):
2924 return self.value == other
2925 return NotImplemented
2926 def __ne__(self, other):
2927 if isinstance(other, C):
2928 return self.value != other.value
2929 if isinstance(other, int) or isinstance(other, long):
2930 return self.value != other
2931 return NotImplemented
2932 def __lt__(self, other):
2933 if isinstance(other, C):
2934 return self.value < other.value
2935 if isinstance(other, int) or isinstance(other, long):
2936 return self.value < other
2937 return NotImplemented
2938 def __le__(self, other):
2939 if isinstance(other, C):
2940 return self.value <= other.value
2941 if isinstance(other, int) or isinstance(other, long):
2942 return self.value <= other
2943 return NotImplemented
2944 def __gt__(self, other):
2945 if isinstance(other, C):
2946 return self.value > other.value
2947 if isinstance(other, int) or isinstance(other, long):
2948 return self.value > other
2949 return NotImplemented
2950 def __ge__(self, other):
2951 if isinstance(other, C):
2952 return self.value >= other.value
2953 if isinstance(other, int) or isinstance(other, long):
2954 return self.value >= other
2955 return NotImplemented
2956 c1 = C(1)
2957 c2 = C(2)
2958 c3 = C(3)
2959 self.assertEqual(c1, 1)
2960 c = {1: c1, 2: c2, 3: c3}
2961 for x in 1, 2, 3:
2962 for y in 1, 2, 3:
2963 for op in "<", "<=", "==", "!=", ">", ">=":
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002964 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002965 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002966 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002967 "x=%d, y=%d" % (x, y))
Benjamin Peterson5c8da862009-06-30 22:57:08 +00002968 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
Georg Brandl48545522008-02-02 10:12:36 +00002969 "x=%d, y=%d" % (x, y))
2970
2971 def test_coercions(self):
2972 # Testing coercions...
2973 class I(int): pass
2974 coerce(I(0), 0)
2975 coerce(0, I(0))
2976 class L(long): pass
2977 coerce(L(0), 0)
2978 coerce(L(0), 0L)
2979 coerce(0, L(0))
2980 coerce(0L, L(0))
2981 class F(float): pass
2982 coerce(F(0), 0)
2983 coerce(F(0), 0L)
2984 coerce(F(0), 0.)
2985 coerce(0, F(0))
2986 coerce(0L, F(0))
2987 coerce(0., F(0))
2988 class C(complex): pass
2989 coerce(C(0), 0)
2990 coerce(C(0), 0L)
2991 coerce(C(0), 0.)
2992 coerce(C(0), 0j)
2993 coerce(0, C(0))
2994 coerce(0L, C(0))
2995 coerce(0., C(0))
2996 coerce(0j, C(0))
2997
2998 def test_descrdoc(self):
2999 # Testing descriptor doc strings...
3000 def check(descr, what):
3001 self.assertEqual(descr.__doc__, what)
3002 check(file.closed, "True if the file is closed") # getset descriptor
3003 check(file.name, "file name") # member descriptor
3004
3005 def test_doc_descriptor(self):
3006 # Testing __doc__ descriptor...
3007 # SF bug 542984
3008 class DocDescr(object):
3009 def __get__(self, object, otype):
3010 if object:
3011 object = object.__class__.__name__ + ' instance'
3012 if otype:
3013 otype = otype.__name__
3014 return 'object=%s; type=%s' % (object, otype)
3015 class OldClass:
3016 __doc__ = DocDescr()
3017 class NewClass(object):
3018 __doc__ = DocDescr()
3019 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3020 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3021 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3022 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3023
3024 def test_set_class(self):
3025 # Testing __class__ assignment...
3026 class C(object): pass
3027 class D(object): pass
3028 class E(object): pass
3029 class F(D, E): pass
3030 for cls in C, D, E, F:
3031 for cls2 in C, D, E, F:
3032 x = cls()
3033 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003034 self.assertTrue(x.__class__ is cls2)
Georg Brandl48545522008-02-02 10:12:36 +00003035 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003036 self.assertTrue(x.__class__ is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003037 def cant(x, C):
3038 try:
3039 x.__class__ = C
3040 except TypeError:
3041 pass
3042 else:
3043 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3044 try:
3045 delattr(x, "__class__")
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003046 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003047 pass
3048 else:
3049 self.fail("shouldn't allow del %r.__class__" % x)
3050 cant(C(), list)
3051 cant(list(), C)
3052 cant(C(), 1)
3053 cant(C(), object)
3054 cant(object(), list)
3055 cant(list(), object)
3056 class Int(int): __slots__ = []
3057 cant(2, Int)
3058 cant(Int(), int)
3059 cant(True, int)
3060 cant(2, bool)
3061 o = object()
3062 cant(o, type(1))
3063 cant(o, type(None))
3064 del o
3065 class G(object):
3066 __slots__ = ["a", "b"]
3067 class H(object):
3068 __slots__ = ["b", "a"]
3069 try:
3070 unicode
3071 except NameError:
3072 class I(object):
3073 __slots__ = ["a", "b"]
3074 else:
3075 class I(object):
3076 __slots__ = [unicode("a"), unicode("b")]
3077 class J(object):
3078 __slots__ = ["c", "b"]
3079 class K(object):
3080 __slots__ = ["a", "b", "d"]
3081 class L(H):
3082 __slots__ = ["e"]
3083 class M(I):
3084 __slots__ = ["e"]
3085 class N(J):
3086 __slots__ = ["__weakref__"]
3087 class P(J):
3088 __slots__ = ["__dict__"]
3089 class Q(J):
3090 pass
3091 class R(J):
3092 __slots__ = ["__dict__", "__weakref__"]
3093
3094 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3095 x = cls()
3096 x.a = 1
3097 x.__class__ = cls2
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003098 self.assertTrue(x.__class__ is cls2,
Georg Brandl48545522008-02-02 10:12:36 +00003099 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3100 self.assertEqual(x.a, 1)
3101 x.__class__ = cls
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003102 self.assertTrue(x.__class__ is cls,
Georg Brandl48545522008-02-02 10:12:36 +00003103 "assigning %r as __class__ for %r silently failed" % (cls, x))
3104 self.assertEqual(x.a, 1)
3105 for cls in G, J, K, L, M, N, P, R, list, Int:
3106 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3107 if cls is cls2:
3108 continue
3109 cant(cls(), cls2)
3110
Benjamin Peterson5083dc52009-04-25 00:41:22 +00003111 # Issue5283: when __class__ changes in __del__, the wrong
3112 # type gets DECREF'd.
3113 class O(object):
3114 pass
3115 class A(object):
3116 def __del__(self):
3117 self.__class__ = O
3118 l = [A() for x in range(100)]
3119 del l
3120
Georg Brandl48545522008-02-02 10:12:36 +00003121 def test_set_dict(self):
3122 # Testing __dict__ assignment...
3123 class C(object): pass
3124 a = C()
3125 a.__dict__ = {'b': 1}
3126 self.assertEqual(a.b, 1)
3127 def cant(x, dict):
3128 try:
3129 x.__dict__ = dict
3130 except (AttributeError, TypeError):
3131 pass
3132 else:
3133 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3134 cant(a, None)
3135 cant(a, [])
3136 cant(a, 1)
3137 del a.__dict__ # Deleting __dict__ is allowed
3138
3139 class Base(object):
3140 pass
3141 def verify_dict_readonly(x):
3142 """
3143 x has to be an instance of a class inheriting from Base.
3144 """
3145 cant(x, {})
3146 try:
3147 del x.__dict__
3148 except (AttributeError, TypeError):
3149 pass
3150 else:
3151 self.fail("shouldn't allow del %r.__dict__" % x)
3152 dict_descr = Base.__dict__["__dict__"]
3153 try:
3154 dict_descr.__set__(x, {})
3155 except (AttributeError, TypeError):
3156 pass
3157 else:
3158 self.fail("dict_descr allowed access to %r's dict" % x)
3159
3160 # Classes don't allow __dict__ assignment and have readonly dicts
3161 class Meta1(type, Base):
3162 pass
3163 class Meta2(Base, type):
3164 pass
3165 class D(object):
3166 __metaclass__ = Meta1
3167 class E(object):
3168 __metaclass__ = Meta2
3169 for cls in C, D, E:
3170 verify_dict_readonly(cls)
3171 class_dict = cls.__dict__
3172 try:
3173 class_dict["spam"] = "eggs"
3174 except TypeError:
3175 pass
3176 else:
3177 self.fail("%r's __dict__ can be modified" % cls)
3178
3179 # Modules also disallow __dict__ assignment
3180 class Module1(types.ModuleType, Base):
3181 pass
3182 class Module2(Base, types.ModuleType):
3183 pass
3184 for ModuleType in Module1, Module2:
3185 mod = ModuleType("spam")
3186 verify_dict_readonly(mod)
3187 mod.__dict__["spam"] = "eggs"
3188
3189 # Exception's __dict__ can be replaced, but not deleted
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003190 # (at least not any more than regular exception's __dict__ can
3191 # be deleted; on CPython it is not the case, whereas on PyPy they
3192 # can, just like any other new-style instance's __dict__.)
3193 def can_delete_dict(e):
3194 try:
3195 del e.__dict__
3196 except (TypeError, AttributeError):
3197 return False
3198 else:
3199 return True
Georg Brandl48545522008-02-02 10:12:36 +00003200 class Exception1(Exception, Base):
3201 pass
3202 class Exception2(Base, Exception):
3203 pass
3204 for ExceptionType in Exception, Exception1, Exception2:
3205 e = ExceptionType()
3206 e.__dict__ = {"a": 1}
3207 self.assertEqual(e.a, 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003208 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
Georg Brandl48545522008-02-02 10:12:36 +00003209
3210 def test_pickles(self):
3211 # Testing pickling and copying new-style classes and objects...
3212 import pickle, cPickle
3213
3214 def sorteditems(d):
3215 L = d.items()
3216 L.sort()
3217 return L
3218
3219 global C
3220 class C(object):
3221 def __init__(self, a, b):
3222 super(C, self).__init__()
3223 self.a = a
3224 self.b = b
3225 def __repr__(self):
3226 return "C(%r, %r)" % (self.a, self.b)
3227
3228 global C1
3229 class C1(list):
3230 def __new__(cls, a, b):
3231 return super(C1, cls).__new__(cls)
3232 def __getnewargs__(self):
3233 return (self.a, self.b)
3234 def __init__(self, a, b):
3235 self.a = a
3236 self.b = b
3237 def __repr__(self):
3238 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3239
3240 global C2
3241 class C2(int):
3242 def __new__(cls, a, b, val=0):
3243 return super(C2, cls).__new__(cls, val)
3244 def __getnewargs__(self):
3245 return (self.a, self.b, int(self))
3246 def __init__(self, a, b, val=0):
3247 self.a = a
3248 self.b = b
3249 def __repr__(self):
3250 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3251
3252 global C3
3253 class C3(object):
3254 def __init__(self, foo):
3255 self.foo = foo
3256 def __getstate__(self):
3257 return self.foo
3258 def __setstate__(self, foo):
3259 self.foo = foo
3260
3261 global C4classic, C4
3262 class C4classic: # classic
3263 pass
3264 class C4(C4classic, object): # mixed inheritance
3265 pass
3266
3267 for p in pickle, cPickle:
3268 for bin in 0, 1:
3269 for cls in C, C1, C2:
3270 s = p.dumps(cls, bin)
3271 cls2 = p.loads(s)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003272 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003273
3274 a = C1(1, 2); a.append(42); a.append(24)
3275 b = C2("hello", "world", 42)
3276 s = p.dumps((a, b), bin)
3277 x, y = p.loads(s)
3278 self.assertEqual(x.__class__, a.__class__)
3279 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3280 self.assertEqual(y.__class__, b.__class__)
3281 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3282 self.assertEqual(repr(x), repr(a))
3283 self.assertEqual(repr(y), repr(b))
3284 # Test for __getstate__ and __setstate__ on new style class
3285 u = C3(42)
3286 s = p.dumps(u, bin)
3287 v = p.loads(s)
3288 self.assertEqual(u.__class__, v.__class__)
3289 self.assertEqual(u.foo, v.foo)
3290 # Test for picklability of hybrid class
3291 u = C4()
3292 u.foo = 42
3293 s = p.dumps(u, bin)
3294 v = p.loads(s)
3295 self.assertEqual(u.__class__, v.__class__)
3296 self.assertEqual(u.foo, v.foo)
3297
3298 # Testing copy.deepcopy()
3299 import copy
3300 for cls in C, C1, C2:
3301 cls2 = copy.deepcopy(cls)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003302 self.assertTrue(cls2 is cls)
Georg Brandl48545522008-02-02 10:12:36 +00003303
3304 a = C1(1, 2); a.append(42); a.append(24)
3305 b = C2("hello", "world", 42)
3306 x, y = copy.deepcopy((a, b))
3307 self.assertEqual(x.__class__, a.__class__)
3308 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3309 self.assertEqual(y.__class__, b.__class__)
3310 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3311 self.assertEqual(repr(x), repr(a))
3312 self.assertEqual(repr(y), repr(b))
3313
3314 def test_pickle_slots(self):
3315 # Testing pickling of classes with __slots__ ...
3316 import pickle, cPickle
3317 # Pickling of classes with __slots__ but without __getstate__ should fail
3318 global B, C, D, E
3319 class B(object):
3320 pass
3321 for base in [object, B]:
3322 class C(base):
3323 __slots__ = ['a']
3324 class D(C):
3325 pass
3326 try:
3327 pickle.dumps(C())
3328 except TypeError:
3329 pass
3330 else:
3331 self.fail("should fail: pickle C instance - %s" % base)
3332 try:
3333 cPickle.dumps(C())
3334 except TypeError:
3335 pass
3336 else:
3337 self.fail("should fail: cPickle C instance - %s" % base)
3338 try:
3339 pickle.dumps(C())
3340 except TypeError:
3341 pass
3342 else:
3343 self.fail("should fail: pickle D instance - %s" % base)
3344 try:
3345 cPickle.dumps(D())
3346 except TypeError:
3347 pass
3348 else:
3349 self.fail("should fail: cPickle D instance - %s" % base)
3350 # Give C a nice generic __getstate__ and __setstate__
3351 class C(base):
3352 __slots__ = ['a']
3353 def __getstate__(self):
3354 try:
3355 d = self.__dict__.copy()
3356 except AttributeError:
3357 d = {}
3358 for cls in self.__class__.__mro__:
3359 for sn in cls.__dict__.get('__slots__', ()):
3360 try:
3361 d[sn] = getattr(self, sn)
3362 except AttributeError:
3363 pass
3364 return d
3365 def __setstate__(self, d):
3366 for k, v in d.items():
3367 setattr(self, k, v)
3368 class D(C):
3369 pass
3370 # Now it should work
3371 x = C()
3372 y = pickle.loads(pickle.dumps(x))
3373 self.assertEqual(hasattr(y, 'a'), 0)
3374 y = cPickle.loads(cPickle.dumps(x))
3375 self.assertEqual(hasattr(y, 'a'), 0)
3376 x.a = 42
3377 y = pickle.loads(pickle.dumps(x))
3378 self.assertEqual(y.a, 42)
3379 y = cPickle.loads(cPickle.dumps(x))
3380 self.assertEqual(y.a, 42)
3381 x = D()
3382 x.a = 42
3383 x.b = 100
3384 y = pickle.loads(pickle.dumps(x))
3385 self.assertEqual(y.a + y.b, 142)
3386 y = cPickle.loads(cPickle.dumps(x))
3387 self.assertEqual(y.a + y.b, 142)
3388 # A subclass that adds a slot should also work
3389 class E(C):
3390 __slots__ = ['b']
3391 x = E()
3392 x.a = 42
3393 x.b = "foo"
3394 y = pickle.loads(pickle.dumps(x))
3395 self.assertEqual(y.a, x.a)
3396 self.assertEqual(y.b, x.b)
3397 y = cPickle.loads(cPickle.dumps(x))
3398 self.assertEqual(y.a, x.a)
3399 self.assertEqual(y.b, x.b)
3400
3401 def test_binary_operator_override(self):
3402 # Testing overrides of binary operations...
3403 class I(int):
3404 def __repr__(self):
3405 return "I(%r)" % int(self)
3406 def __add__(self, other):
3407 return I(int(self) + int(other))
3408 __radd__ = __add__
3409 def __pow__(self, other, mod=None):
3410 if mod is None:
3411 return I(pow(int(self), int(other)))
3412 else:
3413 return I(pow(int(self), int(other), int(mod)))
3414 def __rpow__(self, other, mod=None):
3415 if mod is None:
3416 return I(pow(int(other), int(self), mod))
3417 else:
3418 return I(pow(int(other), int(self), int(mod)))
3419
3420 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3421 self.assertEqual(repr(I(1) + 2), "I(3)")
3422 self.assertEqual(repr(1 + I(2)), "I(3)")
3423 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3424 self.assertEqual(repr(2 ** I(3)), "I(8)")
3425 self.assertEqual(repr(I(2) ** 3), "I(8)")
3426 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3427 class S(str):
3428 def __eq__(self, other):
3429 return self.lower() == other.lower()
Nick Coghlan48361f52008-08-11 15:45:58 +00003430 __hash__ = None # Silence Py3k warning
Georg Brandl48545522008-02-02 10:12:36 +00003431
3432 def test_subclass_propagation(self):
3433 # Testing propagation of slot functions to subclasses...
3434 class A(object):
3435 pass
3436 class B(A):
3437 pass
3438 class C(A):
3439 pass
3440 class D(B, C):
3441 pass
3442 d = D()
3443 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3444 A.__hash__ = lambda self: 42
3445 self.assertEqual(hash(d), 42)
3446 C.__hash__ = lambda self: 314
3447 self.assertEqual(hash(d), 314)
3448 B.__hash__ = lambda self: 144
3449 self.assertEqual(hash(d), 144)
3450 D.__hash__ = lambda self: 100
3451 self.assertEqual(hash(d), 100)
Nick Coghlan53663a62008-07-15 14:27:37 +00003452 D.__hash__ = None
3453 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003454 del D.__hash__
3455 self.assertEqual(hash(d), 144)
Nick Coghlan53663a62008-07-15 14:27:37 +00003456 B.__hash__ = None
3457 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003458 del B.__hash__
3459 self.assertEqual(hash(d), 314)
Nick Coghlan53663a62008-07-15 14:27:37 +00003460 C.__hash__ = None
3461 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003462 del C.__hash__
3463 self.assertEqual(hash(d), 42)
Nick Coghlan53663a62008-07-15 14:27:37 +00003464 A.__hash__ = None
3465 self.assertRaises(TypeError, hash, d)
Georg Brandl48545522008-02-02 10:12:36 +00003466 del A.__hash__
3467 self.assertEqual(hash(d), orig_hash)
3468 d.foo = 42
3469 d.bar = 42
3470 self.assertEqual(d.foo, 42)
3471 self.assertEqual(d.bar, 42)
3472 def __getattribute__(self, name):
3473 if name == "foo":
3474 return 24
3475 return object.__getattribute__(self, name)
3476 A.__getattribute__ = __getattribute__
3477 self.assertEqual(d.foo, 24)
3478 self.assertEqual(d.bar, 42)
3479 def __getattr__(self, name):
3480 if name in ("spam", "foo", "bar"):
3481 return "hello"
3482 raise AttributeError, name
3483 B.__getattr__ = __getattr__
3484 self.assertEqual(d.spam, "hello")
3485 self.assertEqual(d.foo, 24)
3486 self.assertEqual(d.bar, 42)
3487 del A.__getattribute__
3488 self.assertEqual(d.foo, 42)
3489 del d.foo
3490 self.assertEqual(d.foo, "hello")
3491 self.assertEqual(d.bar, 42)
3492 del B.__getattr__
3493 try:
3494 d.foo
3495 except AttributeError:
3496 pass
3497 else:
3498 self.fail("d.foo should be undefined now")
3499
3500 # Test a nasty bug in recurse_down_subclasses()
Georg Brandl48545522008-02-02 10:12:36 +00003501 class A(object):
3502 pass
3503 class B(A):
3504 pass
3505 del B
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003506 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003507 A.__setitem__ = lambda *a: None # crash
3508
3509 def test_buffer_inheritance(self):
3510 # Testing that buffer interface is inherited ...
3511
3512 import binascii
3513 # SF bug [#470040] ParseTuple t# vs subclasses.
3514
3515 class MyStr(str):
3516 pass
3517 base = 'abc'
3518 m = MyStr(base)
3519 # b2a_hex uses the buffer interface to get its argument's value, via
3520 # PyArg_ParseTuple 't#' code.
3521 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3522
3523 # It's not clear that unicode will continue to support the character
3524 # buffer interface, and this test will fail if that's taken away.
3525 class MyUni(unicode):
3526 pass
3527 base = u'abc'
3528 m = MyUni(base)
3529 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3530
3531 class MyInt(int):
3532 pass
3533 m = MyInt(42)
3534 try:
3535 binascii.b2a_hex(m)
3536 self.fail('subclass of int should not have a buffer interface')
3537 except TypeError:
3538 pass
3539
3540 def test_str_of_str_subclass(self):
3541 # Testing __str__ defined in subclass of str ...
3542 import binascii
3543 import cStringIO
3544
3545 class octetstring(str):
3546 def __str__(self):
3547 return binascii.b2a_hex(self)
3548 def __repr__(self):
3549 return self + " repr"
3550
3551 o = octetstring('A')
3552 self.assertEqual(type(o), octetstring)
3553 self.assertEqual(type(str(o)), str)
3554 self.assertEqual(type(repr(o)), str)
3555 self.assertEqual(ord(o), 0x41)
3556 self.assertEqual(str(o), '41')
3557 self.assertEqual(repr(o), 'A repr')
3558 self.assertEqual(o.__str__(), '41')
3559 self.assertEqual(o.__repr__(), 'A repr')
3560
3561 capture = cStringIO.StringIO()
3562 # Calling str() or not exercises different internal paths.
3563 print >> capture, o
3564 print >> capture, str(o)
3565 self.assertEqual(capture.getvalue(), '41\n41\n')
3566 capture.close()
3567
3568 def test_keyword_arguments(self):
3569 # Testing keyword arguments to __init__, __call__...
3570 def f(a): return a
3571 self.assertEqual(f.__call__(a=42), 42)
3572 a = []
3573 list.__init__(a, sequence=[0, 1, 2])
3574 self.assertEqual(a, [0, 1, 2])
3575
3576 def test_recursive_call(self):
3577 # Testing recursive __call__() by setting to instance of class...
3578 class A(object):
3579 pass
3580
3581 A.__call__ = A()
3582 try:
3583 A()()
3584 except RuntimeError:
3585 pass
3586 else:
3587 self.fail("Recursion limit should have been reached for __call__()")
3588
3589 def test_delete_hook(self):
3590 # Testing __del__ hook...
3591 log = []
3592 class C(object):
3593 def __del__(self):
3594 log.append(1)
3595 c = C()
3596 self.assertEqual(log, [])
3597 del c
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003598 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003599 self.assertEqual(log, [1])
3600
3601 class D(object): pass
3602 d = D()
3603 try: del d[0]
3604 except TypeError: pass
3605 else: self.fail("invalid del() didn't raise TypeError")
3606
3607 def test_hash_inheritance(self):
3608 # Testing hash of mutable subclasses...
3609
3610 class mydict(dict):
3611 pass
3612 d = mydict()
3613 try:
3614 hash(d)
3615 except TypeError:
3616 pass
3617 else:
3618 self.fail("hash() of dict subclass should fail")
3619
3620 class mylist(list):
3621 pass
3622 d = mylist()
3623 try:
3624 hash(d)
3625 except TypeError:
3626 pass
3627 else:
3628 self.fail("hash() of list subclass should fail")
3629
3630 def test_str_operations(self):
3631 try: 'a' + 5
3632 except TypeError: pass
3633 else: self.fail("'' + 5 doesn't raise TypeError")
3634
3635 try: ''.split('')
3636 except ValueError: pass
3637 else: self.fail("''.split('') doesn't raise ValueError")
3638
3639 try: ''.join([0])
3640 except TypeError: pass
3641 else: self.fail("''.join([0]) doesn't raise TypeError")
3642
3643 try: ''.rindex('5')
3644 except ValueError: pass
3645 else: self.fail("''.rindex('5') doesn't raise ValueError")
3646
3647 try: '%(n)s' % None
3648 except TypeError: pass
3649 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3650
3651 try: '%(n' % {}
3652 except ValueError: pass
3653 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3654
3655 try: '%*s' % ('abc')
3656 except TypeError: pass
3657 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3658
3659 try: '%*.*s' % ('abc', 5)
3660 except TypeError: pass
3661 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3662
3663 try: '%s' % (1, 2)
3664 except TypeError: pass
3665 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3666
3667 try: '%' % None
3668 except ValueError: pass
3669 else: self.fail("'%' % None doesn't raise ValueError")
3670
3671 self.assertEqual('534253'.isdigit(), 1)
3672 self.assertEqual('534253x'.isdigit(), 0)
3673 self.assertEqual('%c' % 5, '\x05')
3674 self.assertEqual('%c' % '5', '5')
3675
3676 def test_deepcopy_recursive(self):
3677 # Testing deepcopy of recursive objects...
3678 class Node:
3679 pass
3680 a = Node()
3681 b = Node()
3682 a.b = b
3683 b.a = a
3684 z = deepcopy(a) # This blew up before
3685
3686 def test_unintialized_modules(self):
3687 # Testing uninitialized module objects...
3688 from types import ModuleType as M
3689 m = M.__new__(M)
3690 str(m)
3691 self.assertEqual(hasattr(m, "__name__"), 0)
3692 self.assertEqual(hasattr(m, "__file__"), 0)
3693 self.assertEqual(hasattr(m, "foo"), 0)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003694 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
Georg Brandl48545522008-02-02 10:12:36 +00003695 m.foo = 1
3696 self.assertEqual(m.__dict__, {"foo": 1})
3697
3698 def test_funny_new(self):
3699 # Testing __new__ returning something unexpected...
3700 class C(object):
3701 def __new__(cls, arg):
3702 if isinstance(arg, str): return [1, 2, 3]
3703 elif isinstance(arg, int): return object.__new__(D)
3704 else: return object.__new__(cls)
3705 class D(C):
3706 def __init__(self, arg):
3707 self.foo = arg
3708 self.assertEqual(C("1"), [1, 2, 3])
3709 self.assertEqual(D("1"), [1, 2, 3])
3710 d = D(None)
3711 self.assertEqual(d.foo, None)
3712 d = C(1)
3713 self.assertEqual(isinstance(d, D), True)
3714 self.assertEqual(d.foo, 1)
3715 d = D(1)
3716 self.assertEqual(isinstance(d, D), True)
3717 self.assertEqual(d.foo, 1)
3718
3719 def test_imul_bug(self):
3720 # Testing for __imul__ problems...
3721 # SF bug 544647
3722 class C(object):
3723 def __imul__(self, other):
3724 return (self, other)
3725 x = C()
3726 y = x
3727 y *= 1.0
3728 self.assertEqual(y, (x, 1.0))
3729 y = x
3730 y *= 2
3731 self.assertEqual(y, (x, 2))
3732 y = x
3733 y *= 3L
3734 self.assertEqual(y, (x, 3L))
3735 y = x
3736 y *= 1L<<100
3737 self.assertEqual(y, (x, 1L<<100))
3738 y = x
3739 y *= None
3740 self.assertEqual(y, (x, None))
3741 y = x
3742 y *= "foo"
3743 self.assertEqual(y, (x, "foo"))
3744
3745 def test_copy_setstate(self):
3746 # Testing that copy.*copy() correctly uses __setstate__...
3747 import copy
3748 class C(object):
3749 def __init__(self, foo=None):
3750 self.foo = foo
3751 self.__foo = foo
3752 def setfoo(self, foo=None):
3753 self.foo = foo
3754 def getfoo(self):
3755 return self.__foo
3756 def __getstate__(self):
3757 return [self.foo]
3758 def __setstate__(self_, lst):
3759 self.assertEqual(len(lst), 1)
3760 self_.__foo = self_.foo = lst[0]
3761 a = C(42)
3762 a.setfoo(24)
3763 self.assertEqual(a.foo, 24)
3764 self.assertEqual(a.getfoo(), 42)
3765 b = copy.copy(a)
3766 self.assertEqual(b.foo, 24)
3767 self.assertEqual(b.getfoo(), 24)
3768 b = copy.deepcopy(a)
3769 self.assertEqual(b.foo, 24)
3770 self.assertEqual(b.getfoo(), 24)
3771
3772 def test_slices(self):
3773 # Testing cases with slices and overridden __getitem__ ...
3774
3775 # Strings
3776 self.assertEqual("hello"[:4], "hell")
3777 self.assertEqual("hello"[slice(4)], "hell")
3778 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3779 class S(str):
3780 def __getitem__(self, x):
3781 return str.__getitem__(self, x)
3782 self.assertEqual(S("hello")[:4], "hell")
3783 self.assertEqual(S("hello")[slice(4)], "hell")
3784 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3785 # Tuples
3786 self.assertEqual((1,2,3)[:2], (1,2))
3787 self.assertEqual((1,2,3)[slice(2)], (1,2))
3788 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3789 class T(tuple):
3790 def __getitem__(self, x):
3791 return tuple.__getitem__(self, x)
3792 self.assertEqual(T((1,2,3))[:2], (1,2))
3793 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3794 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3795 # Lists
3796 self.assertEqual([1,2,3][:2], [1,2])
3797 self.assertEqual([1,2,3][slice(2)], [1,2])
3798 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3799 class L(list):
3800 def __getitem__(self, x):
3801 return list.__getitem__(self, x)
3802 self.assertEqual(L([1,2,3])[:2], [1,2])
3803 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
3804 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
3805 # Now do lists and __setitem__
3806 a = L([1,2,3])
3807 a[slice(1, 3)] = [3,2]
3808 self.assertEqual(a, [1,3,2])
3809 a[slice(0, 2, 1)] = [3,1]
3810 self.assertEqual(a, [3,1,2])
3811 a.__setitem__(slice(1, 3), [2,1])
3812 self.assertEqual(a, [3,2,1])
3813 a.__setitem__(slice(0, 2, 1), [2,3])
3814 self.assertEqual(a, [2,3,1])
3815
3816 def test_subtype_resurrection(self):
3817 # Testing resurrection of new-style instance...
3818
3819 class C(object):
3820 container = []
3821
3822 def __del__(self):
3823 # resurrect the instance
3824 C.container.append(self)
3825
3826 c = C()
3827 c.attr = 42
3828
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003829 # The most interesting thing here is whether this blows up, due to
3830 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3831 # bug).
Georg Brandl48545522008-02-02 10:12:36 +00003832 del c
3833
3834 # If that didn't blow up, it's also interesting to see whether clearing
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003835 # the last container slot works: that will attempt to delete c again,
3836 # which will cause c to get appended back to the container again
3837 # "during" the del. (On non-CPython implementations, however, __del__
3838 # is typically not called again.)
3839 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00003840 self.assertEqual(len(C.container), 1)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003841 del C.container[-1]
3842 if test_support.check_impl_detail():
3843 test_support.gc_collect()
3844 self.assertEqual(len(C.container), 1)
3845 self.assertEqual(C.container[-1].attr, 42)
Georg Brandl48545522008-02-02 10:12:36 +00003846
3847 # Make c mortal again, so that the test framework with -l doesn't report
3848 # it as a leak.
3849 del C.__del__
3850
3851 def test_slots_trash(self):
3852 # Testing slot trash...
3853 # Deallocating deeply nested slotted trash caused stack overflows
3854 class trash(object):
3855 __slots__ = ['x']
3856 def __init__(self, x):
3857 self.x = x
3858 o = None
3859 for i in xrange(50000):
3860 o = trash(o)
3861 del o
3862
3863 def test_slots_multiple_inheritance(self):
3864 # SF bug 575229, multiple inheritance w/ slots dumps core
3865 class A(object):
3866 __slots__=()
3867 class B(object):
3868 pass
3869 class C(A,B) :
3870 __slots__=()
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003871 if test_support.check_impl_detail():
3872 self.assertEqual(C.__basicsize__, B.__basicsize__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00003873 self.assertTrue(hasattr(C, '__dict__'))
3874 self.assertTrue(hasattr(C, '__weakref__'))
Georg Brandl48545522008-02-02 10:12:36 +00003875 C().x = 2
3876
3877 def test_rmul(self):
3878 # Testing correct invocation of __rmul__...
3879 # SF patch 592646
3880 class C(object):
3881 def __mul__(self, other):
3882 return "mul"
3883 def __rmul__(self, other):
3884 return "rmul"
3885 a = C()
3886 self.assertEqual(a*2, "mul")
3887 self.assertEqual(a*2.2, "mul")
3888 self.assertEqual(2*a, "rmul")
3889 self.assertEqual(2.2*a, "rmul")
3890
3891 def test_ipow(self):
3892 # Testing correct invocation of __ipow__...
3893 # [SF bug 620179]
3894 class C(object):
3895 def __ipow__(self, other):
3896 pass
3897 a = C()
3898 a **= 2
3899
3900 def test_mutable_bases(self):
3901 # Testing mutable bases...
3902
3903 # stuff that should work:
3904 class C(object):
3905 pass
3906 class C2(object):
3907 def __getattribute__(self, attr):
3908 if attr == 'a':
3909 return 2
3910 else:
3911 return super(C2, self).__getattribute__(attr)
3912 def meth(self):
3913 return 1
3914 class D(C):
3915 pass
3916 class E(D):
3917 pass
3918 d = D()
3919 e = E()
3920 D.__bases__ = (C,)
3921 D.__bases__ = (C2,)
3922 self.assertEqual(d.meth(), 1)
3923 self.assertEqual(e.meth(), 1)
3924 self.assertEqual(d.a, 2)
3925 self.assertEqual(e.a, 2)
3926 self.assertEqual(C2.__subclasses__(), [D])
3927
Georg Brandl48545522008-02-02 10:12:36 +00003928 try:
3929 del D.__bases__
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00003930 except (TypeError, AttributeError):
Georg Brandl48545522008-02-02 10:12:36 +00003931 pass
3932 else:
3933 self.fail("shouldn't be able to delete .__bases__")
3934
3935 try:
3936 D.__bases__ = ()
3937 except TypeError, msg:
3938 if str(msg) == "a new-style class can't have only classic bases":
3939 self.fail("wrong error message for .__bases__ = ()")
3940 else:
3941 self.fail("shouldn't be able to set .__bases__ to ()")
3942
3943 try:
3944 D.__bases__ = (D,)
3945 except TypeError:
3946 pass
3947 else:
3948 # actually, we'll have crashed by here...
3949 self.fail("shouldn't be able to create inheritance cycles")
3950
3951 try:
3952 D.__bases__ = (C, C)
3953 except TypeError:
3954 pass
3955 else:
3956 self.fail("didn't detect repeated base classes")
3957
3958 try:
3959 D.__bases__ = (E,)
3960 except TypeError:
3961 pass
3962 else:
3963 self.fail("shouldn't be able to create inheritance cycles")
3964
3965 # let's throw a classic class into the mix:
3966 class Classic:
3967 def meth2(self):
3968 return 3
3969
3970 D.__bases__ = (C, Classic)
3971
3972 self.assertEqual(d.meth2(), 3)
3973 self.assertEqual(e.meth2(), 3)
3974 try:
3975 d.a
3976 except AttributeError:
3977 pass
3978 else:
3979 self.fail("attribute should have vanished")
3980
3981 try:
3982 D.__bases__ = (Classic,)
3983 except TypeError:
3984 pass
3985 else:
3986 self.fail("new-style class must have a new-style base")
3987
Benjamin Petersond4d400c2009-04-18 20:12:47 +00003988 def test_builtin_bases(self):
3989 # Make sure all the builtin types can have their base queried without
3990 # segfaulting. See issue #5787.
3991 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
3992 if isinstance(tp, type)]
3993 for tp in builtin_types:
3994 object.__getattribute__(tp, "__bases__")
3995 if tp is not object:
3996 self.assertEqual(len(tp.__bases__), 1, tp)
3997
Benjamin Petersonaccb3d02009-04-18 21:03:10 +00003998 class L(list):
3999 pass
4000
4001 class C(object):
4002 pass
4003
4004 class D(C):
4005 pass
4006
4007 try:
4008 L.__bases__ = (dict,)
4009 except TypeError:
4010 pass
4011 else:
4012 self.fail("shouldn't turn list subclass into dict subclass")
4013
4014 try:
4015 list.__bases__ = (dict,)
4016 except TypeError:
4017 pass
4018 else:
4019 self.fail("shouldn't be able to assign to list.__bases__")
4020
4021 try:
4022 D.__bases__ = (C, list)
4023 except TypeError:
4024 pass
4025 else:
4026 assert 0, "best_base calculation found wanting"
4027
Benjamin Petersond4d400c2009-04-18 20:12:47 +00004028
Georg Brandl48545522008-02-02 10:12:36 +00004029 def test_mutable_bases_with_failing_mro(self):
4030 # Testing mutable bases with failing mro...
4031 class WorkOnce(type):
4032 def __new__(self, name, bases, ns):
4033 self.flag = 0
4034 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4035 def mro(self):
4036 if self.flag > 0:
4037 raise RuntimeError, "bozo"
4038 else:
4039 self.flag += 1
4040 return type.mro(self)
4041
4042 class WorkAlways(type):
4043 def mro(self):
4044 # this is here to make sure that .mro()s aren't called
4045 # with an exception set (which was possible at one point).
4046 # An error message will be printed in a debug build.
4047 # What's a good way to test for this?
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004048 return type.mro(self)
4049
Georg Brandl48545522008-02-02 10:12:36 +00004050 class C(object):
4051 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004052
Georg Brandl48545522008-02-02 10:12:36 +00004053 class C2(object):
4054 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004055
Georg Brandl48545522008-02-02 10:12:36 +00004056 class D(C):
4057 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004058
Georg Brandl48545522008-02-02 10:12:36 +00004059 class E(D):
4060 pass
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004061
Georg Brandl48545522008-02-02 10:12:36 +00004062 class F(D):
4063 __metaclass__ = WorkOnce
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004064
Georg Brandl48545522008-02-02 10:12:36 +00004065 class G(D):
4066 __metaclass__ = WorkAlways
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004067
Georg Brandl48545522008-02-02 10:12:36 +00004068 # Immediate subclasses have their mro's adjusted in alphabetical
4069 # order, so E's will get adjusted before adjusting F's fails. We
4070 # check here that E's gets restored.
Michael W. Hudson586da8f2002-11-27 15:20:19 +00004071
Georg Brandl48545522008-02-02 10:12:36 +00004072 E_mro_before = E.__mro__
4073 D_mro_before = D.__mro__
Armin Rigofd163f92005-12-29 15:59:19 +00004074
Armin Rigofd163f92005-12-29 15:59:19 +00004075 try:
Georg Brandl48545522008-02-02 10:12:36 +00004076 D.__bases__ = (C2,)
4077 except RuntimeError:
4078 self.assertEqual(E.__mro__, E_mro_before)
4079 self.assertEqual(D.__mro__, D_mro_before)
4080 else:
4081 self.fail("exception not propagated")
4082
4083 def test_mutable_bases_catch_mro_conflict(self):
4084 # Testing mutable bases catch mro conflict...
4085 class A(object):
4086 pass
4087
4088 class B(object):
4089 pass
4090
4091 class C(A, B):
4092 pass
4093
4094 class D(A, B):
4095 pass
4096
4097 class E(C, D):
4098 pass
4099
4100 try:
4101 C.__bases__ = (B, A)
Armin Rigofd163f92005-12-29 15:59:19 +00004102 except TypeError:
4103 pass
4104 else:
Georg Brandl48545522008-02-02 10:12:36 +00004105 self.fail("didn't catch MRO conflict")
Armin Rigofd163f92005-12-29 15:59:19 +00004106
Georg Brandl48545522008-02-02 10:12:36 +00004107 def test_mutable_names(self):
4108 # Testing mutable names...
4109 class C(object):
4110 pass
4111
4112 # C.__module__ could be 'test_descr' or '__main__'
4113 mod = C.__module__
4114
4115 C.__name__ = 'D'
4116 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4117
4118 C.__name__ = 'D.E'
4119 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4120
4121 def test_subclass_right_op(self):
4122 # Testing correct dispatch of subclass overloading __r<op>__...
4123
4124 # This code tests various cases where right-dispatch of a subclass
4125 # should be preferred over left-dispatch of a base class.
4126
4127 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4128
4129 class B(int):
4130 def __floordiv__(self, other):
4131 return "B.__floordiv__"
4132 def __rfloordiv__(self, other):
4133 return "B.__rfloordiv__"
4134
4135 self.assertEqual(B(1) // 1, "B.__floordiv__")
4136 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4137
4138 # Case 2: subclass of object; this is just the baseline for case 3
4139
4140 class C(object):
4141 def __floordiv__(self, other):
4142 return "C.__floordiv__"
4143 def __rfloordiv__(self, other):
4144 return "C.__rfloordiv__"
4145
4146 self.assertEqual(C() // 1, "C.__floordiv__")
4147 self.assertEqual(1 // C(), "C.__rfloordiv__")
4148
4149 # Case 3: subclass of new-style class; here it gets interesting
4150
4151 class D(C):
4152 def __floordiv__(self, other):
4153 return "D.__floordiv__"
4154 def __rfloordiv__(self, other):
4155 return "D.__rfloordiv__"
4156
4157 self.assertEqual(D() // C(), "D.__floordiv__")
4158 self.assertEqual(C() // D(), "D.__rfloordiv__")
4159
4160 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4161
4162 class E(C):
4163 pass
4164
4165 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4166
4167 self.assertEqual(E() // 1, "C.__floordiv__")
4168 self.assertEqual(1 // E(), "C.__rfloordiv__")
4169 self.assertEqual(E() // C(), "C.__floordiv__")
4170 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4171
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004172 @test_support.impl_detail("testing an internal kind of method object")
Georg Brandl48545522008-02-02 10:12:36 +00004173 def test_meth_class_get(self):
4174 # Testing __get__ method of METH_CLASS C methods...
4175 # Full coverage of descrobject.c::classmethod_get()
4176
4177 # Baseline
4178 arg = [1, 2, 3]
4179 res = {1: None, 2: None, 3: None}
4180 self.assertEqual(dict.fromkeys(arg), res)
4181 self.assertEqual({}.fromkeys(arg), res)
4182
4183 # Now get the descriptor
4184 descr = dict.__dict__["fromkeys"]
4185
4186 # More baseline using the descriptor directly
4187 self.assertEqual(descr.__get__(None, dict)(arg), res)
4188 self.assertEqual(descr.__get__({})(arg), res)
4189
4190 # Now check various error cases
4191 try:
4192 descr.__get__(None, None)
4193 except TypeError:
4194 pass
4195 else:
4196 self.fail("shouldn't have allowed descr.__get__(None, None)")
4197 try:
4198 descr.__get__(42)
4199 except TypeError:
4200 pass
4201 else:
4202 self.fail("shouldn't have allowed descr.__get__(42)")
4203 try:
4204 descr.__get__(None, 42)
4205 except TypeError:
4206 pass
4207 else:
4208 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4209 try:
4210 descr.__get__(None, int)
4211 except TypeError:
4212 pass
4213 else:
4214 self.fail("shouldn't have allowed descr.__get__(None, int)")
4215
4216 def test_isinst_isclass(self):
4217 # Testing proxy isinstance() and isclass()...
4218 class Proxy(object):
4219 def __init__(self, obj):
4220 self.__obj = obj
4221 def __getattribute__(self, name):
4222 if name.startswith("_Proxy__"):
4223 return object.__getattribute__(self, name)
4224 else:
4225 return getattr(self.__obj, name)
4226 # Test with a classic class
4227 class C:
4228 pass
4229 a = C()
4230 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004231 self.assertIsInstance(a, C) # Baseline
4232 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004233 # Test with a classic subclass
4234 class D(C):
4235 pass
4236 a = D()
4237 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004238 self.assertIsInstance(a, C) # Baseline
4239 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004240 # Test with a new-style class
4241 class C(object):
4242 pass
4243 a = C()
4244 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004245 self.assertIsInstance(a, C) # Baseline
4246 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004247 # Test with a new-style subclass
4248 class D(C):
4249 pass
4250 a = D()
4251 pa = Proxy(a)
Ezio Melottib0f5adc2010-01-24 16:58:36 +00004252 self.assertIsInstance(a, C) # Baseline
4253 self.assertIsInstance(pa, C) # Test
Georg Brandl48545522008-02-02 10:12:36 +00004254
4255 def test_proxy_super(self):
4256 # Testing super() for a proxy object...
4257 class Proxy(object):
4258 def __init__(self, obj):
4259 self.__obj = obj
4260 def __getattribute__(self, name):
4261 if name.startswith("_Proxy__"):
4262 return object.__getattribute__(self, name)
4263 else:
4264 return getattr(self.__obj, name)
4265
4266 class B(object):
4267 def f(self):
4268 return "B.f"
4269
4270 class C(B):
4271 def f(self):
4272 return super(C, self).f() + "->C.f"
4273
4274 obj = C()
4275 p = Proxy(obj)
4276 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4277
4278 def test_carloverre(self):
4279 # Testing prohibition of Carlo Verre's hack...
4280 try:
4281 object.__setattr__(str, "foo", 42)
4282 except TypeError:
4283 pass
4284 else:
4285 self.fail("Carlo Verre __setattr__ suceeded!")
4286 try:
4287 object.__delattr__(str, "lower")
4288 except TypeError:
4289 pass
4290 else:
4291 self.fail("Carlo Verre __delattr__ succeeded!")
4292
4293 def test_weakref_segfault(self):
4294 # Testing weakref segfault...
4295 # SF 742911
4296 import weakref
4297
4298 class Provoker:
4299 def __init__(self, referrent):
4300 self.ref = weakref.ref(referrent)
4301
4302 def __del__(self):
4303 x = self.ref()
4304
4305 class Oops(object):
4306 pass
4307
4308 o = Oops()
4309 o.whatever = Provoker(o)
4310 del o
4311
4312 def test_wrapper_segfault(self):
4313 # SF 927248: deeply nested wrappers could cause stack overflow
4314 f = lambda:None
4315 for i in xrange(1000000):
4316 f = f.__call__
4317 f = None
4318
4319 def test_file_fault(self):
4320 # Testing sys.stdout is changed in getattr...
Nick Coghlan0447cd62009-10-17 06:33:05 +00004321 test_stdout = sys.stdout
Georg Brandl48545522008-02-02 10:12:36 +00004322 class StdoutGuard:
4323 def __getattr__(self, attr):
4324 sys.stdout = sys.__stdout__
4325 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4326 sys.stdout = StdoutGuard()
4327 try:
4328 print "Oops!"
4329 except RuntimeError:
4330 pass
Nick Coghlan0447cd62009-10-17 06:33:05 +00004331 finally:
4332 sys.stdout = test_stdout
Georg Brandl48545522008-02-02 10:12:36 +00004333
4334 def test_vicious_descriptor_nonsense(self):
4335 # Testing vicious_descriptor_nonsense...
4336
4337 # A potential segfault spotted by Thomas Wouters in mail to
4338 # python-dev 2003-04-17, turned into an example & fixed by Michael
4339 # Hudson just less than four months later...
4340
4341 class Evil(object):
4342 def __hash__(self):
4343 return hash('attr')
4344 def __eq__(self, other):
4345 del C.attr
4346 return 0
4347
4348 class Descr(object):
4349 def __get__(self, ob, type=None):
4350 return 1
4351
4352 class C(object):
4353 attr = Descr()
4354
4355 c = C()
4356 c.__dict__[Evil()] = 0
4357
4358 self.assertEqual(c.attr, 1)
4359 # this makes a crash more likely:
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004360 test_support.gc_collect()
Georg Brandl48545522008-02-02 10:12:36 +00004361 self.assertEqual(hasattr(c, 'attr'), False)
4362
4363 def test_init(self):
4364 # SF 1155938
4365 class Foo(object):
4366 def __init__(self):
4367 return 10
4368 try:
4369 Foo()
4370 except TypeError:
4371 pass
4372 else:
4373 self.fail("did not test __init__() for None return")
4374
4375 def test_method_wrapper(self):
4376 # Testing method-wrapper objects...
4377 # <type 'method-wrapper'> did not support any reflection before 2.5
4378
4379 l = []
4380 self.assertEqual(l.__add__, l.__add__)
4381 self.assertEqual(l.__add__, [].__add__)
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004382 self.assertTrue(l.__add__ != [5].__add__)
4383 self.assertTrue(l.__add__ != l.__mul__)
4384 self.assertTrue(l.__add__.__name__ == '__add__')
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004385 if hasattr(l.__add__, '__self__'):
4386 # CPython
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004387 self.assertTrue(l.__add__.__self__ is l)
4388 self.assertTrue(l.__add__.__objclass__ is list)
Benjamin Peterson21f6aac2009-03-26 20:17:27 +00004389 else:
4390 # Python implementations where [].__add__ is a normal bound method
Benjamin Peterson5c8da862009-06-30 22:57:08 +00004391 self.assertTrue(l.__add__.im_self is l)
4392 self.assertTrue(l.__add__.im_class is list)
Georg Brandl48545522008-02-02 10:12:36 +00004393 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4394 try:
4395 hash(l.__add__)
4396 except TypeError:
4397 pass
4398 else:
4399 self.fail("no TypeError from hash([].__add__)")
4400
4401 t = ()
4402 t += (7,)
4403 self.assertEqual(t.__add__, (7,).__add__)
4404 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4405
4406 def test_not_implemented(self):
4407 # Testing NotImplemented...
4408 # all binary methods should be able to return a NotImplemented
Georg Brandl48545522008-02-02 10:12:36 +00004409 import operator
4410
4411 def specialmethod(self, other):
4412 return NotImplemented
4413
4414 def check(expr, x, y):
4415 try:
4416 exec expr in {'x': x, 'y': y, 'operator': operator}
4417 except TypeError:
4418 pass
Armin Rigofd163f92005-12-29 15:59:19 +00004419 else:
Georg Brandl48545522008-02-02 10:12:36 +00004420 self.fail("no TypeError from %r" % (expr,))
Armin Rigofd163f92005-12-29 15:59:19 +00004421
Georg Brandl48545522008-02-02 10:12:36 +00004422 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4423 # TypeErrors
4424 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4425 # ValueErrors instead of TypeErrors
4426 for metaclass in [type, types.ClassType]:
4427 for name, expr, iexpr in [
4428 ('__add__', 'x + y', 'x += y'),
4429 ('__sub__', 'x - y', 'x -= y'),
4430 ('__mul__', 'x * y', 'x *= y'),
4431 ('__truediv__', 'operator.truediv(x, y)', None),
4432 ('__floordiv__', 'operator.floordiv(x, y)', None),
4433 ('__div__', 'x / y', 'x /= y'),
4434 ('__mod__', 'x % y', 'x %= y'),
4435 ('__divmod__', 'divmod(x, y)', None),
4436 ('__pow__', 'x ** y', 'x **= y'),
4437 ('__lshift__', 'x << y', 'x <<= y'),
4438 ('__rshift__', 'x >> y', 'x >>= y'),
4439 ('__and__', 'x & y', 'x &= y'),
4440 ('__or__', 'x | y', 'x |= y'),
4441 ('__xor__', 'x ^ y', 'x ^= y'),
4442 ('__coerce__', 'coerce(x, y)', None)]:
4443 if name == '__coerce__':
4444 rname = name
4445 else:
4446 rname = '__r' + name[2:]
4447 A = metaclass('A', (), {name: specialmethod})
4448 B = metaclass('B', (), {rname: specialmethod})
4449 a = A()
4450 b = B()
4451 check(expr, a, a)
4452 check(expr, a, b)
4453 check(expr, b, a)
4454 check(expr, b, b)
4455 check(expr, a, N1)
4456 check(expr, a, N2)
4457 check(expr, N1, b)
4458 check(expr, N2, b)
4459 if iexpr:
4460 check(iexpr, a, a)
4461 check(iexpr, a, b)
4462 check(iexpr, b, a)
4463 check(iexpr, b, b)
4464 check(iexpr, a, N1)
4465 check(iexpr, a, N2)
4466 iname = '__i' + name[2:]
4467 C = metaclass('C', (), {iname: specialmethod})
4468 c = C()
4469 check(iexpr, c, a)
4470 check(iexpr, c, b)
4471 check(iexpr, c, N1)
4472 check(iexpr, c, N2)
Georg Brandl0fca97a2007-03-05 22:28:08 +00004473
Georg Brandl48545522008-02-02 10:12:36 +00004474 def test_assign_slice(self):
4475 # ceval.c's assign_slice used to check for
4476 # tp->tp_as_sequence->sq_slice instead of
4477 # tp->tp_as_sequence->sq_ass_slice
Georg Brandl0fca97a2007-03-05 22:28:08 +00004478
Georg Brandl48545522008-02-02 10:12:36 +00004479 class C(object):
4480 def __setslice__(self, start, stop, value):
4481 self.value = value
Georg Brandl0fca97a2007-03-05 22:28:08 +00004482
Georg Brandl48545522008-02-02 10:12:36 +00004483 c = C()
4484 c[1:2] = 3
4485 self.assertEqual(c.value, 3)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004486
Benjamin Peterson9179dab2010-01-18 23:07:56 +00004487 def test_set_and_no_get(self):
4488 # See
4489 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4490 class Descr(object):
4491
4492 def __init__(self, name):
4493 self.name = name
4494
4495 def __set__(self, obj, value):
4496 obj.__dict__[self.name] = value
4497 descr = Descr("a")
4498
4499 class X(object):
4500 a = descr
4501
4502 x = X()
4503 self.assertIs(x.a, descr)
4504 x.a = 42
4505 self.assertEqual(x.a, 42)
4506
Benjamin Peterson42d59472010-02-06 20:14:10 +00004507 # Also check type_getattro for correctness.
4508 class Meta(type):
4509 pass
4510 class X(object):
4511 __metaclass__ = Meta
4512 X.a = 42
4513 Meta.a = Descr("a")
4514 self.assertEqual(X.a, 42)
4515
Benjamin Peterson273c2332008-11-17 22:39:09 +00004516 def test_getattr_hooks(self):
4517 # issue 4230
4518
4519 class Descriptor(object):
4520 counter = 0
4521 def __get__(self, obj, objtype=None):
4522 def getter(name):
4523 self.counter += 1
4524 raise AttributeError(name)
4525 return getter
4526
4527 descr = Descriptor()
4528 class A(object):
4529 __getattribute__ = descr
4530 class B(object):
4531 __getattr__ = descr
4532 class C(object):
4533 __getattribute__ = descr
4534 __getattr__ = descr
4535
4536 self.assertRaises(AttributeError, getattr, A(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004537 self.assertEqual(descr.counter, 1)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004538 self.assertRaises(AttributeError, getattr, B(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004539 self.assertEqual(descr.counter, 2)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004540 self.assertRaises(AttributeError, getattr, C(), "attr")
Ezio Melotti2623a372010-11-21 13:34:58 +00004541 self.assertEqual(descr.counter, 4)
Benjamin Peterson273c2332008-11-17 22:39:09 +00004542
4543 import gc
4544 class EvilGetattribute(object):
4545 # This used to segfault
4546 def __getattr__(self, name):
4547 raise AttributeError(name)
4548 def __getattribute__(self, name):
4549 del EvilGetattribute.__getattr__
4550 for i in range(5):
4551 gc.collect()
4552 raise AttributeError(name)
4553
4554 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4555
Benjamin Peterson9b911ca2011-01-12 15:49:47 +00004556 def test_abstractmethods(self):
4557 # type pretends not to have __abstractmethods__.
4558 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4559 class meta(type):
4560 pass
4561 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4562 class X(object):
4563 pass
4564 with self.assertRaises(AttributeError):
4565 del X.__abstractmethods__
4566
Guido van Rossum9acc3872008-01-23 23:23:43 +00004567
Georg Brandl48545522008-02-02 10:12:36 +00004568class DictProxyTests(unittest.TestCase):
4569 def setUp(self):
4570 class C(object):
4571 def meth(self):
4572 pass
4573 self.C = C
Guido van Rossum9acc3872008-01-23 23:23:43 +00004574
Georg Brandl48545522008-02-02 10:12:36 +00004575 def test_iter_keys(self):
4576 # Testing dict-proxy iterkeys...
4577 keys = [ key for key in self.C.__dict__.iterkeys() ]
4578 keys.sort()
Ezio Melotti2623a372010-11-21 13:34:58 +00004579 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
Georg Brandl48545522008-02-02 10:12:36 +00004580 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004581
Georg Brandl48545522008-02-02 10:12:36 +00004582 def test_iter_values(self):
4583 # Testing dict-proxy itervalues...
4584 values = [ values for values in self.C.__dict__.itervalues() ]
4585 self.assertEqual(len(values), 5)
Guido van Rossum9acc3872008-01-23 23:23:43 +00004586
Georg Brandl48545522008-02-02 10:12:36 +00004587 def test_iter_items(self):
4588 # Testing dict-proxy iteritems...
4589 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4590 keys.sort()
4591 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4592 '__weakref__', 'meth'])
Guido van Rossum9acc3872008-01-23 23:23:43 +00004593
Georg Brandl48545522008-02-02 10:12:36 +00004594 def test_dict_type_with_metaclass(self):
4595 # Testing type of __dict__ when __metaclass__ set...
4596 class B(object):
4597 pass
4598 class M(type):
4599 pass
4600 class C:
4601 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4602 __metaclass__ = M
4603 self.assertEqual(type(C.__dict__), type(B.__dict__))
Guido van Rossum9acc3872008-01-23 23:23:43 +00004604
Guido van Rossum9acc3872008-01-23 23:23:43 +00004605
Georg Brandl48545522008-02-02 10:12:36 +00004606class PTypesLongInitTest(unittest.TestCase):
4607 # This is in its own TestCase so that it can be run before any other tests.
4608 def test_pytype_long_ready(self):
4609 # Testing SF bug 551412 ...
Guido van Rossum9acc3872008-01-23 23:23:43 +00004610
Georg Brandl48545522008-02-02 10:12:36 +00004611 # This dumps core when SF bug 551412 isn't fixed --
4612 # but only when test_descr.py is run separately.
4613 # (That can't be helped -- as soon as PyType_Ready()
4614 # is called for PyLong_Type, the bug is gone.)
4615 class UserLong(object):
4616 def __pow__(self, *args):
4617 pass
4618 try:
4619 pow(0L, UserLong(), 0L)
4620 except:
4621 pass
Guido van Rossum9acc3872008-01-23 23:23:43 +00004622
Georg Brandl48545522008-02-02 10:12:36 +00004623 # Another segfault only when run early
4624 # (before PyType_Ready(tuple) is called)
4625 type.mro(tuple)
Guido van Rossum37edeab2008-01-24 17:58:05 +00004626
4627
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004628def test_main():
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004629 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4630 DeprecationWarning)]
4631 if sys.py3kwarning:
4632 deprecations += [
Florent Xicluna07627882010-03-21 01:14:24 +00004633 ("classic (int|long) division", DeprecationWarning),
4634 ("coerce.. not supported", DeprecationWarning),
Florent Xicluna6257a7b2010-03-31 22:01:03 +00004635 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4636 with test_support.check_warnings(*deprecations):
Florent Xicluna07627882010-03-21 01:14:24 +00004637 # Run all local test cases, with PTypesLongInitTest first.
4638 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4639 ClassPropertiesAndMethods, DictProxyTests)
Tim Peters6d6c1a32001-08-02 04:15:00 +00004640
Guido van Rossuma56b42b2001-09-20 21:39:07 +00004641if __name__ == "__main__":
4642 test_main()