Debian Codegraph @

cpython27/Lib/test/test_descr.py

raw symbols SCIP
1 import __builtin__
2 import copy
3 import gc
4 import pickle
5 import sys
6 import types
7 import unittest
8 import warnings
9 import weakref
10
11 from copy import deepcopy
12 from test import test_support
13
14
15 def func(*args):
16 return args
17
18
19 class OperatorsTest(unittest.TestCase):
20
21 def __init__(self, *args, **kwargs):
22 unittest.TestCase.__init__(self, *args, **kwargs)
23 self.binops = {
24 'add': '+',
25 'sub': '-',
26 'mul': '*',
27 'div': '/',
28 'divmod': 'divmod',
29 'pow': '**',
30 'lshift': '<<',
31 'rshift': '>>',
32 'and': '&',
33 'xor': '^',
34 'or': '|',
35 'cmp': 'cmp',
36 'lt': '<',
37 'le': '<=',
38 'eq': '==',
39 'ne': '!=',
40 'gt': '>',
41 'ge': '>=',
42 }
43
44 for name, expr in self.binops.items():
45 if expr.islower():
46 expr = expr + "(a, b)"
47 else:
48 expr = 'a %s b' % expr
49 self.binops[name] = expr
50
51 self.unops = {
52 'pos': '+',
53 'neg': '-',
54 'abs': 'abs',
55 'invert': '~',
56 'int': 'int',
57 'long': 'long',
58 'float': 'float',
59 'oct': 'oct',
60 'hex': 'hex',
61 }
62
63 for name, expr in self.unops.items():
64 if expr.islower():
65 expr = expr + "(a)"
66 else:
67 expr = '%s a' % expr
68 self.unops[name] = expr
69
70 def unop_test(self, a, res, expr="len(a)", meth="__len__"):
71 d = {'a': a}
72 self.assertEqual(eval(expr, d), res)
73 t = type(a)
74 m = getattr(t, meth)
75
76 # Find method in parent class
77 while meth not in t.__dict__:
78 t = t.__bases__[0]
79 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
80 # method object; the getattr() below obtains its underlying function.
81 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
82 self.assertEqual(m(a), res)
83 bm = getattr(a, meth)
84 self.assertEqual(bm(), res)
85
86 def binop_test(self, a, b, res, expr="a+b", meth="__add__"):
87 d = {'a': a, 'b': b}
88
89 # XXX Hack so this passes before 2.3 when -Qnew is specified.
90 if meth == "__div__" and 1/2 == 0.5:
91 meth = "__truediv__"
92
93 if meth == '__divmod__': pass
94
95 self.assertEqual(eval(expr, d), res)
96 t = type(a)
97 m = getattr(t, meth)
98 while meth not in t.__dict__:
99 t = t.__bases__[0]
100 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
101 # method object; the getattr() below obtains its underlying function.
102 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
103 self.assertEqual(m(a, b), res)
104 bm = getattr(a, meth)
105 self.assertEqual(bm(b), res)
106
107 def ternop_test(self, a, b, c, res, expr="a[b:c]", meth="__getslice__"):
108 d = {'a': a, 'b': b, 'c': c}
109 self.assertEqual(eval(expr, d), res)
110 t = type(a)
111 m = getattr(t, meth)
112 while meth not in t.__dict__:
113 t = t.__bases__[0]
114 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
115 # method object; the getattr() below obtains its underlying function.
116 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
117 self.assertEqual(m(a, b, c), res)
118 bm = getattr(a, meth)
119 self.assertEqual(bm(b, c), res)
120
121 def setop_test(self, a, b, res, stmt="a+=b", meth="__iadd__"):
122 d = {'a': deepcopy(a), 'b': b}
123 exec stmt in d
124 self.assertEqual(d['a'], res)
125 t = type(a)
126 m = getattr(t, meth)
127 while meth not in t.__dict__:
128 t = t.__bases__[0]
129 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
130 # method object; the getattr() below obtains its underlying function.
131 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
132 d['a'] = deepcopy(a)
133 m(d['a'], b)
134 self.assertEqual(d['a'], res)
135 d['a'] = deepcopy(a)
136 bm = getattr(d['a'], meth)
137 bm(b)
138 self.assertEqual(d['a'], res)
139
140 def set2op_test(self, a, b, c, res, stmt="a[b]=c", meth="__setitem__"):
141 d = {'a': deepcopy(a), 'b': b, 'c': c}
142 exec stmt in d
143 self.assertEqual(d['a'], res)
144 t = type(a)
145 m = getattr(t, meth)
146 while meth not in t.__dict__:
147 t = t.__bases__[0]
148 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
149 # method object; the getattr() below obtains its underlying function.
150 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
151 d['a'] = deepcopy(a)
152 m(d['a'], b, c)
153 self.assertEqual(d['a'], res)
154 d['a'] = deepcopy(a)
155 bm = getattr(d['a'], meth)
156 bm(b, c)
157 self.assertEqual(d['a'], res)
158
159 def set3op_test(self, a, b, c, d, res, stmt="a[b:c]=d", meth="__setslice__"):
160 dictionary = {'a': deepcopy(a), 'b': b, 'c': c, 'd': d}
161 exec stmt in dictionary
162 self.assertEqual(dictionary['a'], res)
163 t = type(a)
164 while meth not in t.__dict__:
165 t = t.__bases__[0]
166 m = getattr(t, meth)
167 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
168 # method object; the getattr() below obtains its underlying function.
169 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth])
170 dictionary['a'] = deepcopy(a)
171 m(dictionary['a'], b, c, d)
172 self.assertEqual(dictionary['a'], res)
173 dictionary['a'] = deepcopy(a)
174 bm = getattr(dictionary['a'], meth)
175 bm(b, c, d)
176 self.assertEqual(dictionary['a'], res)
177
178 def test_lists(self):
179 # Testing list operations...
180 # Asserts are within individual test methods
181 self.binop_test([1], [2], [1,2], "a+b", "__add__")
182 self.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
183 self.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
184 self.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
185 self.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
186 self.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
187 self.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
188 self.unop_test([1,2,3], 3, "len(a)", "__len__")
189 self.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
190 self.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
191 self.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
192 self.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
193 "__setslice__")
194
195 def test_dicts(self):
196 # Testing dict operations...
197 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
198 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
199 else:
200 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
201 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
202 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
203 self.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
204
205 d = {1:2, 3:4}
206 l1 = []
207 for i in d.keys():
208 l1.append(i)
209 l = []
210 for i in iter(d):
211 l.append(i)
212 self.assertEqual(l, l1)
213 l = []
214 for i in d.__iter__():
215 l.append(i)
216 self.assertEqual(l, l1)
217 l = []
218 for i in dict.__iter__(d):
219 l.append(i)
220 self.assertEqual(l, l1)
221 d = {1:2, 3:4}
222 self.unop_test(d, 2, "len(a)", "__len__")
223 self.assertEqual(eval(repr(d), {}), d)
224 self.assertEqual(eval(d.__repr__(), {}), d)
225 self.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
226 "__setitem__")
227
228 # Tests for unary and binary operators
229 def number_operators(self, a, b, skip=[]):
230 dict = {'a': a, 'b': b}
231
232 for name, expr in self.binops.items():
233 if name not in skip:
234 name = "__%s__" % name
235 if hasattr(a, name):
236 res = eval(expr, dict)
237 self.binop_test(a, b, res, expr, name)
238
239 for name, expr in self.unops.items():
240 if name not in skip:
241 name = "__%s__" % name
242 if hasattr(a, name):
243 res = eval(expr, dict)
244 self.unop_test(a, res, expr, name)
245
246 def test_ints(self):
247 # Testing int operations...
248 self.number_operators(100, 3)
249 # The following crashes in Python 2.2
250 self.assertEqual((1).__nonzero__(), 1)
251 self.assertEqual((0).__nonzero__(), 0)
252 # This returns 'NotImplemented' in Python 2.2
253 class C(int):
254 def __add__(self, other):
255 return NotImplemented
256 self.assertEqual(C(5L), 5)
257 try:
258 C() + ""
259 except TypeError:
260 pass
261 else:
262 self.fail("NotImplemented should have caused TypeError")
263 try:
264 C(sys.maxint+1)
265 except OverflowError:
266 pass
267 else:
268 self.fail("should have raised OverflowError")
269
270 def test_longs(self):
271 # Testing long operations...
272 self.number_operators(100L, 3L)
273
274 def test_floats(self):
275 # Testing float operations...
276 self.number_operators(100.0, 3.0)
277
278 def test_complexes(self):
279 # Testing complex operations...
280 self.number_operators(100.0j, 3.0j, skip=['lt', 'le', 'gt', 'ge',
281 'int', 'long', 'float'])
282
283 class Number(complex):
284 __slots__ = ['prec']
285 def __new__(cls, *args, **kwds):
286 result = complex.__new__(cls, *args)
287 result.prec = kwds.get('prec', 12)
288 return result
289 def __repr__(self):
290 prec = self.prec
291 if self.imag == 0.0:
292 return "%.*g" % (prec, self.real)
293 if self.real == 0.0:
294 return "%.*gj" % (prec, self.imag)
295 return "(%.*g+%.*gj)" % (prec, self.real, prec, self.imag)
296 __str__ = __repr__
297
298 a = Number(3.14, prec=6)
299 self.assertEqual(repr(a), "3.14")
300 self.assertEqual(a.prec, 6)
301
302 a = Number(a, prec=2)
303 self.assertEqual(repr(a), "3.1")
304 self.assertEqual(a.prec, 2)
305
306 a = Number(234.5)
307 self.assertEqual(repr(a), "234.5")
308 self.assertEqual(a.prec, 12)
309
310 @test_support.impl_detail("the module 'xxsubtype' is internal")
311 def test_spam_lists(self):
312 # Testing spamlist operations...
313 import copy, xxsubtype as spam
314
315 def spamlist(l, memo=None):
316 import xxsubtype as spam
317 return spam.spamlist(l)
318
319 # This is an ugly hack:
320 copy._deepcopy_dispatch[spam.spamlist] = spamlist
321
322 self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
323 "__add__")
324 self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
325 self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
326 self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
327 self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
328 "__getslice__")
329 self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
330 "__iadd__")
331 self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
332 "__imul__")
333 self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
334 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
335 "__mul__")
336 self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
337 "__rmul__")
338 self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
339 "__setitem__")
340 self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
341 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
342 # Test subclassing
343 class C(spam.spamlist):
344 def foo(self): return 1
345 a = C()
346 self.assertEqual(a, [])
347 self.assertEqual(a.foo(), 1)
348 a.append(100)
349 self.assertEqual(a, [100])
350 self.assertEqual(a.getstate(), 0)
351 a.setstate(42)
352 self.assertEqual(a.getstate(), 42)
353
354 @test_support.impl_detail("the module 'xxsubtype' is internal")
355 def test_spam_dicts(self):
356 # Testing spamdict operations...
357 import copy, xxsubtype as spam
358 def spamdict(d, memo=None):
359 import xxsubtype as spam
360 sd = spam.spamdict()
361 for k, v in d.items():
362 sd[k] = v
363 return sd
364 # This is an ugly hack:
365 copy._deepcopy_dispatch[spam.spamdict] = spamdict
366
367 self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
368 "__cmp__")
369 self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
370 self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
371 self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
372 d = spamdict({1:2,3:4})
373 l1 = []
374 for i in d.keys():
375 l1.append(i)
376 l = []
377 for i in iter(d):
378 l.append(i)
379 self.assertEqual(l, l1)
380 l = []
381 for i in d.__iter__():
382 l.append(i)
383 self.assertEqual(l, l1)
384 l = []
385 for i in type(spamdict({})).__iter__(d):
386 l.append(i)
387 self.assertEqual(l, l1)
388 straightd = {1:2, 3:4}
389 spamd = spamdict(straightd)
390 self.unop_test(spamd, 2, "len(a)", "__len__")
391 self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
392 self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
393 "a[b]=c", "__setitem__")
394 # Test subclassing
395 class C(spam.spamdict):
396 def foo(self): return 1
397 a = C()
398 self.assertEqual(a.items(), [])
399 self.assertEqual(a.foo(), 1)
400 a['foo'] = 'bar'
401 self.assertEqual(a.items(), [('foo', 'bar')])
402 self.assertEqual(a.getstate(), 0)
403 a.setstate(100)
404 self.assertEqual(a.getstate(), 100)
405
406 def test_wrap_lenfunc_bad_cast(self):
407 try:
408 large_range = xrange(sys.maxsize)
409 except OverflowError as exc:
410 self.skipTest("xrange(sys.maxsize) failed with: %s" % exc)
411 self.assertEqual(large_range.__len__(), sys.maxsize)
412
413
414 class ClassPropertiesAndMethods(unittest.TestCase):
415
416 def assertHasAttr(self, obj, name):
417 self.assertTrue(hasattr(obj, name),
418 '%r has no attribute %r' % (obj, name))
419
420 def assertNotHasAttr(self, obj, name):
421 self.assertFalse(hasattr(obj, name),
422 '%r has unexpected attribute %r' % (obj, name))
423
424 def test_python_dicts(self):
425 # Testing Python subclass of dict...
426 self.assertTrue(issubclass(dict, dict))
427 self.assertIsInstance({}, dict)
428 d = dict()
429 self.assertEqual(d, {})
430 self.assertIs(d.__class__, dict)
431 self.assertIsInstance(d, dict)
432 class C(dict):
433 state = -1
434 def __init__(self_local, *a, **kw):
435 if a:
436 self.assertEqual(len(a), 1)
437 self_local.state = a[0]
438 if kw:
439 for k, v in kw.items():
440 self_local[v] = k
441 def __getitem__(self, key):
442 return self.get(key, 0)
443 def __setitem__(self_local, key, value):
444 self.assertIsInstance(key, type(0))
445 dict.__setitem__(self_local, key, value)
446 def setstate(self, state):
447 self.state = state
448 def getstate(self):
449 return self.state
450 self.assertTrue(issubclass(C, dict))
451 a1 = C(12)
452 self.assertEqual(a1.state, 12)
453 a2 = C(foo=1, bar=2)
454 self.assertEqual(a2[1] == 'foo' and a2[2], 'bar')
455 a = C()
456 self.assertEqual(a.state, -1)
457 self.assertEqual(a.getstate(), -1)
458 a.setstate(0)
459 self.assertEqual(a.state, 0)
460 self.assertEqual(a.getstate(), 0)
461 a.setstate(10)
462 self.assertEqual(a.state, 10)
463 self.assertEqual(a.getstate(), 10)
464 self.assertEqual(a[42], 0)
465 a[42] = 24
466 self.assertEqual(a[42], 24)
467 N = 50
468 for i in range(N):
469 a[i] = C()
470 for j in range(N):
471 a[i][j] = i*j
472 for i in range(N):
473 for j in range(N):
474 self.assertEqual(a[i][j], i*j)
475
476 def test_python_lists(self):
477 # Testing Python subclass of list...
478 class C(list):
479 def __getitem__(self, i):
480 return list.__getitem__(self, i) + 100
481 def __getslice__(self, i, j):
482 return (i, j)
483 a = C()
484 a.extend([0,1,2])
485 self.assertEqual(a[0], 100)
486 self.assertEqual(a[1], 101)
487 self.assertEqual(a[2], 102)
488 self.assertEqual(a[100:200], (100,200))
489
490 def test_metaclass(self):
491 # Testing __metaclass__...
492 class C:
493 __metaclass__ = type
494 def __init__(self):
495 self.__state = 0
496 def getstate(self):
497 return self.__state
498 def setstate(self, state):
499 self.__state = state
500 a = C()
501 self.assertEqual(a.getstate(), 0)
502 a.setstate(10)
503 self.assertEqual(a.getstate(), 10)
504 class D:
505 class __metaclass__(type):
506 def myself(cls): return cls
507 self.assertEqual(D.myself(), D)
508 d = D()
509 self.assertEqual(d.__class__, D)
510 class M1(type):
511 def __new__(cls, name, bases, dict):
512 dict['__spam__'] = 1
513 return type.__new__(cls, name, bases, dict)
514 class C:
515 __metaclass__ = M1
516 self.assertEqual(C.__spam__, 1)
517 c = C()
518 self.assertEqual(c.__spam__, 1)
519
520 class _instance(object):
521 pass
522 class M2(object):
523 @staticmethod
524 def __new__(cls, name, bases, dict):
525 self = object.__new__(cls)
526 self.name = name
527 self.bases = bases
528 self.dict = dict
529 return self
530 def __call__(self):
531 it = _instance()
532 # Early binding of methods
533 for key in self.dict:
534 if key.startswith("__"):
535 continue
536 setattr(it, key, self.dict[key].__get__(it, self))
537 return it
538 class C:
539 __metaclass__ = M2
540 def spam(self):
541 return 42
542 self.assertEqual(C.name, 'C')
543 self.assertEqual(C.bases, ())
544 self.assertIn('spam', C.dict)
545 c = C()
546 self.assertEqual(c.spam(), 42)
547
548 # More metaclass examples
549
550 class autosuper(type):
551 # Automatically add __super to the class
552 # This trick only works for dynamic classes
553 def __new__(metaclass, name, bases, dict):
554 cls = super(autosuper, metaclass).__new__(metaclass,
555 name, bases, dict)
556 # Name mangling for __super removes leading underscores
557 while name[:1] == "_":
558 name = name[1:]
559 if name:
560 name = "_%s__super" % name
561 else:
562 name = "__super"
563 setattr(cls, name, super(cls))
564 return cls
565 class A:
566 __metaclass__ = autosuper
567 def meth(self):
568 return "A"
569 class B(A):
570 def meth(self):
571 return "B" + self.__super.meth()
572 class C(A):
573 def meth(self):
574 return "C" + self.__super.meth()
575 class D(C, B):
576 def meth(self):
577 return "D" + self.__super.meth()
578 self.assertEqual(D().meth(), "DCBA")
579 class E(B, C):
580 def meth(self):
581 return "E" + self.__super.meth()
582 self.assertEqual(E().meth(), "EBCA")
583
584 class autoproperty(type):
585 # Automatically create property attributes when methods
586 # named _get_x and/or _set_x are found
587 def __new__(metaclass, name, bases, dict):
588 hits = {}
589 for key, val in dict.iteritems():
590 if key.startswith("_get_"):
591 key = key[5:]
592 get, set = hits.get(key, (None, None))
593 get = val
594 hits[key] = get, set
595 elif key.startswith("_set_"):
596 key = key[5:]
597 get, set = hits.get(key, (None, None))
598 set = val
599 hits[key] = get, set
600 for key, (get, set) in hits.iteritems():
601 dict[key] = property(get, set)
602 return super(autoproperty, metaclass).__new__(metaclass,
603 name, bases, dict)
604 class A:
605 __metaclass__ = autoproperty
606 def _get_x(self):
607 return -self.__x
608 def _set_x(self, x):
609 self.__x = -x
610 a = A()
611 self.assertNotHasAttr(a, "x")
612 a.x = 12
613 self.assertEqual(a.x, 12)
614 self.assertEqual(a._A__x, -12)
615
616 class multimetaclass(autoproperty, autosuper):
617 # Merge of multiple cooperating metaclasses
618 pass
619 class A:
620 __metaclass__ = multimetaclass
621 def _get_x(self):
622 return "A"
623 class B(A):
624 def _get_x(self):
625 return "B" + self.__super._get_x()
626 class C(A):
627 def _get_x(self):
628 return "C" + self.__super._get_x()
629 class D(C, B):
630 def _get_x(self):
631 return "D" + self.__super._get_x()
632 self.assertEqual(D().x, "DCBA")
633
634 # Make sure type(x) doesn't call x.__class__.__init__
635 class T(type):
636 counter = 0
637 def __init__(self, *args):
638 T.counter += 1
639 class C:
640 __metaclass__ = T
641 self.assertEqual(T.counter, 1)
642 a = C()
643 self.assertEqual(type(a), C)
644 self.assertEqual(T.counter, 1)
645
646 class C(object): pass
647 c = C()
648 try: c()
649 except TypeError: pass
650 else: self.fail("calling object w/o call method should raise "
651 "TypeError")
652
653 # Testing code to find most derived baseclass
654 class A(type):
655 def __new__(*args, **kwargs):
656 return type.__new__(*args, **kwargs)
657
658 class B(object):
659 pass
660
661 class C(object):
662 __metaclass__ = A
663
664 # The most derived metaclass of D is A rather than type.
665 class D(B, C):
666 pass
667
668 def test_module_subclasses(self):
669 # Testing Python subclass of module...
670 log = []
671 MT = type(sys)
672 class MM(MT):
673 def __init__(self, name):
674 MT.__init__(self, name)
675 def __getattribute__(self, name):
676 log.append(("getattr", name))
677 return MT.__getattribute__(self, name)
678 def __setattr__(self, name, value):
679 log.append(("setattr", name, value))
680 MT.__setattr__(self, name, value)
681 def __delattr__(self, name):
682 log.append(("delattr", name))
683 MT.__delattr__(self, name)
684 a = MM("a")
685 a.foo = 12
686 x = a.foo
687 del a.foo
688 self.assertEqual(log, [("setattr", "foo", 12),
689 ("getattr", "foo"),
690 ("delattr", "foo")])
691
692 # http://python.org/sf/1174712
693 try:
694 class Module(types.ModuleType, str):
695 pass
696 except TypeError:
697 pass
698 else:
699 self.fail("inheriting from ModuleType and str at the same time "
700 "should fail")
701
702 def test_multiple_inheritance(self):
703 # Testing multiple inheritance...
704 class C(object):
705 def __init__(self):
706 self.__state = 0
707 def getstate(self):
708 return self.__state
709 def setstate(self, state):
710 self.__state = state
711 a = C()
712 self.assertEqual(a.getstate(), 0)
713 a.setstate(10)
714 self.assertEqual(a.getstate(), 10)
715 class D(dict, C):
716 def __init__(self):
717 type({}).__init__(self)
718 C.__init__(self)
719 d = D()
720 self.assertEqual(d.keys(), [])
721 d["hello"] = "world"
722 self.assertEqual(d.items(), [("hello", "world")])
723 self.assertEqual(d["hello"], "world")
724 self.assertEqual(d.getstate(), 0)
725 d.setstate(10)
726 self.assertEqual(d.getstate(), 10)
727 self.assertEqual(D.__mro__, (D, dict, C, object))
728
729 # SF bug #442833
730 class Node(object):
731 def __int__(self):
732 return int(self.foo())
733 def foo(self):
734 return "23"
735 class Frag(Node, list):
736 def foo(self):
737 return "42"
738 self.assertEqual(Node().__int__(), 23)
739 self.assertEqual(int(Node()), 23)
740 self.assertEqual(Frag().__int__(), 42)
741 self.assertEqual(int(Frag()), 42)
742
743 # MI mixing classic and new-style classes.
744
745 class A:
746 x = 1
747
748 class B(A):
749 pass
750
751 class C(A):
752 x = 2
753
754 class D(B, C):
755 pass
756 self.assertEqual(D.x, 1)
757
758 # Classic MRO is preserved for a classic base class.
759 class E(D, object):
760 pass
761 self.assertEqual(E.__mro__, (E, D, B, A, C, object))
762 self.assertEqual(E.x, 1)
763
764 # But with a mix of classic bases, their MROs are combined using
765 # new-style MRO.
766 class F(B, C, object):
767 pass
768 self.assertEqual(F.__mro__, (F, B, C, A, object))
769 self.assertEqual(F.x, 2)
770
771 # Try something else.
772 class C:
773 def cmethod(self):
774 return "C a"
775 def all_method(self):
776 return "C b"
777
778 class M1(C, object):
779 def m1method(self):
780 return "M1 a"
781 def all_method(self):
782 return "M1 b"
783
784 self.assertEqual(M1.__mro__, (M1, C, object))
785 m = M1()
786 self.assertEqual(m.cmethod(), "C a")
787 self.assertEqual(m.m1method(), "M1 a")
788 self.assertEqual(m.all_method(), "M1 b")
789
790 class D(C):
791 def dmethod(self):
792 return "D a"
793 def all_method(self):
794 return "D b"
795
796 class M2(D, object):
797 def m2method(self):
798 return "M2 a"
799 def all_method(self):
800 return "M2 b"
801
802 self.assertEqual(M2.__mro__, (M2, D, C, object))
803 m = M2()
804 self.assertEqual(m.cmethod(), "C a")
805 self.assertEqual(m.dmethod(), "D a")
806 self.assertEqual(m.m2method(), "M2 a")
807 self.assertEqual(m.all_method(), "M2 b")
808
809 class M3(M1, M2, object):
810 def m3method(self):
811 return "M3 a"
812 def all_method(self):
813 return "M3 b"
814 self.assertEqual(M3.__mro__, (M3, M1, M2, D, C, object))
815 m = M3()
816 self.assertEqual(m.cmethod(), "C a")
817 self.assertEqual(m.dmethod(), "D a")
818 self.assertEqual(m.m1method(), "M1 a")
819 self.assertEqual(m.m2method(), "M2 a")
820 self.assertEqual(m.m3method(), "M3 a")
821 self.assertEqual(m.all_method(), "M3 b")
822
823 class Classic:
824 pass
825 try:
826 class New(Classic):
827 __metaclass__ = type
828 except TypeError:
829 pass
830 else:
831 self.fail("new class with only classic bases - shouldn't be")
832
833 def test_diamond_inheritance(self):
834 # Testing multiple inheritance special cases...
835 class A(object):
836 def spam(self): return "A"
837 self.assertEqual(A().spam(), "A")
838 class B(A):
839 def boo(self): return "B"
840 def spam(self): return "B"
841 self.assertEqual(B().spam(), "B")
842 self.assertEqual(B().boo(), "B")
843 class C(A):
844 def boo(self): return "C"
845 self.assertEqual(C().spam(), "A")
846 self.assertEqual(C().boo(), "C")
847 class D(B, C): pass
848 self.assertEqual(D().spam(), "B")
849 self.assertEqual(D().boo(), "B")
850 self.assertEqual(D.__mro__, (D, B, C, A, object))
851 class E(C, B): pass
852 self.assertEqual(E().spam(), "B")
853 self.assertEqual(E().boo(), "C")
854 self.assertEqual(E.__mro__, (E, C, B, A, object))
855 # MRO order disagreement
856 try:
857 class F(D, E): pass
858 except TypeError:
859 pass
860 else:
861 self.fail("expected MRO order disagreement (F)")
862 try:
863 class G(E, D): pass
864 except TypeError:
865 pass
866 else:
867 self.fail("expected MRO order disagreement (G)")
868
869 # see thread python-dev/2002-October/029035.html
870 def test_ex5_from_c3_switch(self):
871 # Testing ex5 from C3 switch discussion...
872 class A(object): pass
873 class B(object): pass
874 class C(object): pass
875 class X(A): pass
876 class Y(A): pass
877 class Z(X,B,Y,C): pass
878 self.assertEqual(Z.__mro__, (Z, X, B, Y, A, C, object))
879
880 # see "A Monotonic Superclass Linearization for Dylan",
881 # by Kim Barrett et al. (OOPSLA 1996)
882 def test_monotonicity(self):
883 # Testing MRO monotonicity...
884 class Boat(object): pass
885 class DayBoat(Boat): pass
886 class WheelBoat(Boat): pass
887 class EngineLess(DayBoat): pass
888 class SmallMultihull(DayBoat): pass
889 class PedalWheelBoat(EngineLess,WheelBoat): pass
890 class SmallCatamaran(SmallMultihull): pass
891 class Pedalo(PedalWheelBoat,SmallCatamaran): pass
892
893 self.assertEqual(PedalWheelBoat.__mro__,
894 (PedalWheelBoat, EngineLess, DayBoat, WheelBoat, Boat, object))
895 self.assertEqual(SmallCatamaran.__mro__,
896 (SmallCatamaran, SmallMultihull, DayBoat, Boat, object))
897 self.assertEqual(Pedalo.__mro__,
898 (Pedalo, PedalWheelBoat, EngineLess, SmallCatamaran,
899 SmallMultihull, DayBoat, WheelBoat, Boat, object))
900
901 # see "A Monotonic Superclass Linearization for Dylan",
902 # by Kim Barrett et al. (OOPSLA 1996)
903 def test_consistency_with_epg(self):
904 # Testing consistency with EPG...
905 class Pane(object): pass
906 class ScrollingMixin(object): pass
907 class EditingMixin(object): pass
908 class ScrollablePane(Pane,ScrollingMixin): pass
909 class EditablePane(Pane,EditingMixin): pass
910 class EditableScrollablePane(ScrollablePane,EditablePane): pass
911
912 self.assertEqual(EditableScrollablePane.__mro__,
913 (EditableScrollablePane, ScrollablePane, EditablePane, Pane,
914 ScrollingMixin, EditingMixin, object))
915
916 def test_mro_disagreement(self):
917 # Testing error messages for MRO disagreement...
918 mro_err_msg = """Cannot create a consistent method resolution
919 order (MRO) for bases """
920
921 def raises(exc, expected, callable, *args):
922 try:
923 callable(*args)
924 except exc, msg:
925 # the exact msg is generally considered an impl detail
926 if test_support.check_impl_detail():
927 if not str(msg).startswith(expected):
928 self.fail("Message %r, expected %r" %
929 (str(msg), expected))
930 else:
931 self.fail("Expected %s" % exc)
932
933 class A(object): pass
934 class B(A): pass
935 class C(object): pass
936
937 # Test some very simple errors
938 raises(TypeError, "duplicate base class A",
939 type, "X", (A, A), {})
940 raises(TypeError, mro_err_msg,
941 type, "X", (A, B), {})
942 raises(TypeError, mro_err_msg,
943 type, "X", (A, C, B), {})
944 # Test a slightly more complex error
945 class GridLayout(object): pass
946 class HorizontalGrid(GridLayout): pass
947 class VerticalGrid(GridLayout): pass
948 class HVGrid(HorizontalGrid, VerticalGrid): pass
949 class VHGrid(VerticalGrid, HorizontalGrid): pass
950 raises(TypeError, mro_err_msg,
951 type, "ConfusedGrid", (HVGrid, VHGrid), {})
952
953 def test_object_class(self):
954 # Testing object class...
955 a = object()
956 self.assertEqual(a.__class__, object)
957 self.assertEqual(type(a), object)
958 b = object()
959 self.assertNotEqual(a, b)
960 self.assertNotHasAttr(a, "foo")
961 try:
962 a.foo = 12
963 except (AttributeError, TypeError):
964 pass
965 else:
966 self.fail("object() should not allow setting a foo attribute")
967 self.assertNotHasAttr(object(), "__dict__")
968
969 class Cdict(object):
970 pass
971 x = Cdict()
972 self.assertEqual(x.__dict__, {})
973 x.foo = 1
974 self.assertEqual(x.foo, 1)
975 self.assertEqual(x.__dict__, {'foo': 1})
976
977 def test_slots(self):
978 # Testing __slots__...
979 class C0(object):
980 __slots__ = []
981 x = C0()
982 self.assertNotHasAttr(x, "__dict__")
983 self.assertNotHasAttr(x, "foo")
984
985 class C1(object):
986 __slots__ = ['a']
987 x = C1()
988 self.assertNotHasAttr(x, "__dict__")
989 self.assertNotHasAttr(x, "a")
990 x.a = 1
991 self.assertEqual(x.a, 1)
992 x.a = None
993 self.assertEqual(x.a, None)
994 del x.a
995 self.assertNotHasAttr(x, "a")
996
997 class C3(object):
998 __slots__ = ['a', 'b', 'c']
999 x = C3()
1000 self.assertNotHasAttr(x, "__dict__")
1001 self.assertNotHasAttr(x, 'a')
1002 self.assertNotHasAttr(x, 'b')
1003 self.assertNotHasAttr(x, 'c')
1004 x.a = 1
1005 x.b = 2
1006 x.c = 3
1007 self.assertEqual(x.a, 1)
1008 self.assertEqual(x.b, 2)
1009 self.assertEqual(x.c, 3)
1010
1011 class C4(object):
1012 """Validate name mangling"""
1013 __slots__ = ['__a']
1014 def __init__(self, value):
1015 self.__a = value
1016 def get(self):
1017 return self.__a
1018 x = C4(5)
1019 self.assertNotHasAttr(x, '__dict__')
1020 self.assertNotHasAttr(x, '__a')
1021 self.assertEqual(x.get(), 5)
1022 try:
1023 x.__a = 6
1024 except AttributeError:
1025 pass
1026 else:
1027 self.fail("Double underscored names not mangled")
1028
1029 # Make sure slot names are proper identifiers
1030 try:
1031 class C(object):
1032 __slots__ = [None]
1033 except TypeError:
1034 pass
1035 else:
1036 self.fail("[None] slots not caught")
1037 try:
1038 class C(object):
1039 __slots__ = ["foo bar"]
1040 except TypeError:
1041 pass
1042 else:
1043 self.fail("['foo bar'] slots not caught")
1044 try:
1045 class C(object):
1046 __slots__ = ["foo\0bar"]
1047 except TypeError:
1048 pass
1049 else:
1050 self.fail("['foo\\0bar'] slots not caught")
1051 try:
1052 class C(object):
1053 __slots__ = ["1"]
1054 except TypeError:
1055 pass
1056 else:
1057 self.fail("['1'] slots not caught")
1058 try:
1059 class C(object):
1060 __slots__ = [""]
1061 except TypeError:
1062 pass
1063 else:
1064 self.fail("[''] slots not caught")
1065 class C(object):
1066 __slots__ = ["a", "a_b", "_a", "A0123456789Z"]
1067 # XXX(nnorwitz): was there supposed to be something tested
1068 # from the class above?
1069
1070 # Test a single string is not expanded as a sequence.
1071 class C(object):
1072 __slots__ = "abc"
1073 c = C()
1074 c.abc = 5
1075 self.assertEqual(c.abc, 5)
1076
1077 def test_unicode_slots(self):
1078 # Test unicode slot names
1079 try:
1080 unicode
1081 except NameError:
1082 self.skipTest('no unicode support')
1083 else:
1084 # Test a single unicode string is not expanded as a sequence.
1085 class C(object):
1086 __slots__ = unicode("abc")
1087 c = C()
1088 c.abc = 5
1089 self.assertEqual(c.abc, 5)
1090
1091 # _unicode_to_string used to modify slots in certain circumstances
1092 slots = (unicode("foo"), unicode("bar"))
1093 class C(object):
1094 __slots__ = slots
1095 x = C()
1096 x.foo = 5
1097 self.assertEqual(x.foo, 5)
1098 self.assertEqual(type(slots[0]), unicode)
1099 # this used to leak references
1100 try:
1101 class C(object):
1102 __slots__ = [unichr(128)]
1103 except (TypeError, UnicodeEncodeError):
1104 pass
1105 else:
1106 self.fail("[unichr(128)] slots not caught")
1107
1108 # Test leaks
1109 class Counted(object):
1110 counter = 0 # counts the number of instances alive
1111 def __init__(self):
1112 Counted.counter += 1
1113 def __del__(self):
1114 Counted.counter -= 1
1115 class C(object):
1116 __slots__ = ['a', 'b', 'c']
1117 x = C()
1118 x.a = Counted()
1119 x.b = Counted()
1120 x.c = Counted()
1121 self.assertEqual(Counted.counter, 3)
1122 del x
1123 test_support.gc_collect()
1124 self.assertEqual(Counted.counter, 0)
1125 class D(C):
1126 pass
1127 x = D()
1128 x.a = Counted()
1129 x.z = Counted()
1130 self.assertEqual(Counted.counter, 2)
1131 del x
1132 test_support.gc_collect()
1133 self.assertEqual(Counted.counter, 0)
1134 class E(D):
1135 __slots__ = ['e']
1136 x = E()
1137 x.a = Counted()
1138 x.z = Counted()
1139 x.e = Counted()
1140 self.assertEqual(Counted.counter, 3)
1141 del x
1142 test_support.gc_collect()
1143 self.assertEqual(Counted.counter, 0)
1144
1145 # Test cyclical leaks [SF bug 519621]
1146 class F(object):
1147 __slots__ = ['a', 'b']
1148 s = F()
1149 s.a = [Counted(), s]
1150 self.assertEqual(Counted.counter, 1)
1151 s = None
1152 test_support.gc_collect()
1153 self.assertEqual(Counted.counter, 0)
1154
1155 # Test lookup leaks [SF bug 572567]
1156 if hasattr(gc, 'get_objects'):
1157 class G(object):
1158 def __cmp__(self, other):
1159 return 0
1160 __hash__ = None # Silence Py3k warning
1161 g = G()
1162 orig_objects = len(gc.get_objects())
1163 for i in xrange(10):
1164 g==g
1165 new_objects = len(gc.get_objects())
1166 self.assertEqual(orig_objects, new_objects)
1167
1168 class H(object):
1169 __slots__ = ['a', 'b']
1170 def __init__(self):
1171 self.a = 1
1172 self.b = 2
1173 def __del__(self_):
1174 self.assertEqual(self_.a, 1)
1175 self.assertEqual(self_.b, 2)
1176 with test_support.captured_output('stderr') as s:
1177 h = H()
1178 del h
1179 self.assertEqual(s.getvalue(), '')
1180
1181 class X(object):
1182 __slots__ = "a"
1183 with self.assertRaises(AttributeError):
1184 del X().a
1185
1186 def test_slots_special(self):
1187 # Testing __dict__ and __weakref__ in __slots__...
1188 class D(object):
1189 __slots__ = ["__dict__"]
1190 a = D()
1191 self.assertHasAttr(a, "__dict__")
1192 self.assertNotHasAttr(a, "__weakref__")
1193 a.foo = 42
1194 self.assertEqual(a.__dict__, {"foo": 42})
1195
1196 class W(object):
1197 __slots__ = ["__weakref__"]
1198 a = W()
1199 self.assertHasAttr(a, "__weakref__")
1200 self.assertNotHasAttr(a, "__dict__")
1201 try:
1202 a.foo = 42
1203 except AttributeError:
1204 pass
1205 else:
1206 self.fail("shouldn't be allowed to set a.foo")
1207
1208 class C1(W, D):
1209 __slots__ = []
1210 a = C1()
1211 self.assertHasAttr(a, "__dict__")
1212 self.assertHasAttr(a, "__weakref__")
1213 a.foo = 42
1214 self.assertEqual(a.__dict__, {"foo": 42})
1215
1216 class C2(D, W):
1217 __slots__ = []
1218 a = C2()
1219 self.assertHasAttr(a, "__dict__")
1220 self.assertHasAttr(a, "__weakref__")
1221 a.foo = 42
1222 self.assertEqual(a.__dict__, {"foo": 42})
1223
1224 def test_slots_descriptor(self):
1225 # Issue2115: slot descriptors did not correctly check
1226 # the type of the given object
1227 import abc
1228 class MyABC:
1229 __metaclass__ = abc.ABCMeta
1230 __slots__ = "a"
1231
1232 class Unrelated(object):
1233 pass
1234 MyABC.register(Unrelated)
1235
1236 u = Unrelated()
1237 self.assertIsInstance(u, MyABC)
1238
1239 # This used to crash
1240 self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
1241
1242 def test_metaclass_cmp(self):
1243 # See bug 7491.
1244 class M(type):
1245 def __cmp__(self, other):
1246 return -1
1247 class X(object):
1248 __metaclass__ = M
1249 self.assertTrue(X < M)
1250
1251 def test_dynamics(self):
1252 # Testing class attribute propagation...
1253 class D(object):
1254 pass
1255 class E(D):
1256 pass
1257 class F(D):
1258 pass
1259 D.foo = 1
1260 self.assertEqual(D.foo, 1)
1261 # Test that dynamic attributes are inherited
1262 self.assertEqual(E.foo, 1)
1263 self.assertEqual(F.foo, 1)
1264 # Test dynamic instances
1265 class C(object):
1266 pass
1267 a = C()
1268 self.assertNotHasAttr(a, "foobar")
1269 C.foobar = 2
1270 self.assertEqual(a.foobar, 2)
1271 C.method = lambda self: 42
1272 self.assertEqual(a.method(), 42)
1273 C.__repr__ = lambda self: "C()"
1274 self.assertEqual(repr(a), "C()")
1275 C.__int__ = lambda self: 100
1276 self.assertEqual(int(a), 100)
1277 self.assertEqual(a.foobar, 2)
1278 self.assertNotHasAttr(a, "spam")
1279 def mygetattr(self, name):
1280 if name == "spam":
1281 return "spam"
1282 raise AttributeError
1283 C.__getattr__ = mygetattr
1284 self.assertEqual(a.spam, "spam")
1285 a.new = 12
1286 self.assertEqual(a.new, 12)
1287 def mysetattr(self, name, value):
1288 if name == "spam":
1289 raise AttributeError
1290 return object.__setattr__(self, name, value)
1291 C.__setattr__ = mysetattr
1292 try:
1293 a.spam = "not spam"
1294 except AttributeError:
1295 pass
1296 else:
1297 self.fail("expected AttributeError")
1298 self.assertEqual(a.spam, "spam")
1299 class D(C):
1300 pass
1301 d = D()
1302 d.foo = 1
1303 self.assertEqual(d.foo, 1)
1304
1305 # Test handling of int*seq and seq*int
1306 class I(int):
1307 pass
1308 self.assertEqual("a"*I(2), "aa")
1309 self.assertEqual(I(2)*"a", "aa")
1310 self.assertEqual(2*I(3), 6)
1311 self.assertEqual(I(3)*2, 6)
1312 self.assertEqual(I(3)*I(2), 6)
1313
1314 # Test handling of long*seq and seq*long
1315 class L(long):
1316 pass
1317 self.assertEqual("a"*L(2L), "aa")
1318 self.assertEqual(L(2L)*"a", "aa")
1319 self.assertEqual(2*L(3), 6)
1320 self.assertEqual(L(3)*2, 6)
1321 self.assertEqual(L(3)*L(2), 6)
1322
1323 # Test comparison of classes with dynamic metaclasses
1324 class dynamicmetaclass(type):
1325 pass
1326 class someclass:
1327 __metaclass__ = dynamicmetaclass
1328 self.assertNotEqual(someclass, object)
1329
1330 def test_errors(self):
1331 # Testing errors...
1332 try:
1333 class C(list, dict):
1334 pass
1335 except TypeError:
1336 pass
1337 else:
1338 self.fail("inheritance from both list and dict should be illegal")
1339
1340 try:
1341 class C(object, None):
1342 pass
1343 except TypeError:
1344 pass
1345 else:
1346 self.fail("inheritance from non-type should be illegal")
1347 class Classic:
1348 pass
1349
1350 try:
1351 class C(type(len)):
1352 pass
1353 except TypeError:
1354 pass
1355 else:
1356 self.fail("inheritance from CFunction should be illegal")
1357
1358 try:
1359 class C(object):
1360 __slots__ = 1
1361 except TypeError:
1362 pass
1363 else:
1364 self.fail("__slots__ = 1 should be illegal")
1365
1366 try:
1367 class C(object):
1368 __slots__ = [1]
1369 except TypeError:
1370 pass
1371 else:
1372 self.fail("__slots__ = [1] should be illegal")
1373
1374 class M1(type):
1375 pass
1376 class M2(type):
1377 pass
1378 class A1(object):
1379 __metaclass__ = M1
1380 class A2(object):
1381 __metaclass__ = M2
1382 try:
1383 class B(A1, A2):
1384 pass
1385 except TypeError:
1386 pass
1387 else:
1388 self.fail("finding the most derived metaclass should have failed")
1389
1390 def test_classmethods(self):
1391 # Testing class methods...
1392 class C(object):
1393 def foo(*a): return a
1394 goo = classmethod(foo)
1395 c = C()
1396 self.assertEqual(C.goo(1), (C, 1))
1397 self.assertEqual(c.goo(1), (C, 1))
1398 self.assertEqual(c.foo(1), (c, 1))
1399 class D(C):
1400 pass
1401 d = D()
1402 self.assertEqual(D.goo(1), (D, 1))
1403 self.assertEqual(d.goo(1), (D, 1))
1404 self.assertEqual(d.foo(1), (d, 1))
1405 self.assertEqual(D.foo(d, 1), (d, 1))
1406 # Test for a specific crash (SF bug 528132)
1407 def f(cls, arg): return (cls, arg)
1408 ff = classmethod(f)
1409 self.assertEqual(ff.__get__(0, int)(42), (int, 42))
1410 self.assertEqual(ff.__get__(0)(42), (int, 42))
1411
1412 # Test super() with classmethods (SF bug 535444)
1413 self.assertEqual(C.goo.im_self, C)
1414 self.assertEqual(D.goo.im_self, D)
1415 self.assertEqual(super(D,D).goo.im_self, D)
1416 self.assertEqual(super(D,d).goo.im_self, D)
1417 self.assertEqual(super(D,D).goo(), (D,))
1418 self.assertEqual(super(D,d).goo(), (D,))
1419
1420 # Verify that a non-callable will raise
1421 meth = classmethod(1).__get__(1)
1422 self.assertRaises(TypeError, meth)
1423
1424 # Verify that classmethod() doesn't allow keyword args
1425 try:
1426 classmethod(f, kw=1)
1427 except TypeError:
1428 pass
1429 else:
1430 self.fail("classmethod shouldn't accept keyword args")
1431
1432 @test_support.cpython_only
1433 def test_classmethod_copy_pickle(self):
1434 cm = classmethod(func)
1435 with test_support.check_py3k_warnings(
1436 (".*classmethod", DeprecationWarning)):
1437 copy.copy(cm)
1438 with test_support.check_py3k_warnings(
1439 (".*classmethod", DeprecationWarning)):
1440 copy.deepcopy(cm)
1441 for proto in range(2):
1442 self.assertRaises(TypeError, pickle.dumps, cm, proto)
1443 with test_support.check_py3k_warnings(
1444 (".*classmethod", DeprecationWarning)):
1445 pickle.dumps(cm, 2)
1446
1447 @test_support.impl_detail("the module 'xxsubtype' is internal")
1448 def test_classmethods_in_c(self):
1449 # Testing C-based class methods...
1450 import xxsubtype as spam
1451 a = (1, 2, 3)
1452 d = {'abc': 123}
1453 x, a1, d1 = spam.spamlist.classmeth(*a, **d)
1454 self.assertEqual(x, spam.spamlist)
1455 self.assertEqual(a, a1)
1456 self.assertEqual(d, d1)
1457 x, a1, d1 = spam.spamlist().classmeth(*a, **d)
1458 self.assertEqual(x, spam.spamlist)
1459 self.assertEqual(a, a1)
1460 self.assertEqual(d, d1)
1461 spam_cm = spam.spamlist.__dict__['classmeth']
1462 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d)
1463 self.assertEqual(x2, spam.spamlist)
1464 self.assertEqual(a2, a1)
1465 self.assertEqual(d2, d1)
1466 class SubSpam(spam.spamlist): pass
1467 x2, a2, d2 = spam_cm(SubSpam, *a, **d)
1468 self.assertEqual(x2, SubSpam)
1469 self.assertEqual(a2, a1)
1470 self.assertEqual(d2, d1)
1471 with self.assertRaises(TypeError):
1472 spam_cm()
1473 with self.assertRaises(TypeError):
1474 spam_cm(spam.spamlist())
1475 with self.assertRaises(TypeError):
1476 spam_cm(list)
1477
1478 def test_staticmethods(self):
1479 # Testing static methods...
1480 class C(object):
1481 def foo(*a): return a
1482 goo = staticmethod(foo)
1483 c = C()
1484 self.assertEqual(C.goo(1), (1,))
1485 self.assertEqual(c.goo(1), (1,))
1486 self.assertEqual(c.foo(1), (c, 1,))
1487 class D(C):
1488 pass
1489 d = D()
1490 self.assertEqual(D.goo(1), (1,))
1491 self.assertEqual(d.goo(1), (1,))
1492 self.assertEqual(d.foo(1), (d, 1))
1493 self.assertEqual(D.foo(d, 1), (d, 1))
1494
1495 @test_support.cpython_only
1496 def test_staticmethod_copy_pickle(self):
1497 sm = staticmethod(func)
1498 with test_support.check_py3k_warnings(
1499 (".*staticmethod", DeprecationWarning)):
1500 copy.copy(sm)
1501 with test_support.check_py3k_warnings(
1502 (".*staticmethod", DeprecationWarning)):
1503 copy.deepcopy(sm)
1504 for proto in range(2):
1505 self.assertRaises(TypeError, pickle.dumps, sm, proto)
1506 with test_support.check_py3k_warnings(
1507 (".*staticmethod", DeprecationWarning)):
1508 pickle.dumps(sm, 2)
1509
1510 @test_support.impl_detail("the module 'xxsubtype' is internal")
1511 def test_staticmethods_in_c(self):
1512 # Testing C-based static methods...
1513 import xxsubtype as spam
1514 a = (1, 2, 3)
1515 d = {"abc": 123}
1516 x, a1, d1 = spam.spamlist.staticmeth(*a, **d)
1517 self.assertEqual(x, None)
1518 self.assertEqual(a, a1)
1519 self.assertEqual(d, d1)
1520 x, a1, d2 = spam.spamlist().staticmeth(*a, **d)
1521 self.assertEqual(x, None)
1522 self.assertEqual(a, a1)
1523 self.assertEqual(d, d1)
1524
1525 def test_classic(self):
1526 # Testing classic classes...
1527 class C:
1528 def foo(*a): return a
1529 goo = classmethod(foo)
1530 c = C()
1531 self.assertEqual(C.goo(1), (C, 1))
1532 self.assertEqual(c.goo(1), (C, 1))
1533 self.assertEqual(c.foo(1), (c, 1))
1534 class D(C):
1535 pass
1536 d = D()
1537 self.assertEqual(D.goo(1), (D, 1))
1538 self.assertEqual(d.goo(1), (D, 1))
1539 self.assertEqual(d.foo(1), (d, 1))
1540 self.assertEqual(D.foo(d, 1), (d, 1))
1541 class E: # *not* subclassing from C
1542 foo = C.foo
1543 self.assertEqual(E().foo, C.foo) # i.e., unbound
1544 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
1545
1546 def test_compattr(self):
1547 # Testing computed attributes...
1548 class C(object):
1549 class computed_attribute(object):
1550 def __init__(self, get, set=None, delete=None):
1551 self.__get = get
1552 self.__set = set
1553 self.__delete = delete
1554 def __get__(self, obj, type=None):
1555 return self.__get(obj)
1556 def __set__(self, obj, value):
1557 return self.__set(obj, value)
1558 def __delete__(self, obj):
1559 return self.__delete(obj)
1560 def __init__(self):
1561 self.__x = 0
1562 def __get_x(self):
1563 x = self.__x
1564 self.__x = x+1
1565 return x
1566 def __set_x(self, x):
1567 self.__x = x
1568 def __delete_x(self):
1569 del self.__x
1570 x = computed_attribute(__get_x, __set_x, __delete_x)
1571 a = C()
1572 self.assertEqual(a.x, 0)
1573 self.assertEqual(a.x, 1)
1574 a.x = 10
1575 self.assertEqual(a.x, 10)
1576 self.assertEqual(a.x, 11)
1577 del a.x
1578 self.assertNotHasAttr(a, 'x')
1579
1580 def test_newslots(self):
1581 # Testing __new__ slot override...
1582 class C(list):
1583 def __new__(cls):
1584 self = list.__new__(cls)
1585 self.foo = 1
1586 return self
1587 def __init__(self):
1588 self.foo = self.foo + 2
1589 a = C()
1590 self.assertEqual(a.foo, 3)
1591 self.assertEqual(a.__class__, C)
1592 class D(C):
1593 pass
1594 b = D()
1595 self.assertEqual(b.foo, 3)
1596 self.assertEqual(b.__class__, D)
1597
1598 @unittest.expectedFailure
1599 def test_bad_new(self):
1600 self.assertRaises(TypeError, object.__new__)
1601 self.assertRaises(TypeError, object.__new__, '')
1602 self.assertRaises(TypeError, list.__new__, object)
1603 self.assertRaises(TypeError, object.__new__, list)
1604 class C(object):
1605 __new__ = list.__new__
1606 self.assertRaises(TypeError, C)
1607 class C(list):
1608 __new__ = object.__new__
1609 self.assertRaises(TypeError, C)
1610
1611 def test_object_new(self):
1612 class A(object):
1613 pass
1614 object.__new__(A)
1615 self.assertRaises(TypeError, object.__new__, A, 5)
1616 object.__init__(A())
1617 self.assertRaises(TypeError, object.__init__, A(), 5)
1618
1619 class A(object):
1620 def __init__(self, foo):
1621 self.foo = foo
1622 object.__new__(A)
1623 object.__new__(A, 5)
1624 object.__init__(A(3))
1625 self.assertRaises(TypeError, object.__init__, A(3), 5)
1626
1627 class A(object):
1628 def __new__(cls, foo):
1629 return object.__new__(cls)
1630 object.__new__(A)
1631 self.assertRaises(TypeError, object.__new__, A, 5)
1632 object.__init__(A(3))
1633 object.__init__(A(3), 5)
1634
1635 class A(object):
1636 def __new__(cls, foo):
1637 return object.__new__(cls)
1638 def __init__(self, foo):
1639 self.foo = foo
1640 object.__new__(A)
1641 with warnings.catch_warnings(record=True) as w:
1642 warnings.simplefilter('always', DeprecationWarning)
1643 a = object.__new__(A, 5)
1644 self.assertEqual(type(a), A)
1645 self.assertEqual(len(w), 1)
1646 object.__init__(A(3))
1647 a = A(3)
1648 with warnings.catch_warnings(record=True) as w:
1649 warnings.simplefilter('always', DeprecationWarning)
1650 object.__init__(a, 5)
1651 self.assertEqual(a.foo, 3)
1652 self.assertEqual(len(w), 1)
1653
1654 @unittest.expectedFailure
1655 def test_restored_object_new(self):
1656 class A(object):
1657 def __new__(cls, *args, **kwargs):
1658 raise AssertionError
1659 self.assertRaises(AssertionError, A)
1660 class B(A):
1661 __new__ = object.__new__
1662 def __init__(self, foo):
1663 self.foo = foo
1664 with warnings.catch_warnings():
1665 warnings.simplefilter('error', DeprecationWarning)
1666 b = B(3)
1667 self.assertEqual(b.foo, 3)
1668 self.assertEqual(b.__class__, B)
1669 del B.__new__
1670 self.assertRaises(AssertionError, B)
1671 del A.__new__
1672 with warnings.catch_warnings():
1673 warnings.simplefilter('error', DeprecationWarning)
1674 b = B(3)
1675 self.assertEqual(b.foo, 3)
1676 self.assertEqual(b.__class__, B)
1677
1678 def test_altmro(self):
1679 # Testing mro() and overriding it...
1680 class A(object):
1681 def f(self): return "A"
1682 class B(A):
1683 pass
1684 class C(A):
1685 def f(self): return "C"
1686 class D(B, C):
1687 pass
1688 self.assertEqual(D.mro(), [D, B, C, A, object])
1689 self.assertEqual(D.__mro__, (D, B, C, A, object))
1690 self.assertEqual(D().f(), "C")
1691
1692 class PerverseMetaType(type):
1693 def mro(cls):
1694 L = type.mro(cls)
1695 L.reverse()
1696 return L
1697 class X(D,B,C,A):
1698 __metaclass__ = PerverseMetaType
1699 self.assertEqual(X.__mro__, (object, A, C, B, D, X))
1700 self.assertEqual(X().f(), "A")
1701
1702 try:
1703 class X(object):
1704 class __metaclass__(type):
1705 def mro(self):
1706 return [self, dict, object]
1707 # In CPython, the class creation above already raises
1708 # TypeError, as a protection against the fact that
1709 # instances of X would segfault it. In other Python
1710 # implementations it would be ok to let the class X
1711 # be created, but instead get a clean TypeError on the
1712 # __setitem__ below.
1713 x = object.__new__(X)
1714 x[5] = 6
1715 except TypeError:
1716 pass
1717 else:
1718 self.fail("devious mro() return not caught")
1719
1720 try:
1721 class X(object):
1722 class __metaclass__(type):
1723 def mro(self):
1724 return [1]
1725 except TypeError:
1726 pass
1727 else:
1728 self.fail("non-class mro() return not caught")
1729
1730 try:
1731 class X(object):
1732 class __metaclass__(type):
1733 def mro(self):
1734 return 1
1735 except TypeError:
1736 pass
1737 else:
1738 self.fail("non-sequence mro() return not caught")
1739
1740 def test_overloading(self):
1741 # Testing operator overloading...
1742
1743 class B(object):
1744 "Intermediate class because object doesn't have a __setattr__"
1745
1746 class C(B):
1747 def __getattr__(self, name):
1748 if name == "foo":
1749 return ("getattr", name)
1750 else:
1751 raise AttributeError
1752 def __setattr__(self, name, value):
1753 if name == "foo":
1754 self.setattr = (name, value)
1755 else:
1756 return B.__setattr__(self, name, value)
1757 def __delattr__(self, name):
1758 if name == "foo":
1759 self.delattr = name
1760 else:
1761 return B.__delattr__(self, name)
1762
1763 def __getitem__(self, key):
1764 return ("getitem", key)
1765 def __setitem__(self, key, value):
1766 self.setitem = (key, value)
1767 def __delitem__(self, key):
1768 self.delitem = key
1769
1770 def __getslice__(self, i, j):
1771 return ("getslice", i, j)
1772 def __setslice__(self, i, j, value):
1773 self.setslice = (i, j, value)
1774 def __delslice__(self, i, j):
1775 self.delslice = (i, j)
1776
1777 a = C()
1778 self.assertEqual(a.foo, ("getattr", "foo"))
1779 a.foo = 12
1780 self.assertEqual(a.setattr, ("foo", 12))
1781 del a.foo
1782 self.assertEqual(a.delattr, "foo")
1783
1784 self.assertEqual(a[12], ("getitem", 12))
1785 a[12] = 21
1786 self.assertEqual(a.setitem, (12, 21))
1787 del a[12]
1788 self.assertEqual(a.delitem, 12)
1789
1790 self.assertEqual(a[0:10], ("getslice", 0, 10))
1791 a[0:10] = "foo"
1792 self.assertEqual(a.setslice, (0, 10, "foo"))
1793 del a[0:10]
1794 self.assertEqual(a.delslice, (0, 10))
1795
1796 def test_methods(self):
1797 # Testing methods...
1798 class C(object):
1799 def __init__(self, x):
1800 self.x = x
1801 def foo(self):
1802 return self.x
1803 c1 = C(1)
1804 self.assertEqual(c1.foo(), 1)
1805 class D(C):
1806 boo = C.foo
1807 goo = c1.foo
1808 d2 = D(2)
1809 self.assertEqual(d2.foo(), 2)
1810 self.assertEqual(d2.boo(), 2)
1811 self.assertEqual(d2.goo(), 1)
1812 class E(object):
1813 foo = C.foo
1814 self.assertEqual(E().foo, C.foo) # i.e., unbound
1815 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
1816
1817 def test_special_method_lookup(self):
1818 # The lookup of special methods bypasses __getattr__ and
1819 # __getattribute__, but they still can be descriptors.
1820
1821 def run_context(manager):
1822 with manager:
1823 pass
1824 def iden(self):
1825 return self
1826 def hello(self):
1827 return "hello"
1828 def empty_seq(self):
1829 return []
1830 def zero(self):
1831 return 0
1832 def complex_num(self):
1833 return 1j
1834 def stop(self):
1835 raise StopIteration
1836 def return_true(self, thing=None):
1837 return True
1838 def do_isinstance(obj):
1839 return isinstance(int, obj)
1840 def do_issubclass(obj):
1841 return issubclass(int, obj)
1842 def swallow(*args):
1843 pass
1844 def do_dict_missing(checker):
1845 class DictSub(checker.__class__, dict):
1846 pass
1847 self.assertEqual(DictSub()["hi"], 4)
1848 def some_number(self_, key):
1849 self.assertEqual(key, "hi")
1850 return 4
1851 def format_impl(self, spec):
1852 return "hello"
1853
1854 # It would be nice to have every special method tested here, but I'm
1855 # only listing the ones I can remember outside of typeobject.c, since it
1856 # does it right.
1857 specials = [
1858 ("__unicode__", unicode, hello, set(), {}),
1859 ("__reversed__", reversed, empty_seq, set(), {}),
1860 ("__length_hint__", list, zero, set(),
1861 {"__iter__" : iden, "next" : stop}),
1862 ("__sizeof__", sys.getsizeof, zero, set(), {}),
1863 ("__instancecheck__", do_isinstance, return_true, set(), {}),
1864 ("__missing__", do_dict_missing, some_number,
1865 set(("__class__",)), {}),
1866 ("__subclasscheck__", do_issubclass, return_true,
1867 set(("__bases__",)), {}),
1868 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}),
1869 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}),
1870 ("__complex__", complex, complex_num, set(), {}),
1871 ("__format__", format, format_impl, set(), {}),
1872 ("__dir__", dir, empty_seq, set(), {}),
1873 ]
1874
1875 class Checker(object):
1876 def __getattr__(self, attr, test=self):
1877 test.fail("__getattr__ called with {0}".format(attr))
1878 def __getattribute__(self, attr, test=self):
1879 if attr not in ok:
1880 test.fail("__getattribute__ called with {0}".format(attr))
1881 return object.__getattribute__(self, attr)
1882 class SpecialDescr(object):
1883 def __init__(self, impl):
1884 self.impl = impl
1885 def __get__(self, obj, owner):
1886 record.append(1)
1887 return self.impl.__get__(obj, owner)
1888 class MyException(Exception):
1889 pass
1890 class ErrDescr(object):
1891 def __get__(self, obj, owner):
1892 raise MyException
1893
1894 for name, runner, meth_impl, ok, env in specials:
1895 class X(Checker):
1896 pass
1897 for attr, obj in env.iteritems():
1898 setattr(X, attr, obj)
1899 setattr(X, name, meth_impl)
1900 runner(X())
1901
1902 record = []
1903 class X(Checker):
1904 pass
1905 for attr, obj in env.iteritems():
1906 setattr(X, attr, obj)
1907 setattr(X, name, SpecialDescr(meth_impl))
1908 runner(X())
1909 self.assertEqual(record, [1], name)
1910
1911 class X(Checker):
1912 pass
1913 for attr, obj in env.iteritems():
1914 setattr(X, attr, obj)
1915 setattr(X, name, ErrDescr())
1916 try:
1917 runner(X())
1918 except MyException:
1919 pass
1920 else:
1921 self.fail("{0!r} didn't raise".format(name))
1922
1923 def test_specials(self):
1924 # Testing special operators...
1925 # Test operators like __hash__ for which a built-in default exists
1926
1927 # Test the default behavior for static classes
1928 class C(object):
1929 def __getitem__(self, i):
1930 if 0 <= i < 10: return i
1931 raise IndexError
1932 c1 = C()
1933 c2 = C()
1934 self.assertFalse(not c1)
1935 self.assertNotEqual(id(c1), id(c2))
1936 hash(c1)
1937 hash(c2)
1938 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
1939 self.assertEqual(c1, c1)
1940 self.assertTrue(c1 != c2)
1941 self.assertFalse(c1 != c1)
1942 self.assertFalse(c1 == c2)
1943 # Note that the module name appears in str/repr, and that varies
1944 # depending on whether this test is run standalone or from a framework.
1945 self.assertGreaterEqual(str(c1).find('C object at '), 0)
1946 self.assertEqual(str(c1), repr(c1))
1947 self.assertNotIn(-1, c1)
1948 for i in range(10):
1949 self.assertIn(i, c1)
1950 self.assertNotIn(10, c1)
1951 # Test the default behavior for dynamic classes
1952 class D(object):
1953 def __getitem__(self, i):
1954 if 0 <= i < 10: return i
1955 raise IndexError
1956 d1 = D()
1957 d2 = D()
1958 self.assertFalse(not d1)
1959 self.assertNotEqual(id(d1), id(d2))
1960 hash(d1)
1961 hash(d2)
1962 self.assertEqual(cmp(d1, d2), cmp(id(d1), id(d2)))
1963 self.assertEqual(d1, d1)
1964 self.assertNotEqual(d1, d2)
1965 self.assertFalse(d1 != d1)
1966 self.assertFalse(d1 == d2)
1967 # Note that the module name appears in str/repr, and that varies
1968 # depending on whether this test is run standalone or from a framework.
1969 self.assertGreaterEqual(str(d1).find('D object at '), 0)
1970 self.assertEqual(str(d1), repr(d1))
1971 self.assertNotIn(-1, d1)
1972 for i in range(10):
1973 self.assertIn(i, d1)
1974 self.assertNotIn(10, d1)
1975 # Test overridden behavior for static classes
1976 class Proxy(object):
1977 def __init__(self, x):
1978 self.x = x
1979 def __nonzero__(self):
1980 return not not self.x
1981 def __hash__(self):
1982 return hash(self.x)
1983 def __eq__(self, other):
1984 return self.x == other
1985 def __ne__(self, other):
1986 return self.x != other
1987 def __cmp__(self, other):
1988 return cmp(self.x, other.x)
1989 def __str__(self):
1990 return "Proxy:%s" % self.x
1991 def __repr__(self):
1992 return "Proxy(%r)" % self.x
1993 def __contains__(self, value):
1994 return value in self.x
1995 p0 = Proxy(0)
1996 p1 = Proxy(1)
1997 p_1 = Proxy(-1)
1998 self.assertFalse(p0)
1999 self.assertFalse(not p1)
2000 self.assertEqual(hash(p0), hash(0))
2001 self.assertEqual(p0, p0)
2002 self.assertNotEqual(p0, p1)
2003 self.assertFalse(p0 != p0)
2004 self.assertEqual(not p0, p1)
2005 self.assertEqual(cmp(p0, p1), -1)
2006 self.assertEqual(cmp(p0, p0), 0)
2007 self.assertEqual(cmp(p0, p_1), 1)
2008 self.assertEqual(str(p0), "Proxy:0")
2009 self.assertEqual(repr(p0), "Proxy(0)")
2010 p10 = Proxy(range(10))
2011 self.assertNotIn(-1, p10)
2012 for i in range(10):
2013 self.assertIn(i, p10)
2014 self.assertNotIn(10, p10)
2015 # Test overridden behavior for dynamic classes
2016 class DProxy(object):
2017 def __init__(self, x):
2018 self.x = x
2019 def __nonzero__(self):
2020 return not not self.x
2021 def __hash__(self):
2022 return hash(self.x)
2023 def __eq__(self, other):
2024 return self.x == other
2025 def __ne__(self, other):
2026 return self.x != other
2027 def __cmp__(self, other):
2028 return cmp(self.x, other.x)
2029 def __str__(self):
2030 return "DProxy:%s" % self.x
2031 def __repr__(self):
2032 return "DProxy(%r)" % self.x
2033 def __contains__(self, value):
2034 return value in self.x
2035 p0 = DProxy(0)
2036 p1 = DProxy(1)
2037 p_1 = DProxy(-1)
2038 self.assertFalse(p0)
2039 self.assertFalse(not p1)
2040 self.assertEqual(hash(p0), hash(0))
2041 self.assertEqual(p0, p0)
2042 self.assertNotEqual(p0, p1)
2043 self.assertNotEqual(not p0, p0)
2044 self.assertEqual(not p0, p1)
2045 self.assertEqual(cmp(p0, p1), -1)
2046 self.assertEqual(cmp(p0, p0), 0)
2047 self.assertEqual(cmp(p0, p_1), 1)
2048 self.assertEqual(str(p0), "DProxy:0")
2049 self.assertEqual(repr(p0), "DProxy(0)")
2050 p10 = DProxy(range(10))
2051 self.assertNotIn(-1, p10)
2052 for i in range(10):
2053 self.assertIn(i, p10)
2054 self.assertNotIn(10, p10)
2055
2056 # Safety test for __cmp__
2057 def unsafecmp(a, b):
2058 if not hasattr(a, '__cmp__'):
2059 return # some types don't have a __cmp__ any more (so the
2060 # test doesn't make sense any more), or maybe they
2061 # never had a __cmp__ at all, e.g. in PyPy
2062 try:
2063 a.__class__.__cmp__(a, b)
2064 except TypeError:
2065 pass
2066 else:
2067 self.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
2068 a.__class__, a, b))
2069
2070 unsafecmp(u"123", "123")
2071 unsafecmp("123", u"123")
2072 unsafecmp(1, 1.0)
2073 unsafecmp(1.0, 1)
2074 unsafecmp(1, 1L)
2075 unsafecmp(1L, 1)
2076
2077 @test_support.impl_detail("custom logic for printing to real file objects")
2078 def test_recursions_1(self):
2079 # Testing recursion checks ...
2080 class Letter(str):
2081 def __new__(cls, letter):
2082 if letter == 'EPS':
2083 return str.__new__(cls)
2084 return str.__new__(cls, letter)
2085 def __str__(self):
2086 if not self:
2087 return 'EPS'
2088 return self
2089 # sys.stdout needs to be the original to trigger the recursion bug
2090 test_stdout = sys.stdout
2091 sys.stdout = test_support.get_original_stdout()
2092 try:
2093 # nothing should actually be printed, this should raise an exception
2094 print Letter('w')
2095 except RuntimeError:
2096 pass
2097 else:
2098 self.fail("expected a RuntimeError for print recursion")
2099 finally:
2100 sys.stdout = test_stdout
2101
2102 def test_recursions_2(self):
2103 # Bug #1202533.
2104 class A(object):
2105 pass
2106 A.__mul__ = types.MethodType(lambda self, x: self * x, None, A)
2107 try:
2108 A()*2
2109 except RuntimeError:
2110 pass
2111 else:
2112 self.fail("expected a RuntimeError")
2113
2114 def test_weakrefs(self):
2115 # Testing weak references...
2116 import weakref
2117 class C(object):
2118 pass
2119 c = C()
2120 r = weakref.ref(c)
2121 self.assertEqual(r(), c)
2122 del c
2123 test_support.gc_collect()
2124 self.assertEqual(r(), None)
2125 del r
2126 class NoWeak(object):
2127 __slots__ = ['foo']
2128 no = NoWeak()
2129 try:
2130 weakref.ref(no)
2131 except TypeError, msg:
2132 self.assertIn("weak reference", str(msg))
2133 else:
2134 self.fail("weakref.ref(no) should be illegal")
2135 class Weak(object):
2136 __slots__ = ['foo', '__weakref__']
2137 yes = Weak()
2138 r = weakref.ref(yes)
2139 self.assertEqual(r(), yes)
2140 del yes
2141 test_support.gc_collect()
2142 self.assertEqual(r(), None)
2143 del r
2144
2145 def test_properties(self):
2146 # Testing property...
2147 class C(object):
2148 def getx(self):
2149 return self.__x
2150 def setx(self, value):
2151 self.__x = value
2152 def delx(self):
2153 del self.__x
2154 x = property(getx, setx, delx, doc="I'm the x property.")
2155 a = C()
2156 self.assertNotHasAttr(a, "x")
2157 a.x = 42
2158 self.assertEqual(a._C__x, 42)
2159 self.assertEqual(a.x, 42)
2160 del a.x
2161 self.assertNotHasAttr(a, "x")
2162 self.assertNotHasAttr(a, "_C__x")
2163 C.x.__set__(a, 100)
2164 self.assertEqual(C.x.__get__(a), 100)
2165 C.x.__delete__(a)
2166 self.assertNotHasAttr(a, "x")
2167
2168 raw = C.__dict__['x']
2169 self.assertIsInstance(raw, property)
2170
2171 attrs = dir(raw)
2172 self.assertIn("__doc__", attrs)
2173 self.assertIn("fget", attrs)
2174 self.assertIn("fset", attrs)
2175 self.assertIn("fdel", attrs)
2176
2177 self.assertEqual(raw.__doc__, "I'm the x property.")
2178 self.assertIs(raw.fget, C.__dict__['getx'])
2179 self.assertIs(raw.fset, C.__dict__['setx'])
2180 self.assertIs(raw.fdel, C.__dict__['delx'])
2181
2182 for attr in "__doc__", "fget", "fset", "fdel":
2183 try:
2184 setattr(raw, attr, 42)
2185 except TypeError, msg:
2186 if str(msg).find('readonly') < 0:
2187 self.fail("when setting readonly attr %r on a property, "
2188 "got unexpected TypeError msg %r" % (attr, str(msg)))
2189 else:
2190 self.fail("expected TypeError from trying to set readonly %r "
2191 "attr on a property" % attr)
2192
2193 class D(object):
2194 __getitem__ = property(lambda s: 1.0/0.0)
2195
2196 d = D()
2197 try:
2198 for i in d:
2199 str(i)
2200 except ZeroDivisionError:
2201 pass
2202 else:
2203 self.fail("expected ZeroDivisionError from bad property")
2204
2205 @test_support.cpython_only
2206 def test_property_copy_pickle(self):
2207 p = property(func)
2208 with test_support.check_py3k_warnings(
2209 (".*property", DeprecationWarning)):
2210 copy.copy(p)
2211 with test_support.check_py3k_warnings(
2212 (".*property", DeprecationWarning)):
2213 copy.deepcopy(p)
2214 for proto in range(2):
2215 self.assertRaises(TypeError, pickle.dumps, p, proto)
2216 with test_support.check_py3k_warnings(
2217 (".*property", DeprecationWarning)):
2218 pickle.dumps(p, 2)
2219
2220 @unittest.skipIf(sys.flags.optimize >= 2,
2221 "Docstrings are omitted with -O2 and above")
2222 def test_properties_doc_attrib(self):
2223 class E(object):
2224 def getter(self):
2225 "getter method"
2226 return 0
2227 def setter(self_, value):
2228 "setter method"
2229 pass
2230 prop = property(getter)
2231 self.assertEqual(prop.__doc__, "getter method")
2232 prop2 = property(fset=setter)
2233 self.assertEqual(prop2.__doc__, None)
2234
2235 @test_support.cpython_only
2236 def test_testcapi_no_segfault(self):
2237 # this segfaulted in 2.5b2
2238 try:
2239 import _testcapi
2240 except ImportError:
2241 pass
2242 else:
2243 class X(object):
2244 p = property(_testcapi.test_with_docstring)
2245
2246 def test_properties_plus(self):
2247 class C(object):
2248 foo = property(doc="hello")
2249 @foo.getter
2250 def foo(self):
2251 return self._foo
2252 @foo.setter
2253 def foo(self, value):
2254 self._foo = abs(value)
2255 @foo.deleter
2256 def foo(self):
2257 del self._foo
2258 c = C()
2259 self.assertEqual(C.foo.__doc__, "hello")
2260 self.assertNotHasAttr(c, "foo")
2261 c.foo = -42
2262 self.assertHasAttr(c, '_foo')
2263 self.assertEqual(c._foo, 42)
2264 self.assertEqual(c.foo, 42)
2265 del c.foo
2266 self.assertNotHasAttr(c, '_foo')
2267 self.assertNotHasAttr(c, "foo")
2268
2269 class D(C):
2270 @C.foo.deleter
2271 def foo(self):
2272 try:
2273 del self._foo
2274 except AttributeError:
2275 pass
2276 d = D()
2277 d.foo = 24
2278 self.assertEqual(d.foo, 24)
2279 del d.foo
2280 del d.foo
2281
2282 class E(object):
2283 @property
2284 def foo(self):
2285 return self._foo
2286 @foo.setter
2287 def foo(self, value):
2288 raise RuntimeError
2289 @foo.setter
2290 def foo(self, value):
2291 self._foo = abs(value)
2292 @foo.deleter
2293 def foo(self, value=None):
2294 del self._foo
2295
2296 e = E()
2297 e.foo = -42
2298 self.assertEqual(e.foo, 42)
2299 del e.foo
2300
2301 class F(E):
2302 @E.foo.deleter
2303 def foo(self):
2304 del self._foo
2305 @foo.setter
2306 def foo(self, value):
2307 self._foo = max(0, value)
2308 f = F()
2309 f.foo = -10
2310 self.assertEqual(f.foo, 0)
2311 del f.foo
2312
2313 def test_dict_constructors(self):
2314 # Testing dict constructor ...
2315 d = dict()
2316 self.assertEqual(d, {})
2317 d = dict({})
2318 self.assertEqual(d, {})
2319 d = dict({1: 2, 'a': 'b'})
2320 self.assertEqual(d, {1: 2, 'a': 'b'})
2321 self.assertEqual(d, dict(d.items()))
2322 self.assertEqual(d, dict(d.iteritems()))
2323 d = dict({'one':1, 'two':2})
2324 self.assertEqual(d, dict(one=1, two=2))
2325 self.assertEqual(d, dict(**d))
2326 self.assertEqual(d, dict({"one": 1}, two=2))
2327 self.assertEqual(d, dict([("two", 2)], one=1))
2328 self.assertEqual(d, dict([("one", 100), ("two", 200)], **d))
2329 self.assertEqual(d, dict(**d))
2330
2331 for badarg in 0, 0L, 0j, "0", [0], (0,):
2332 try:
2333 dict(badarg)
2334 except TypeError:
2335 pass
2336 except ValueError:
2337 if badarg == "0":
2338 # It's a sequence, and its elements are also sequences (gotta
2339 # love strings <wink>), but they aren't of length 2, so this
2340 # one seemed better as a ValueError than a TypeError.
2341 pass
2342 else:
2343 self.fail("no TypeError from dict(%r)" % badarg)
2344 else:
2345 self.fail("no TypeError from dict(%r)" % badarg)
2346
2347 try:
2348 dict({}, {})
2349 except TypeError:
2350 pass
2351 else:
2352 self.fail("no TypeError from dict({}, {})")
2353
2354 class Mapping:
2355 # Lacks a .keys() method; will be added later.
2356 dict = {1:2, 3:4, 'a':1j}
2357
2358 try:
2359 dict(Mapping())
2360 except TypeError:
2361 pass
2362 else:
2363 self.fail("no TypeError from dict(incomplete mapping)")
2364
2365 Mapping.keys = lambda self: self.dict.keys()
2366 Mapping.__getitem__ = lambda self, i: self.dict[i]
2367 d = dict(Mapping())
2368 self.assertEqual(d, Mapping.dict)
2369
2370 # Init from sequence of iterable objects, each producing a 2-sequence.
2371 class AddressBookEntry:
2372 def __init__(self, first, last):
2373 self.first = first
2374 self.last = last
2375 def __iter__(self):
2376 return iter([self.first, self.last])
2377
2378 d = dict([AddressBookEntry('Tim', 'Warsaw'),
2379 AddressBookEntry('Barry', 'Peters'),
2380 AddressBookEntry('Tim', 'Peters'),
2381 AddressBookEntry('Barry', 'Warsaw')])
2382 self.assertEqual(d, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2383
2384 d = dict(zip(range(4), range(1, 5)))
2385 self.assertEqual(d, dict([(i, i+1) for i in range(4)]))
2386
2387 # Bad sequence lengths.
2388 for bad in [('tooshort',)], [('too', 'long', 'by 1')]:
2389 try:
2390 dict(bad)
2391 except ValueError:
2392 pass
2393 else:
2394 self.fail("no ValueError from dict(%r)" % bad)
2395
2396 def test_dir(self):
2397 # Testing dir() ...
2398 junk = 12
2399 self.assertEqual(dir(), ['junk', 'self'])
2400 del junk
2401
2402 # Just make sure these don't blow up!
2403 for arg in 2, 2L, 2j, 2e0, [2], "2", u"2", (2,), {2:2}, type, self.test_dir:
2404 dir(arg)
2405
2406 # Try classic classes.
2407 class C:
2408 Cdata = 1
2409 def Cmethod(self): pass
2410
2411 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
2412 self.assertEqual(dir(C), cstuff)
2413 self.assertIn('im_self', dir(C.Cmethod))
2414
2415 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2416 self.assertEqual(dir(c), cstuff)
2417
2418 c.cdata = 2
2419 c.cmethod = lambda self: 0
2420 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
2421 self.assertIn('im_self', dir(c.Cmethod))
2422
2423 class A(C):
2424 Adata = 1
2425 def Amethod(self): pass
2426
2427 astuff = ['Adata', 'Amethod'] + cstuff
2428 self.assertEqual(dir(A), astuff)
2429 self.assertIn('im_self', dir(A.Amethod))
2430 a = A()
2431 self.assertEqual(dir(a), astuff)
2432 self.assertIn('im_self', dir(a.Amethod))
2433 a.adata = 42
2434 a.amethod = lambda self: 3
2435 self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
2436
2437 # The same, but with new-style classes. Since these have object as a
2438 # base class, a lot more gets sucked in.
2439 def interesting(strings):
2440 return [s for s in strings if not s.startswith('_')]
2441
2442 class C(object):
2443 Cdata = 1
2444 def Cmethod(self): pass
2445
2446 cstuff = ['Cdata', 'Cmethod']
2447 self.assertEqual(interesting(dir(C)), cstuff)
2448
2449 c = C()
2450 self.assertEqual(interesting(dir(c)), cstuff)
2451 self.assertIn('im_self', dir(C.Cmethod))
2452
2453 c.cdata = 2
2454 c.cmethod = lambda self: 0
2455 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
2456 self.assertIn('im_self', dir(c.Cmethod))
2457
2458 class A(C):
2459 Adata = 1
2460 def Amethod(self): pass
2461
2462 astuff = ['Adata', 'Amethod'] + cstuff
2463 self.assertEqual(interesting(dir(A)), astuff)
2464 self.assertIn('im_self', dir(A.Amethod))
2465 a = A()
2466 self.assertEqual(interesting(dir(a)), astuff)
2467 a.adata = 42
2468 a.amethod = lambda self: 3
2469 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
2470 self.assertIn('im_self', dir(a.Amethod))
2471
2472 # Try a module subclass.
2473 class M(type(sys)):
2474 pass
2475 minstance = M("m")
2476 minstance.b = 2
2477 minstance.a = 1
2478 names = [x for x in dir(minstance) if x not in ["__name__", "__doc__"]]
2479 self.assertEqual(names, ['a', 'b'])
2480
2481 class M2(M):
2482 def getdict(self):
2483 return "Not a dict!"
2484 __dict__ = property(getdict)
2485
2486 m2instance = M2("m2")
2487 m2instance.b = 2
2488 m2instance.a = 1
2489 self.assertEqual(m2instance.__dict__, "Not a dict!")
2490 try:
2491 dir(m2instance)
2492 except TypeError:
2493 pass
2494
2495 # Two essentially featureless objects, just inheriting stuff from
2496 # object.
2497 self.assertEqual(dir(NotImplemented), dir(Ellipsis))
2498 if test_support.check_impl_detail():
2499 # None differs in PyPy: it has a __nonzero__
2500 self.assertEqual(dir(None), dir(Ellipsis))
2501
2502 # Nasty test case for proxied objects
2503 class Wrapper(object):
2504 def __init__(self, obj):
2505 self.__obj = obj
2506 def __repr__(self):
2507 return "Wrapper(%s)" % repr(self.__obj)
2508 def __getitem__(self, key):
2509 return Wrapper(self.__obj[key])
2510 def __len__(self):
2511 return len(self.__obj)
2512 def __getattr__(self, name):
2513 return Wrapper(getattr(self.__obj, name))
2514
2515 class C(object):
2516 def __getclass(self):
2517 return Wrapper(type(self))
2518 __class__ = property(__getclass)
2519
2520 dir(C()) # This used to segfault
2521
2522 def test_supers(self):
2523 # Testing super...
2524
2525 class A(object):
2526 def meth(self, a):
2527 return "A(%r)" % a
2528
2529 self.assertEqual(A().meth(1), "A(1)")
2530
2531 class B(A):
2532 def __init__(self):
2533 self.__super = super(B, self)
2534 def meth(self, a):
2535 return "B(%r)" % a + self.__super.meth(a)
2536
2537 self.assertEqual(B().meth(2), "B(2)A(2)")
2538
2539 class C(A):
2540 def meth(self, a):
2541 return "C(%r)" % a + self.__super.meth(a)
2542 C._C__super = super(C)
2543
2544 self.assertEqual(C().meth(3), "C(3)A(3)")
2545
2546 class D(C, B):
2547 def meth(self, a):
2548 return "D(%r)" % a + super(D, self).meth(a)
2549
2550 self.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2551
2552 # Test for subclassing super
2553
2554 class mysuper(super):
2555 def __init__(self, *args):
2556 return super(mysuper, self).__init__(*args)
2557
2558 class E(D):
2559 def meth(self, a):
2560 return "E(%r)" % a + mysuper(E, self).meth(a)
2561
2562 self.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2563
2564 class F(E):
2565 def meth(self, a):
2566 s = self.__super # == mysuper(F, self)
2567 return "F(%r)[%s]" % (a, s.__class__.__name__) + s.meth(a)
2568 F._F__super = mysuper(F)
2569
2570 self.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2571
2572 # Make sure certain errors are raised
2573
2574 try:
2575 super(D, 42)
2576 except TypeError:
2577 pass
2578 else:
2579 self.fail("shouldn't allow super(D, 42)")
2580
2581 try:
2582 super(D, C())
2583 except TypeError:
2584 pass
2585 else:
2586 self.fail("shouldn't allow super(D, C())")
2587
2588 try:
2589 super(D).__get__(12)
2590 except TypeError:
2591 pass
2592 else:
2593 self.fail("shouldn't allow super(D).__get__(12)")
2594
2595 try:
2596 super(D).__get__(C())
2597 except TypeError:
2598 pass
2599 else:
2600 self.fail("shouldn't allow super(D).__get__(C())")
2601
2602 # Make sure data descriptors can be overridden and accessed via super
2603 # (new feature in Python 2.3)
2604
2605 class DDbase(object):
2606 def getx(self): return 42
2607 x = property(getx)
2608
2609 class DDsub(DDbase):
2610 def getx(self): return "hello"
2611 x = property(getx)
2612
2613 dd = DDsub()
2614 self.assertEqual(dd.x, "hello")
2615 self.assertEqual(super(DDsub, dd).x, 42)
2616
2617 # Ensure that super() lookup of descriptor from classmethod
2618 # works (SF ID# 743627)
2619
2620 class Base(object):
2621 aProp = property(lambda self: "foo")
2622
2623 class Sub(Base):
2624 @classmethod
2625 def test(klass):
2626 return super(Sub,klass).aProp
2627
2628 self.assertEqual(Sub.test(), Base.aProp)
2629
2630 # Verify that super() doesn't allow keyword args
2631 try:
2632 super(Base, kw=1)
2633 except TypeError:
2634 pass
2635 else:
2636 self.assertEqual("super shouldn't accept keyword args")
2637
2638 def test_basic_inheritance(self):
2639 # Testing inheritance from basic types...
2640
2641 class hexint(int):
2642 def __repr__(self):
2643 return hex(self)
2644 def __add__(self, other):
2645 return hexint(int.__add__(self, other))
2646 # (Note that overriding __radd__ doesn't work,
2647 # because the int type gets first dibs.)
2648 self.assertEqual(repr(hexint(7) + 9), "0x10")
2649 self.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2650 a = hexint(12345)
2651 self.assertEqual(a, 12345)
2652 self.assertEqual(int(a), 12345)
2653 self.assertIs(int(a).__class__, int)
2654 self.assertEqual(hash(a), hash(12345))
2655 self.assertIs((+a).__class__, int)
2656 self.assertIs((a >> 0).__class__, int)
2657 self.assertIs((a << 0).__class__, int)
2658 self.assertIs((hexint(0) << 12).__class__, int)
2659 self.assertIs((hexint(0) >> 12).__class__, int)
2660
2661 class octlong(long):
2662 __slots__ = []
2663 def __str__(self):
2664 s = oct(self)
2665 if s[-1] == 'L':
2666 s = s[:-1]
2667 return s
2668 def __add__(self, other):
2669 return self.__class__(super(octlong, self).__add__(other))
2670 __radd__ = __add__
2671 self.assertEqual(str(octlong(3) + 5), "010")
2672 # (Note that overriding __radd__ here only seems to work
2673 # because the example uses a short int left argument.)
2674 self.assertEqual(str(5 + octlong(3000)), "05675")
2675 a = octlong(12345)
2676 self.assertEqual(a, 12345L)
2677 self.assertEqual(long(a), 12345L)
2678 self.assertEqual(hash(a), hash(12345L))
2679 self.assertIs(long(a).__class__, long)
2680 self.assertIs((+a).__class__, long)
2681 self.assertIs((-a).__class__, long)
2682 self.assertIs((-octlong(0)).__class__, long)
2683 self.assertIs((a >> 0).__class__, long)
2684 self.assertIs((a << 0).__class__, long)
2685 self.assertIs((a - 0).__class__, long)
2686 self.assertIs((a * 1).__class__, long)
2687 self.assertIs((a ** 1).__class__, long)
2688 self.assertIs((a // 1).__class__, long)
2689 self.assertIs((1 * a).__class__, long)
2690 self.assertIs((a | 0).__class__, long)
2691 self.assertIs((a ^ 0).__class__, long)
2692 self.assertIs((a & -1L).__class__, long)
2693 self.assertIs((octlong(0) << 12).__class__, long)
2694 self.assertIs((octlong(0) >> 12).__class__, long)
2695 self.assertIs(abs(octlong(0)).__class__, long)
2696
2697 # Because octlong overrides __add__, we can't check the absence of +0
2698 # optimizations using octlong.
2699 class longclone(long):
2700 pass
2701 a = longclone(1)
2702 self.assertIs((a + 0).__class__, long)
2703 self.assertIs((0 + a).__class__, long)
2704
2705 # Check that negative clones don't segfault
2706 a = longclone(-1)
2707 self.assertEqual(a.__dict__, {})
2708 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
2709
2710 class precfloat(float):
2711 __slots__ = ['prec']
2712 def __init__(self, value=0.0, prec=12):
2713 self.prec = int(prec)
2714 def __repr__(self):
2715 return "%.*g" % (self.prec, self)
2716 self.assertEqual(repr(precfloat(1.1)), "1.1")
2717 a = precfloat(12345)
2718 self.assertEqual(a, 12345.0)
2719 self.assertEqual(float(a), 12345.0)
2720 self.assertIs(float(a).__class__, float)
2721 self.assertEqual(hash(a), hash(12345.0))
2722 self.assertIs((+a).__class__, float)
2723
2724 class madcomplex(complex):
2725 def __repr__(self):
2726 return "%.17gj%+.17g" % (self.imag, self.real)
2727 a = madcomplex(-3, 4)
2728 self.assertEqual(repr(a), "4j-3")
2729 base = complex(-3, 4)
2730 self.assertEqual(base.__class__, complex)
2731 self.assertEqual(a, base)
2732 self.assertEqual(complex(a), base)
2733 self.assertEqual(complex(a).__class__, complex)
2734 a = madcomplex(a) # just trying another form of the constructor
2735 self.assertEqual(repr(a), "4j-3")
2736 self.assertEqual(a, base)
2737 self.assertEqual(complex(a), base)
2738 self.assertEqual(complex(a).__class__, complex)
2739 self.assertEqual(hash(a), hash(base))
2740 self.assertEqual((+a).__class__, complex)
2741 self.assertEqual((a + 0).__class__, complex)
2742 self.assertEqual(a + 0, base)
2743 self.assertEqual((a - 0).__class__, complex)
2744 self.assertEqual(a - 0, base)
2745 self.assertEqual((a * 1).__class__, complex)
2746 self.assertEqual(a * 1, base)
2747 self.assertEqual((a / 1).__class__, complex)
2748 self.assertEqual(a / 1, base)
2749
2750 class madtuple(tuple):
2751 _rev = None
2752 def rev(self):
2753 if self._rev is not None:
2754 return self._rev
2755 L = list(self)
2756 L.reverse()
2757 self._rev = self.__class__(L)
2758 return self._rev
2759 a = madtuple((1,2,3,4,5,6,7,8,9,0))
2760 self.assertEqual(a, (1,2,3,4,5,6,7,8,9,0))
2761 self.assertEqual(a.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2762 self.assertEqual(a.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2763 for i in range(512):
2764 t = madtuple(range(i))
2765 u = t.rev()
2766 v = u.rev()
2767 self.assertEqual(v, t)
2768 a = madtuple((1,2,3,4,5))
2769 self.assertEqual(tuple(a), (1,2,3,4,5))
2770 self.assertIs(tuple(a).__class__, tuple)
2771 self.assertEqual(hash(a), hash((1,2,3,4,5)))
2772 self.assertIs(a[:].__class__, tuple)
2773 self.assertIs((a * 1).__class__, tuple)
2774 self.assertIs((a * 0).__class__, tuple)
2775 self.assertIs((a + ()).__class__, tuple)
2776 a = madtuple(())
2777 self.assertEqual(tuple(a), ())
2778 self.assertIs(tuple(a).__class__, tuple)
2779 self.assertIs((a + a).__class__, tuple)
2780 self.assertIs((a * 0).__class__, tuple)
2781 self.assertIs((a * 1).__class__, tuple)
2782 self.assertIs((a * 2).__class__, tuple)
2783 self.assertIs(a[:].__class__, tuple)
2784
2785 class madstring(str):
2786 _rev = None
2787 def rev(self):
2788 if self._rev is not None:
2789 return self._rev
2790 L = list(self)
2791 L.reverse()
2792 self._rev = self.__class__("".join(L))
2793 return self._rev
2794 s = madstring("abcdefghijklmnopqrstuvwxyz")
2795 self.assertEqual(s, "abcdefghijklmnopqrstuvwxyz")
2796 self.assertEqual(s.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2797 self.assertEqual(s.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2798 for i in range(256):
2799 s = madstring("".join(map(chr, range(i))))
2800 t = s.rev()
2801 u = t.rev()
2802 self.assertEqual(u, s)
2803 s = madstring("12345")
2804 self.assertEqual(str(s), "12345")
2805 self.assertIs(str(s).__class__, str)
2806
2807 base = "\x00" * 5
2808 s = madstring(base)
2809 self.assertEqual(s, base)
2810 self.assertEqual(str(s), base)
2811 self.assertIs(str(s).__class__, str)
2812 self.assertEqual(hash(s), hash(base))
2813 self.assertEqual({s: 1}[base], 1)
2814 self.assertEqual({base: 1}[s], 1)
2815 self.assertIs((s + "").__class__, str)
2816 self.assertEqual(s + "", base)
2817 self.assertIs(("" + s).__class__, str)
2818 self.assertEqual("" + s, base)
2819 self.assertIs((s * 0).__class__, str)
2820 self.assertEqual(s * 0, "")
2821 self.assertIs((s * 1).__class__, str)
2822 self.assertEqual(s * 1, base)
2823 self.assertIs((s * 2).__class__, str)
2824 self.assertEqual(s * 2, base + base)
2825 self.assertIs(s[:].__class__, str)
2826 self.assertEqual(s[:], base)
2827 self.assertIs(s[0:0].__class__, str)
2828 self.assertEqual(s[0:0], "")
2829 self.assertIs(s.strip().__class__, str)
2830 self.assertEqual(s.strip(), base)
2831 self.assertIs(s.lstrip().__class__, str)
2832 self.assertEqual(s.lstrip(), base)
2833 self.assertIs(s.rstrip().__class__, str)
2834 self.assertEqual(s.rstrip(), base)
2835 identitytab = ''.join([chr(i) for i in range(256)])
2836 self.assertIs(s.translate(identitytab).__class__, str)
2837 self.assertEqual(s.translate(identitytab), base)
2838 self.assertIs(s.translate(identitytab, "x").__class__, str)
2839 self.assertEqual(s.translate(identitytab, "x"), base)
2840 self.assertEqual(s.translate(identitytab, "\x00"), "")
2841 self.assertIs(s.replace("x", "x").__class__, str)
2842 self.assertEqual(s.replace("x", "x"), base)
2843 self.assertIs(s.ljust(len(s)).__class__, str)
2844 self.assertEqual(s.ljust(len(s)), base)
2845 self.assertIs(s.rjust(len(s)).__class__, str)
2846 self.assertEqual(s.rjust(len(s)), base)
2847 self.assertIs(s.center(len(s)).__class__, str)
2848 self.assertEqual(s.center(len(s)), base)
2849 self.assertIs(s.lower().__class__, str)
2850 self.assertEqual(s.lower(), base)
2851
2852 class madunicode(unicode):
2853 _rev = None
2854 def rev(self):
2855 if self._rev is not None:
2856 return self._rev
2857 L = list(self)
2858 L.reverse()
2859 self._rev = self.__class__(u"".join(L))
2860 return self._rev
2861 u = madunicode("ABCDEF")
2862 self.assertEqual(u, u"ABCDEF")
2863 self.assertEqual(u.rev(), madunicode(u"FEDCBA"))
2864 self.assertEqual(u.rev().rev(), madunicode(u"ABCDEF"))
2865 base = u"12345"
2866 u = madunicode(base)
2867 self.assertEqual(unicode(u), base)
2868 self.assertIs(unicode(u).__class__, unicode)
2869 self.assertEqual(hash(u), hash(base))
2870 self.assertEqual({u: 1}[base], 1)
2871 self.assertEqual({base: 1}[u], 1)
2872 self.assertIs(u.strip().__class__, unicode)
2873 self.assertEqual(u.strip(), base)
2874 self.assertIs(u.lstrip().__class__, unicode)
2875 self.assertEqual(u.lstrip(), base)
2876 self.assertIs(u.rstrip().__class__, unicode)
2877 self.assertEqual(u.rstrip(), base)
2878 self.assertIs(u.replace(u"x", u"x").__class__, unicode)
2879 self.assertEqual(u.replace(u"x", u"x"), base)
2880 self.assertIs(u.replace(u"xy", u"xy").__class__, unicode)
2881 self.assertEqual(u.replace(u"xy", u"xy"), base)
2882 self.assertIs(u.center(len(u)).__class__, unicode)
2883 self.assertEqual(u.center(len(u)), base)
2884 self.assertIs(u.ljust(len(u)).__class__, unicode)
2885 self.assertEqual(u.ljust(len(u)), base)
2886 self.assertIs(u.rjust(len(u)).__class__, unicode)
2887 self.assertEqual(u.rjust(len(u)), base)
2888 self.assertIs(u.lower().__class__, unicode)
2889 self.assertEqual(u.lower(), base)
2890 self.assertIs(u.upper().__class__, unicode)
2891 self.assertEqual(u.upper(), base)
2892 self.assertIs(u.capitalize().__class__, unicode)
2893 self.assertEqual(u.capitalize(), base)
2894 self.assertIs(u.title().__class__, unicode)
2895 self.assertEqual(u.title(), base)
2896 self.assertIs((u + u"").__class__, unicode)
2897 self.assertEqual(u + u"", base)
2898 self.assertIs((u"" + u).__class__, unicode)
2899 self.assertEqual(u"" + u, base)
2900 self.assertIs((u * 0).__class__, unicode)
2901 self.assertEqual(u * 0, u"")
2902 self.assertIs((u * 1).__class__, unicode)
2903 self.assertEqual(u * 1, base)
2904 self.assertIs((u * 2).__class__, unicode)
2905 self.assertEqual(u * 2, base + base)
2906 self.assertIs(u[:].__class__, unicode)
2907 self.assertEqual(u[:], base)
2908 self.assertIs(u[0:0].__class__, unicode)
2909 self.assertEqual(u[0:0], u"")
2910
2911 class sublist(list):
2912 pass
2913 a = sublist(range(5))
2914 self.assertEqual(a, range(5))
2915 a.append("hello")
2916 self.assertEqual(a, range(5) + ["hello"])
2917 a[5] = 5
2918 self.assertEqual(a, range(6))
2919 a.extend(range(6, 20))
2920 self.assertEqual(a, range(20))
2921 a[-5:] = []
2922 self.assertEqual(a, range(15))
2923 del a[10:15]
2924 self.assertEqual(len(a), 10)
2925 self.assertEqual(a, range(10))
2926 self.assertEqual(list(a), range(10))
2927 self.assertEqual(a[0], 0)
2928 self.assertEqual(a[9], 9)
2929 self.assertEqual(a[-10], 0)
2930 self.assertEqual(a[-1], 9)
2931 self.assertEqual(a[:5], range(5))
2932
2933 class CountedInput(file):
2934 """Counts lines read by self.readline().
2935
2936 self.lineno is the 0-based ordinal of the last line read, up to
2937 a maximum of one greater than the number of lines in the file.
2938
2939 self.ateof is true if and only if the final "" line has been read,
2940 at which point self.lineno stops incrementing, and further calls
2941 to readline() continue to return "".
2942 """
2943
2944 lineno = 0
2945 ateof = 0
2946 def readline(self):
2947 if self.ateof:
2948 return ""
2949 s = file.readline(self)
2950 # Next line works too.
2951 # s = super(CountedInput, self).readline()
2952 self.lineno += 1
2953 if s == "":
2954 self.ateof = 1
2955 return s
2956
2957 f = file(name=test_support.TESTFN, mode='w')
2958 lines = ['a\n', 'b\n', 'c\n']
2959 try:
2960 f.writelines(lines)
2961 f.close()
2962 f = CountedInput(test_support.TESTFN)
2963 for (i, expected) in zip(range(1, 5) + [4], lines + 2 * [""]):
2964 got = f.readline()
2965 self.assertEqual(expected, got)
2966 self.assertEqual(f.lineno, i)
2967 self.assertEqual(f.ateof, (i > len(lines)))
2968 f.close()
2969 finally:
2970 try:
2971 f.close()
2972 except:
2973 pass
2974 test_support.unlink(test_support.TESTFN)
2975
2976 def test_keywords(self):
2977 # Testing keyword args to basic type constructors ...
2978 self.assertEqual(int(x=1), 1)
2979 self.assertEqual(float(x=2), 2.0)
2980 self.assertEqual(long(x=3), 3L)
2981 self.assertEqual(complex(imag=42, real=666), complex(666, 42))
2982 self.assertEqual(str(object=500), '500')
2983 self.assertEqual(unicode(string='abc', errors='strict'), u'abc')
2984 self.assertEqual(tuple(sequence=range(3)), (0, 1, 2))
2985 self.assertEqual(list(sequence=(0, 1, 2)), range(3))
2986 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2987
2988 for constructor in (int, float, long, complex, str, unicode,
2989 tuple, list, file):
2990 try:
2991 constructor(bogus_keyword_arg=1)
2992 except TypeError:
2993 pass
2994 else:
2995 self.fail("expected TypeError from bogus keyword argument to %r"
2996 % constructor)
2997
2998 def test_str_subclass_as_dict_key(self):
2999 # Testing a str subclass used as dict key ..
3000
3001 class cistr(str):
3002 """Sublcass of str that computes __eq__ case-insensitively.
3003
3004 Also computes a hash code of the string in canonical form.
3005 """
3006
3007 def __init__(self, value):
3008 self.canonical = value.lower()
3009 self.hashcode = hash(self.canonical)
3010
3011 def __eq__(self, other):
3012 if not isinstance(other, cistr):
3013 other = cistr(other)
3014 return self.canonical == other.canonical
3015
3016 def __hash__(self):
3017 return self.hashcode
3018
3019 self.assertEqual(cistr('ABC'), 'abc')
3020 self.assertEqual('aBc', cistr('ABC'))
3021 self.assertEqual(str(cistr('ABC')), 'ABC')
3022
3023 d = {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
3024 self.assertEqual(d[cistr('one')], 1)
3025 self.assertEqual(d[cistr('tWo')], 2)
3026 self.assertEqual(d[cistr('THrEE')], 3)
3027 self.assertIn(cistr('ONe'), d)
3028 self.assertEqual(d.get(cistr('thrEE')), 3)
3029
3030 def test_classic_comparisons(self):
3031 # Testing classic comparisons...
3032 class classic:
3033 pass
3034
3035 for base in (classic, int, object):
3036 class C(base):
3037 def __init__(self, value):
3038 self.value = int(value)
3039 def __cmp__(self, other):
3040 if isinstance(other, C):
3041 return cmp(self.value, other.value)
3042 if isinstance(other, int) or isinstance(other, long):
3043 return cmp(self.value, other)
3044 return NotImplemented
3045 __hash__ = None # Silence Py3k warning
3046
3047 c1 = C(1)
3048 c2 = C(2)
3049 c3 = C(3)
3050 self.assertEqual(c1, 1)
3051 c = {1: c1, 2: c2, 3: c3}
3052 for x in 1, 2, 3:
3053 for y in 1, 2, 3:
3054 self.assertEqual(cmp(c[x], c[y]), cmp(x, y),
3055 "x=%d, y=%d" % (x, y))
3056 for op in "<", "<=", "==", "!=", ">", ">=":
3057 self.assertEqual(eval("c[x] %s c[y]" % op),
3058 eval("x %s y" % op),
3059 "x=%d, y=%d" % (x, y))
3060 self.assertEqual(cmp(c[x], y), cmp(x, y),
3061 "x=%d, y=%d" % (x, y))
3062 self.assertEqual(cmp(x, c[y]), cmp(x, y),
3063 "x=%d, y=%d" % (x, y))
3064
3065 def test_rich_comparisons(self):
3066 # Testing rich comparisons...
3067 class Z(complex):
3068 pass
3069 z = Z(1)
3070 self.assertEqual(z, 1+0j)
3071 self.assertEqual(1+0j, z)
3072 class ZZ(complex):
3073 def __eq__(self, other):
3074 try:
3075 return abs(self - other) <= 1e-6
3076 except:
3077 return NotImplemented
3078 __hash__ = None # Silence Py3k warning
3079 zz = ZZ(1.0000003)
3080 self.assertEqual(zz, 1+0j)
3081 self.assertEqual(1+0j, zz)
3082
3083 class classic:
3084 pass
3085 for base in (classic, int, object, list):
3086 class C(base):
3087 def __init__(self, value):
3088 self.value = int(value)
3089 def __cmp__(self_, other):
3090 self.fail("shouldn't call __cmp__")
3091 __hash__ = None # Silence Py3k warning
3092 def __eq__(self, other):
3093 if isinstance(other, C):
3094 return self.value == other.value
3095 if isinstance(other, int) or isinstance(other, long):
3096 return self.value == other
3097 return NotImplemented
3098 def __ne__(self, other):
3099 if isinstance(other, C):
3100 return self.value != other.value
3101 if isinstance(other, int) or isinstance(other, long):
3102 return self.value != other
3103 return NotImplemented
3104 def __lt__(self, other):
3105 if isinstance(other, C):
3106 return self.value < other.value
3107 if isinstance(other, int) or isinstance(other, long):
3108 return self.value < other
3109 return NotImplemented
3110 def __le__(self, other):
3111 if isinstance(other, C):
3112 return self.value <= other.value
3113 if isinstance(other, int) or isinstance(other, long):
3114 return self.value <= other
3115 return NotImplemented
3116 def __gt__(self, other):
3117 if isinstance(other, C):
3118 return self.value > other.value
3119 if isinstance(other, int) or isinstance(other, long):
3120 return self.value > other
3121 return NotImplemented
3122 def __ge__(self, other):
3123 if isinstance(other, C):
3124 return self.value >= other.value
3125 if isinstance(other, int) or isinstance(other, long):
3126 return self.value >= other
3127 return NotImplemented
3128 c1 = C(1)
3129 c2 = C(2)
3130 c3 = C(3)
3131 self.assertEqual(c1, 1)
3132 c = {1: c1, 2: c2, 3: c3}
3133 for x in 1, 2, 3:
3134 for y in 1, 2, 3:
3135 for op in "<", "<=", "==", "!=", ">", ">=":
3136 self.assertEqual(eval("c[x] %s c[y]" % op),
3137 eval("x %s y" % op),
3138 "x=%d, y=%d" % (x, y))
3139 self.assertEqual(eval("c[x] %s y" % op),
3140 eval("x %s y" % op),
3141 "x=%d, y=%d" % (x, y))
3142 self.assertEqual(eval("x %s c[y]" % op),
3143 eval("x %s y" % op),
3144 "x=%d, y=%d" % (x, y))
3145
3146 def test_coercions(self):
3147 # Testing coercions...
3148 class I(int): pass
3149 coerce(I(0), 0)
3150 coerce(0, I(0))
3151 class L(long): pass
3152 coerce(L(0), 0)
3153 coerce(L(0), 0L)
3154 coerce(0, L(0))
3155 coerce(0L, L(0))
3156 class F(float): pass
3157 coerce(F(0), 0)
3158 coerce(F(0), 0L)
3159 coerce(F(0), 0.)
3160 coerce(0, F(0))
3161 coerce(0L, F(0))
3162 coerce(0., F(0))
3163 class C(complex): pass
3164 coerce(C(0), 0)
3165 coerce(C(0), 0L)
3166 coerce(C(0), 0.)
3167 coerce(C(0), 0j)
3168 coerce(0, C(0))
3169 coerce(0L, C(0))
3170 coerce(0., C(0))
3171 coerce(0j, C(0))
3172
3173 def test_descrdoc(self):
3174 # Testing descriptor doc strings...
3175 def check(descr, what):
3176 self.assertEqual(descr.__doc__, what)
3177 check(file.closed, "True if the file is closed") # getset descriptor
3178 check(file.name, "file name") # member descriptor
3179
3180 def test_doc_descriptor(self):
3181 # Testing __doc__ descriptor...
3182 # SF bug 542984
3183 class DocDescr(object):
3184 def __get__(self, object, otype):
3185 if object:
3186 object = object.__class__.__name__ + ' instance'
3187 if otype:
3188 otype = otype.__name__
3189 return 'object=%s; type=%s' % (object, otype)
3190 class OldClass:
3191 __doc__ = DocDescr()
3192 class NewClass(object):
3193 __doc__ = DocDescr()
3194 self.assertEqual(OldClass.__doc__, 'object=None; type=OldClass')
3195 self.assertEqual(OldClass().__doc__, 'object=OldClass instance; type=OldClass')
3196 self.assertEqual(NewClass.__doc__, 'object=None; type=NewClass')
3197 self.assertEqual(NewClass().__doc__, 'object=NewClass instance; type=NewClass')
3198
3199 def test_set_class(self):
3200 # Testing __class__ assignment...
3201 class C(object): pass
3202 class D(object): pass
3203 class E(object): pass
3204 class F(D, E): pass
3205 for cls in C, D, E, F:
3206 for cls2 in C, D, E, F:
3207 x = cls()
3208 x.__class__ = cls2
3209 self.assertIs(x.__class__, cls2)
3210 x.__class__ = cls
3211 self.assertIs(x.__class__, cls)
3212 def cant(x, C):
3213 try:
3214 x.__class__ = C
3215 except TypeError:
3216 pass
3217 else:
3218 self.fail("shouldn't allow %r.__class__ = %r" % (x, C))
3219 try:
3220 delattr(x, "__class__")
3221 except (TypeError, AttributeError):
3222 pass
3223 else:
3224 self.fail("shouldn't allow del %r.__class__" % x)
3225 cant(C(), list)
3226 cant(list(), C)
3227 cant(C(), 1)
3228 cant(C(), object)
3229 cant(object(), list)
3230 cant(list(), object)
3231 class Int(int): __slots__ = []
3232 cant(2, Int)
3233 cant(Int(), int)
3234 cant(True, int)
3235 cant(2, bool)
3236 o = object()
3237 cant(o, type(1))
3238 cant(o, type(None))
3239 del o
3240 class G(object):
3241 __slots__ = ["a", "b"]
3242 class H(object):
3243 __slots__ = ["b", "a"]
3244 try:
3245 unicode
3246 except NameError:
3247 class I(object):
3248 __slots__ = ["a", "b"]
3249 else:
3250 class I(object):
3251 __slots__ = [unicode("a"), unicode("b")]
3252 class J(object):
3253 __slots__ = ["c", "b"]
3254 class K(object):
3255 __slots__ = ["a", "b", "d"]
3256 class L(H):
3257 __slots__ = ["e"]
3258 class M(I):
3259 __slots__ = ["e"]
3260 class N(J):
3261 __slots__ = ["__weakref__"]
3262 class P(J):
3263 __slots__ = ["__dict__"]
3264 class Q(J):
3265 pass
3266 class R(J):
3267 __slots__ = ["__dict__", "__weakref__"]
3268
3269 for cls, cls2 in ((G, H), (G, I), (I, H), (Q, R), (R, Q)):
3270 x = cls()
3271 x.a = 1
3272 x.__class__ = cls2
3273 self.assertIs(x.__class__, cls2,
3274 "assigning %r as __class__ for %r silently failed" % (cls2, x))
3275 self.assertEqual(x.a, 1)
3276 x.__class__ = cls
3277 self.assertIs(x.__class__, cls,
3278 "assigning %r as __class__ for %r silently failed" % (cls, x))
3279 self.assertEqual(x.a, 1)
3280 for cls in G, J, K, L, M, N, P, R, list, Int:
3281 for cls2 in G, J, K, L, M, N, P, R, list, Int:
3282 if cls is cls2:
3283 continue
3284 cant(cls(), cls2)
3285
3286 # Issue5283: when __class__ changes in __del__, the wrong
3287 # type gets DECREF'd.
3288 class O(object):
3289 pass
3290 class A(object):
3291 def __del__(self):
3292 self.__class__ = O
3293 l = [A() for x in range(100)]
3294 del l
3295
3296 def test_set_dict(self):
3297 # Testing __dict__ assignment...
3298 class C(object): pass
3299 a = C()
3300 a.__dict__ = {'b': 1}
3301 self.assertEqual(a.b, 1)
3302 def cant(x, dict):
3303 try:
3304 x.__dict__ = dict
3305 except (AttributeError, TypeError):
3306 pass
3307 else:
3308 self.fail("shouldn't allow %r.__dict__ = %r" % (x, dict))
3309 cant(a, None)
3310 cant(a, [])
3311 cant(a, 1)
3312 del a.__dict__ # Deleting __dict__ is allowed
3313
3314 class Base(object):
3315 pass
3316 def verify_dict_readonly(x):
3317 """
3318 x has to be an instance of a class inheriting from Base.
3319 """
3320 cant(x, {})
3321 try:
3322 del x.__dict__
3323 except (AttributeError, TypeError):
3324 pass
3325 else:
3326 self.fail("shouldn't allow del %r.__dict__" % x)
3327 dict_descr = Base.__dict__["__dict__"]
3328 try:
3329 dict_descr.__set__(x, {})
3330 except (AttributeError, TypeError):
3331 pass
3332 else:
3333 self.fail("dict_descr allowed access to %r's dict" % x)
3334
3335 # Classes don't allow __dict__ assignment and have readonly dicts
3336 class Meta1(type, Base):
3337 pass
3338 class Meta2(Base, type):
3339 pass
3340 class D(object):
3341 __metaclass__ = Meta1
3342 class E(object):
3343 __metaclass__ = Meta2
3344 for cls in C, D, E:
3345 verify_dict_readonly(cls)
3346 class_dict = cls.__dict__
3347 try:
3348 class_dict["spam"] = "eggs"
3349 except TypeError:
3350 pass
3351 else:
3352 self.fail("%r's __dict__ can be modified" % cls)
3353
3354 # Modules also disallow __dict__ assignment
3355 class Module1(types.ModuleType, Base):
3356 pass
3357 class Module2(Base, types.ModuleType):
3358 pass
3359 for ModuleType in Module1, Module2:
3360 mod = ModuleType("spam")
3361 verify_dict_readonly(mod)
3362 mod.__dict__["spam"] = "eggs"
3363
3364 # Exception's __dict__ can be replaced, but not deleted
3365 # (at least not any more than regular exception's __dict__ can
3366 # be deleted; on CPython it is not the case, whereas on PyPy they
3367 # can, just like any other new-style instance's __dict__.)
3368 def can_delete_dict(e):
3369 try:
3370 del e.__dict__
3371 except (TypeError, AttributeError):
3372 return False
3373 else:
3374 return True
3375 class Exception1(Exception, Base):
3376 pass
3377 class Exception2(Base, Exception):
3378 pass
3379 for ExceptionType in Exception, Exception1, Exception2:
3380 e = ExceptionType()
3381 e.__dict__ = {"a": 1}
3382 self.assertEqual(e.a, 1)
3383 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError()))
3384
3385 def test_pickles(self):
3386 # Testing pickling and copying new-style classes and objects...
3387 import pickle, cPickle
3388
3389 def sorteditems(d):
3390 L = d.items()
3391 L.sort()
3392 return L
3393
3394 global C
3395 class C(object):
3396 def __init__(self, a, b):
3397 super(C, self).__init__()
3398 self.a = a
3399 self.b = b
3400 def __repr__(self):
3401 return "C(%r, %r)" % (self.a, self.b)
3402
3403 global C1
3404 class C1(list):
3405 def __new__(cls, a, b):
3406 return super(C1, cls).__new__(cls)
3407 def __getnewargs__(self):
3408 return (self.a, self.b)
3409 def __init__(self, a, b):
3410 self.a = a
3411 self.b = b
3412 def __repr__(self):
3413 return "C1(%r, %r)<%r>" % (self.a, self.b, list(self))
3414
3415 global C2
3416 class C2(int):
3417 def __new__(cls, a, b, val=0):
3418 return super(C2, cls).__new__(cls, val)
3419 def __getnewargs__(self):
3420 return (self.a, self.b, int(self))
3421 def __init__(self, a, b, val=0):
3422 self.a = a
3423 self.b = b
3424 def __repr__(self):
3425 return "C2(%r, %r)<%r>" % (self.a, self.b, int(self))
3426
3427 global C3
3428 class C3(object):
3429 def __init__(self, foo):
3430 self.foo = foo
3431 def __getstate__(self):
3432 return self.foo
3433 def __setstate__(self, foo):
3434 self.foo = foo
3435
3436 global C4classic, C4
3437 class C4classic: # classic
3438 pass
3439 class C4(C4classic, object): # mixed inheritance
3440 pass
3441
3442 for p in pickle, cPickle:
3443 for bin in range(p.HIGHEST_PROTOCOL + 1):
3444 for cls in C, C1, C2:
3445 s = p.dumps(cls, bin)
3446 cls2 = p.loads(s)
3447 self.assertIs(cls2, cls)
3448
3449 a = C1(1, 2); a.append(42); a.append(24)
3450 b = C2("hello", "world", 42)
3451 s = p.dumps((a, b), bin)
3452 x, y = p.loads(s)
3453 self.assertEqual(x.__class__, a.__class__)
3454 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3455 self.assertEqual(y.__class__, b.__class__)
3456 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3457 self.assertEqual(repr(x), repr(a))
3458 self.assertEqual(repr(y), repr(b))
3459 # Test for __getstate__ and __setstate__ on new style class
3460 u = C3(42)
3461 s = p.dumps(u, bin)
3462 v = p.loads(s)
3463 self.assertEqual(u.__class__, v.__class__)
3464 self.assertEqual(u.foo, v.foo)
3465 # Test for picklability of hybrid class
3466 u = C4()
3467 u.foo = 42
3468 s = p.dumps(u, bin)
3469 v = p.loads(s)
3470 self.assertEqual(u.__class__, v.__class__)
3471 self.assertEqual(u.foo, v.foo)
3472
3473 # Testing copy.deepcopy()
3474 import copy
3475 for cls in C, C1, C2:
3476 cls2 = copy.deepcopy(cls)
3477 self.assertIs(cls2, cls)
3478
3479 a = C1(1, 2); a.append(42); a.append(24)
3480 b = C2("hello", "world", 42)
3481 x, y = copy.deepcopy((a, b))
3482 self.assertEqual(x.__class__, a.__class__)
3483 self.assertEqual(sorteditems(x.__dict__), sorteditems(a.__dict__))
3484 self.assertEqual(y.__class__, b.__class__)
3485 self.assertEqual(sorteditems(y.__dict__), sorteditems(b.__dict__))
3486 self.assertEqual(repr(x), repr(a))
3487 self.assertEqual(repr(y), repr(b))
3488
3489 def test_pickle_slots(self):
3490 # Testing pickling of classes with __slots__ ...
3491 import pickle, cPickle
3492 # Pickling of classes with __slots__ but without __getstate__ should fail
3493 global B, C, D, E
3494 class B(object):
3495 pass
3496 for base in [object, B]:
3497 class C(base):
3498 __slots__ = ['a']
3499 class D(C):
3500 pass
3501 for proto in range(2):
3502 try:
3503 pickle.dumps(C(), proto)
3504 except TypeError:
3505 pass
3506 else:
3507 self.fail("should fail: pickle C instance - %s" % base)
3508 try:
3509 cPickle.dumps(C(), proto)
3510 except TypeError:
3511 pass
3512 else:
3513 self.fail("should fail: cPickle C instance - %s" % base)
3514 try:
3515 pickle.dumps(C(), proto)
3516 except TypeError:
3517 pass
3518 else:
3519 self.fail("should fail: pickle D instance - %s" % base)
3520 try:
3521 cPickle.dumps(D(), proto)
3522 except TypeError:
3523 pass
3524 else:
3525 self.fail("should fail: cPickle D instance - %s" % base)
3526 # Give C a nice generic __getstate__ and __setstate__
3527 class C(base):
3528 __slots__ = ['a']
3529 def __getstate__(self):
3530 try:
3531 d = self.__dict__.copy()
3532 except AttributeError:
3533 d = {}
3534 for cls in self.__class__.__mro__:
3535 for sn in cls.__dict__.get('__slots__', ()):
3536 try:
3537 d[sn] = getattr(self, sn)
3538 except AttributeError:
3539 pass
3540 return d
3541 def __setstate__(self, d):
3542 for k, v in d.items():
3543 setattr(self, k, v)
3544 class D(C):
3545 pass
3546 # Now it should work
3547 x = C()
3548 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3549 y = pickle.loads(pickle.dumps(x, proto))
3550 self.assertNotHasAttr(y, 'a')
3551 y = cPickle.loads(cPickle.dumps(x, proto))
3552 self.assertNotHasAttr(y, 'a')
3553 x.a = 42
3554 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3555 y = pickle.loads(pickle.dumps(x, proto))
3556 self.assertEqual(y.a, 42)
3557 y = cPickle.loads(cPickle.dumps(x, proto))
3558 self.assertEqual(y.a, 42)
3559 x = D()
3560 x.a = 42
3561 x.b = 100
3562 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3563 y = pickle.loads(pickle.dumps(x, proto))
3564 self.assertEqual(y.a + y.b, 142)
3565 y = cPickle.loads(cPickle.dumps(x, proto))
3566 self.assertEqual(y.a + y.b, 142)
3567 # A subclass that adds a slot should also work
3568 class E(C):
3569 __slots__ = ['b']
3570 x = E()
3571 x.a = 42
3572 x.b = "foo"
3573 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
3574 y = pickle.loads(pickle.dumps(x, proto))
3575 self.assertEqual(y.a, x.a)
3576 self.assertEqual(y.b, x.b)
3577 y = cPickle.loads(cPickle.dumps(x, proto))
3578 self.assertEqual(y.a, x.a)
3579 self.assertEqual(y.b, x.b)
3580
3581 def test_binary_operator_override(self):
3582 # Testing overrides of binary operations...
3583 class I(int):
3584 def __repr__(self):
3585 return "I(%r)" % int(self)
3586 def __add__(self, other):
3587 return I(int(self) + int(other))
3588 __radd__ = __add__
3589 def __pow__(self, other, mod=None):
3590 if mod is None:
3591 return I(pow(int(self), int(other)))
3592 else:
3593 return I(pow(int(self), int(other), int(mod)))
3594 def __rpow__(self, other, mod=None):
3595 if mod is None:
3596 return I(pow(int(other), int(self), mod))
3597 else:
3598 return I(pow(int(other), int(self), int(mod)))
3599
3600 self.assertEqual(repr(I(1) + I(2)), "I(3)")
3601 self.assertEqual(repr(I(1) + 2), "I(3)")
3602 self.assertEqual(repr(1 + I(2)), "I(3)")
3603 self.assertEqual(repr(I(2) ** I(3)), "I(8)")
3604 self.assertEqual(repr(2 ** I(3)), "I(8)")
3605 self.assertEqual(repr(I(2) ** 3), "I(8)")
3606 self.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3607 class S(str):
3608 def __eq__(self, other):
3609 return self.lower() == other.lower()
3610 __hash__ = None # Silence Py3k warning
3611
3612 def test_subclass_propagation(self):
3613 # Testing propagation of slot functions to subclasses...
3614 class A(object):
3615 pass
3616 class B(A):
3617 pass
3618 class C(A):
3619 pass
3620 class D(B, C):
3621 pass
3622 d = D()
3623 orig_hash = hash(d) # related to id(d) in platform-dependent ways
3624 A.__hash__ = lambda self: 42
3625 self.assertEqual(hash(d), 42)
3626 C.__hash__ = lambda self: 314
3627 self.assertEqual(hash(d), 314)
3628 B.__hash__ = lambda self: 144
3629 self.assertEqual(hash(d), 144)
3630 D.__hash__ = lambda self: 100
3631 self.assertEqual(hash(d), 100)
3632 D.__hash__ = None
3633 self.assertRaises(TypeError, hash, d)
3634 del D.__hash__
3635 self.assertEqual(hash(d), 144)
3636 B.__hash__ = None
3637 self.assertRaises(TypeError, hash, d)
3638 del B.__hash__
3639 self.assertEqual(hash(d), 314)
3640 C.__hash__ = None
3641 self.assertRaises(TypeError, hash, d)
3642 del C.__hash__
3643 self.assertEqual(hash(d), 42)
3644 A.__hash__ = None
3645 self.assertRaises(TypeError, hash, d)
3646 del A.__hash__
3647 self.assertEqual(hash(d), orig_hash)
3648 d.foo = 42
3649 d.bar = 42
3650 self.assertEqual(d.foo, 42)
3651 self.assertEqual(d.bar, 42)
3652 def __getattribute__(self, name):
3653 if name == "foo":
3654 return 24
3655 return object.__getattribute__(self, name)
3656 A.__getattribute__ = __getattribute__
3657 self.assertEqual(d.foo, 24)
3658 self.assertEqual(d.bar, 42)
3659 def __getattr__(self, name):
3660 if name in ("spam", "foo", "bar"):
3661 return "hello"
3662 raise AttributeError, name
3663 B.__getattr__ = __getattr__
3664 self.assertEqual(d.spam, "hello")
3665 self.assertEqual(d.foo, 24)
3666 self.assertEqual(d.bar, 42)
3667 del A.__getattribute__
3668 self.assertEqual(d.foo, 42)
3669 del d.foo
3670 self.assertEqual(d.foo, "hello")
3671 self.assertEqual(d.bar, 42)
3672 del B.__getattr__
3673 try:
3674 d.foo
3675 except AttributeError:
3676 pass
3677 else:
3678 self.fail("d.foo should be undefined now")
3679
3680 # Test a nasty bug in recurse_down_subclasses()
3681 class A(object):
3682 pass
3683 class B(A):
3684 pass
3685 del B
3686 test_support.gc_collect()
3687 A.__setitem__ = lambda *a: None # crash
3688
3689 def test_buffer_inheritance(self):
3690 # Testing that buffer interface is inherited ...
3691
3692 import binascii
3693 # SF bug [#470040] ParseTuple t# vs subclasses.
3694
3695 class MyStr(str):
3696 pass
3697 base = 'abc'
3698 m = MyStr(base)
3699 # b2a_hex uses the buffer interface to get its argument's value, via
3700 # PyArg_ParseTuple 't#' code.
3701 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3702
3703 # It's not clear that unicode will continue to support the character
3704 # buffer interface, and this test will fail if that's taken away.
3705 class MyUni(unicode):
3706 pass
3707 base = u'abc'
3708 m = MyUni(base)
3709 self.assertEqual(binascii.b2a_hex(m), binascii.b2a_hex(base))
3710
3711 class MyInt(int):
3712 pass
3713 m = MyInt(42)
3714 try:
3715 binascii.b2a_hex(m)
3716 self.fail('subclass of int should not have a buffer interface')
3717 except TypeError:
3718 pass
3719
3720 def test_str_of_str_subclass(self):
3721 # Testing __str__ defined in subclass of str ...
3722 import binascii
3723 import cStringIO
3724
3725 class octetstring(str):
3726 def __str__(self):
3727 return binascii.b2a_hex(self)
3728 def __repr__(self):
3729 return self + " repr"
3730
3731 o = octetstring('A')
3732 self.assertEqual(type(o), octetstring)
3733 self.assertEqual(type(str(o)), str)
3734 self.assertEqual(type(repr(o)), str)
3735 self.assertEqual(ord(o), 0x41)
3736 self.assertEqual(str(o), '41')
3737 self.assertEqual(repr(o), 'A repr')
3738 self.assertEqual(o.__str__(), '41')
3739 self.assertEqual(o.__repr__(), 'A repr')
3740
3741 capture = cStringIO.StringIO()
3742 # Calling str() or not exercises different internal paths.
3743 print >> capture, o
3744 print >> capture, str(o)
3745 self.assertEqual(capture.getvalue(), '41\n41\n')
3746 capture.close()
3747
3748 def test_keyword_arguments(self):
3749 # Testing keyword arguments to __init__, __call__...
3750 def f(a): return a
3751 self.assertEqual(f.__call__(a=42), 42)
3752 a = []
3753 list.__init__(a, sequence=[0, 1, 2])
3754 self.assertEqual(a, [0, 1, 2])
3755
3756 def test_recursive_call(self):
3757 # Testing recursive __call__() by setting to instance of class...
3758 class A(object):
3759 pass
3760
3761 A.__call__ = A()
3762 try:
3763 A()()
3764 except RuntimeError:
3765 pass
3766 else:
3767 self.fail("Recursion limit should have been reached for __call__()")
3768
3769 def test_delete_hook(self):
3770 # Testing __del__ hook...
3771 log = []
3772 class C(object):
3773 def __del__(self):
3774 log.append(1)
3775 c = C()
3776 self.assertEqual(log, [])
3777 del c
3778 test_support.gc_collect()
3779 self.assertEqual(log, [1])
3780
3781 class D(object): pass
3782 d = D()
3783 try: del d[0]
3784 except TypeError: pass
3785 else: self.fail("invalid del() didn't raise TypeError")
3786
3787 def test_hash_inheritance(self):
3788 # Testing hash of mutable subclasses...
3789
3790 class mydict(dict):
3791 pass
3792 d = mydict()
3793 try:
3794 hash(d)
3795 except TypeError:
3796 pass
3797 else:
3798 self.fail("hash() of dict subclass should fail")
3799
3800 class mylist(list):
3801 pass
3802 d = mylist()
3803 try:
3804 hash(d)
3805 except TypeError:
3806 pass
3807 else:
3808 self.fail("hash() of list subclass should fail")
3809
3810 def test_str_operations(self):
3811 try: 'a' + 5
3812 except TypeError: pass
3813 else: self.fail("'' + 5 doesn't raise TypeError")
3814
3815 try: ''.split('')
3816 except ValueError: pass
3817 else: self.fail("''.split('') doesn't raise ValueError")
3818
3819 try: ''.join([0])
3820 except TypeError: pass
3821 else: self.fail("''.join([0]) doesn't raise TypeError")
3822
3823 try: ''.rindex('5')
3824 except ValueError: pass
3825 else: self.fail("''.rindex('5') doesn't raise ValueError")
3826
3827 try: '%(n)s' % None
3828 except TypeError: pass
3829 else: self.fail("'%(n)s' % None doesn't raise TypeError")
3830
3831 try: '%(n' % {}
3832 except ValueError: pass
3833 else: self.fail("'%(n' % {} '' doesn't raise ValueError")
3834
3835 try: '%*s' % ('abc')
3836 except TypeError: pass
3837 else: self.fail("'%*s' % ('abc') doesn't raise TypeError")
3838
3839 try: '%*.*s' % ('abc', 5)
3840 except TypeError: pass
3841 else: self.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3842
3843 try: '%s' % (1, 2)
3844 except TypeError: pass
3845 else: self.fail("'%s' % (1, 2) doesn't raise TypeError")
3846
3847 try: '%' % None
3848 except ValueError: pass
3849 else: self.fail("'%' % None doesn't raise ValueError")
3850
3851 self.assertEqual('534253'.isdigit(), 1)
3852 self.assertEqual('534253x'.isdigit(), 0)
3853 self.assertEqual('%c' % 5, '\x05')
3854 self.assertEqual('%c' % '5', '5')
3855
3856 def test_deepcopy_recursive(self):
3857 # Testing deepcopy of recursive objects...
3858 class Node:
3859 pass
3860 a = Node()
3861 b = Node()
3862 a.b = b
3863 b.a = a
3864 z = deepcopy(a) # This blew up before
3865
3866 def test_uninitialized_modules(self):
3867 # Testing uninitialized module objects...
3868 from types import ModuleType as M
3869 m = M.__new__(M)
3870 str(m)
3871 self.assertNotHasAttr(m, "__name__")
3872 self.assertNotHasAttr(m, "__file__")
3873 self.assertNotHasAttr(m, "foo")
3874 self.assertFalse(m.__dict__) # None or {} are both reasonable answers
3875 m.foo = 1
3876 self.assertEqual(m.__dict__, {"foo": 1})
3877
3878 def test_funny_new(self):
3879 # Testing __new__ returning something unexpected...
3880 class C(object):
3881 def __new__(cls, arg):
3882 if isinstance(arg, str): return [1, 2, 3]
3883 elif isinstance(arg, int): return object.__new__(D)
3884 else: return object.__new__(cls)
3885 class D(C):
3886 def __init__(self, arg):
3887 self.foo = arg
3888 self.assertEqual(C("1"), [1, 2, 3])
3889 self.assertEqual(D("1"), [1, 2, 3])
3890 d = D(None)
3891 self.assertEqual(d.foo, None)
3892 d = C(1)
3893 self.assertEqual(isinstance(d, D), True)
3894 self.assertEqual(d.foo, 1)
3895 d = D(1)
3896 self.assertEqual(isinstance(d, D), True)
3897 self.assertEqual(d.foo, 1)
3898
3899 class C(object):
3900 @staticmethod
3901 def __new__(*args):
3902 return args
3903 self.assertEqual(C(1, 2), (C, 1, 2))
3904 class D(C):
3905 pass
3906 self.assertEqual(D(1, 2), (D, 1, 2))
3907
3908 class C(object):
3909 @classmethod
3910 def __new__(*args):
3911 return args
3912 self.assertEqual(C(1, 2), (C, C, 1, 2))
3913 class D(C):
3914 pass
3915 self.assertEqual(D(1, 2), (D, D, 1, 2))
3916
3917 def test_imul_bug(self):
3918 # Testing for __imul__ problems...
3919 # SF bug 544647
3920 class C(object):
3921 def __imul__(self, other):
3922 return (self, other)
3923 x = C()
3924 y = x
3925 y *= 1.0
3926 self.assertEqual(y, (x, 1.0))
3927 y = x
3928 y *= 2
3929 self.assertEqual(y, (x, 2))
3930 y = x
3931 y *= 3L
3932 self.assertEqual(y, (x, 3L))
3933 y = x
3934 y *= 1L<<100
3935 self.assertEqual(y, (x, 1L<<100))
3936 y = x
3937 y *= None
3938 self.assertEqual(y, (x, None))
3939 y = x
3940 y *= "foo"
3941 self.assertEqual(y, (x, "foo"))
3942
3943 def test_copy_setstate(self):
3944 # Testing that copy.*copy() correctly uses __setstate__...
3945 import copy
3946 class C(object):
3947 def __init__(self, foo=None):
3948 self.foo = foo
3949 self.__foo = foo
3950 def setfoo(self, foo=None):
3951 self.foo = foo
3952 def getfoo(self):
3953 return self.__foo
3954 def __getstate__(self):
3955 return [self.foo]
3956 def __setstate__(self_, lst):
3957 self.assertEqual(len(lst), 1)
3958 self_.__foo = self_.foo = lst[0]
3959 a = C(42)
3960 a.setfoo(24)
3961 self.assertEqual(a.foo, 24)
3962 self.assertEqual(a.getfoo(), 42)
3963 b = copy.copy(a)
3964 self.assertEqual(b.foo, 24)
3965 self.assertEqual(b.getfoo(), 24)
3966 b = copy.deepcopy(a)
3967 self.assertEqual(b.foo, 24)
3968 self.assertEqual(b.getfoo(), 24)
3969
3970 def test_slices(self):
3971 # Testing cases with slices and overridden __getitem__ ...
3972
3973 # Strings
3974 self.assertEqual("hello"[:4], "hell")
3975 self.assertEqual("hello"[slice(4)], "hell")
3976 self.assertEqual(str.__getitem__("hello", slice(4)), "hell")
3977 class S(str):
3978 def __getitem__(self, x):
3979 return str.__getitem__(self, x)
3980 self.assertEqual(S("hello")[:4], "hell")
3981 self.assertEqual(S("hello")[slice(4)], "hell")
3982 self.assertEqual(S("hello").__getitem__(slice(4)), "hell")
3983 # Tuples
3984 self.assertEqual((1,2,3)[:2], (1,2))
3985 self.assertEqual((1,2,3)[slice(2)], (1,2))
3986 self.assertEqual(tuple.__getitem__((1,2,3), slice(2)), (1,2))
3987 class T(tuple):
3988 def __getitem__(self, x):
3989 return tuple.__getitem__(self, x)
3990 self.assertEqual(T((1,2,3))[:2], (1,2))
3991 self.assertEqual(T((1,2,3))[slice(2)], (1,2))
3992 self.assertEqual(T((1,2,3)).__getitem__(slice(2)), (1,2))
3993 # Lists
3994 self.assertEqual([1,2,3][:2], [1,2])
3995 self.assertEqual([1,2,3][slice(2)], [1,2])
3996 self.assertEqual(list.__getitem__([1,2,3], slice(2)), [1,2])
3997 class L(list):
3998 def __getitem__(self, x):
3999 return list.__getitem__(self, x)
4000 self.assertEqual(L([1,2,3])[:2], [1,2])
4001 self.assertEqual(L([1,2,3])[slice(2)], [1,2])
4002 self.assertEqual(L([1,2,3]).__getitem__(slice(2)), [1,2])
4003 # Now do lists and __setitem__
4004 a = L([1,2,3])
4005 a[slice(1, 3)] = [3,2]
4006 self.assertEqual(a, [1,3,2])
4007 a[slice(0, 2, 1)] = [3,1]
4008 self.assertEqual(a, [3,1,2])
4009 a.__setitem__(slice(1, 3), [2,1])
4010 self.assertEqual(a, [3,2,1])
4011 a.__setitem__(slice(0, 2, 1), [2,3])
4012 self.assertEqual(a, [2,3,1])
4013
4014 def test_subtype_resurrection(self):
4015 # Testing resurrection of new-style instance...
4016
4017 class C(object):
4018 container = []
4019
4020 def __del__(self):
4021 # resurrect the instance
4022 C.container.append(self)
4023
4024 c = C()
4025 c.attr = 42
4026
4027 # The most interesting thing here is whether this blows up, due to
4028 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
4029 # bug).
4030 del c
4031
4032 # If that didn't blow up, it's also interesting to see whether clearing
4033 # the last container slot works: that will attempt to delete c again,
4034 # which will cause c to get appended back to the container again
4035 # "during" the del. (On non-CPython implementations, however, __del__
4036 # is typically not called again.)
4037 test_support.gc_collect()
4038 self.assertEqual(len(C.container), 1)
4039 del C.container[-1]
4040 if test_support.check_impl_detail():
4041 test_support.gc_collect()
4042 self.assertEqual(len(C.container), 1)
4043 self.assertEqual(C.container[-1].attr, 42)
4044
4045 # Make c mortal again, so that the test framework with -l doesn't report
4046 # it as a leak.
4047 del C.__del__
4048
4049 def test_slots_trash(self):
4050 # Testing slot trash...
4051 # Deallocating deeply nested slotted trash caused stack overflows
4052 class trash(object):
4053 __slots__ = ['x']
4054 def __init__(self, x):
4055 self.x = x
4056 o = None
4057 for i in xrange(50000):
4058 o = trash(o)
4059 del o
4060
4061 def test_slots_multiple_inheritance(self):
4062 # SF bug 575229, multiple inheritance w/ slots dumps core
4063 class A(object):
4064 __slots__=()
4065 class B(object):
4066 pass
4067 class C(A,B) :
4068 __slots__=()
4069 if test_support.check_impl_detail():
4070 self.assertEqual(C.__basicsize__, B.__basicsize__)
4071 self.assertHasAttr(C, '__dict__')
4072 self.assertHasAttr(C, '__weakref__')
4073 C().x = 2
4074
4075 def test_rmul(self):
4076 # Testing correct invocation of __rmul__...
4077 # SF patch 592646
4078 class C(object):
4079 def __mul__(self, other):
4080 return "mul"
4081 def __rmul__(self, other):
4082 return "rmul"
4083 a = C()
4084 self.assertEqual(a*2, "mul")
4085 self.assertEqual(a*2.2, "mul")
4086 self.assertEqual(2*a, "rmul")
4087 self.assertEqual(2.2*a, "rmul")
4088
4089 def test_ipow(self):
4090 # Testing correct invocation of __ipow__...
4091 # [SF bug 620179]
4092 class C(object):
4093 def __ipow__(self, other):
4094 pass
4095 a = C()
4096 a **= 2
4097
4098 def test_mutable_bases(self):
4099 # Testing mutable bases...
4100
4101 # stuff that should work:
4102 class C(object):
4103 pass
4104 class C2(object):
4105 def __getattribute__(self, attr):
4106 if attr == 'a':
4107 return 2
4108 else:
4109 return super(C2, self).__getattribute__(attr)
4110 def meth(self):
4111 return 1
4112 class D(C):
4113 pass
4114 class E(D):
4115 pass
4116 d = D()
4117 e = E()
4118 D.__bases__ = (C,)
4119 D.__bases__ = (C2,)
4120 self.assertEqual(d.meth(), 1)
4121 self.assertEqual(e.meth(), 1)
4122 self.assertEqual(d.a, 2)
4123 self.assertEqual(e.a, 2)
4124 self.assertEqual(C2.__subclasses__(), [D])
4125
4126 try:
4127 del D.__bases__
4128 except (TypeError, AttributeError):
4129 pass
4130 else:
4131 self.fail("shouldn't be able to delete .__bases__")
4132
4133 try:
4134 D.__bases__ = ()
4135 except TypeError, msg:
4136 if str(msg) == "a new-style class can't have only classic bases":
4137 self.fail("wrong error message for .__bases__ = ()")
4138 else:
4139 self.fail("shouldn't be able to set .__bases__ to ()")
4140
4141 try:
4142 D.__bases__ = (D,)
4143 except TypeError:
4144 pass
4145 else:
4146 # actually, we'll have crashed by here...
4147 self.fail("shouldn't be able to create inheritance cycles")
4148
4149 try:
4150 D.__bases__ = (C, C)
4151 except TypeError:
4152 pass
4153 else:
4154 self.fail("didn't detect repeated base classes")
4155
4156 try:
4157 D.__bases__ = (E,)
4158 except TypeError:
4159 pass
4160 else:
4161 self.fail("shouldn't be able to create inheritance cycles")
4162
4163 # let's throw a classic class into the mix:
4164 class Classic:
4165 def meth2(self):
4166 return 3
4167
4168 D.__bases__ = (C, Classic)
4169
4170 self.assertEqual(d.meth2(), 3)
4171 self.assertEqual(e.meth2(), 3)
4172 try:
4173 d.a
4174 except AttributeError:
4175 pass
4176 else:
4177 self.fail("attribute should have vanished")
4178
4179 try:
4180 D.__bases__ = (Classic,)
4181 except TypeError:
4182 pass
4183 else:
4184 self.fail("new-style class must have a new-style base")
4185
4186 def test_builtin_bases(self):
4187 # Make sure all the builtin types can have their base queried without
4188 # segfaulting. See issue #5787.
4189 builtin_types = [tp for tp in __builtin__.__dict__.itervalues()
4190 if isinstance(tp, type)]
4191 for tp in builtin_types:
4192 object.__getattribute__(tp, "__bases__")
4193 if tp is not object:
4194 self.assertEqual(len(tp.__bases__), 1, tp)
4195
4196 class L(list):
4197 pass
4198
4199 class C(object):
4200 pass
4201
4202 class D(C):
4203 pass
4204
4205 try:
4206 L.__bases__ = (dict,)
4207 except TypeError:
4208 pass
4209 else:
4210 self.fail("shouldn't turn list subclass into dict subclass")
4211
4212 try:
4213 list.__bases__ = (dict,)
4214 except TypeError:
4215 pass
4216 else:
4217 self.fail("shouldn't be able to assign to list.__bases__")
4218
4219 try:
4220 D.__bases__ = (C, list)
4221 except TypeError:
4222 pass
4223 else:
4224 assert 0, "best_base calculation found wanting"
4225
4226 def test_unsubclassable_types(self):
4227 with self.assertRaises(TypeError):
4228 class X(types.NoneType):
4229 pass
4230 with self.assertRaises(TypeError):
4231 class X(object, types.NoneType):
4232 pass
4233 with self.assertRaises(TypeError):
4234 class X(types.NoneType, object):
4235 pass
4236 class O(object):
4237 pass
4238 with self.assertRaises(TypeError):
4239 class X(O, types.NoneType):
4240 pass
4241 with self.assertRaises(TypeError):
4242 class X(types.NoneType, O):
4243 pass
4244
4245 class X(object):
4246 pass
4247 with self.assertRaises(TypeError):
4248 X.__bases__ = types.NoneType,
4249 with self.assertRaises(TypeError):
4250 X.__bases__ = object, types.NoneType
4251 with self.assertRaises(TypeError):
4252 X.__bases__ = types.NoneType, object
4253 with self.assertRaises(TypeError):
4254 X.__bases__ = O, types.NoneType
4255 with self.assertRaises(TypeError):
4256 X.__bases__ = types.NoneType, O
4257
4258 def test_mutable_bases_with_failing_mro(self):
4259 # Testing mutable bases with failing mro...
4260 class WorkOnce(type):
4261 def __new__(self, name, bases, ns):
4262 self.flag = 0
4263 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
4264 def mro(self):
4265 if self.flag > 0:
4266 raise RuntimeError, "bozo"
4267 else:
4268 self.flag += 1
4269 return type.mro(self)
4270
4271 class WorkAlways(type):
4272 def mro(self):
4273 # this is here to make sure that .mro()s aren't called
4274 # with an exception set (which was possible at one point).
4275 # An error message will be printed in a debug build.
4276 # What's a good way to test for this?
4277 return type.mro(self)
4278
4279 class C(object):
4280 pass
4281
4282 class C2(object):
4283 pass
4284
4285 class D(C):
4286 pass
4287
4288 class E(D):
4289 pass
4290
4291 class F(D):
4292 __metaclass__ = WorkOnce
4293
4294 class G(D):
4295 __metaclass__ = WorkAlways
4296
4297 # Immediate subclasses have their mro's adjusted in alphabetical
4298 # order, so E's will get adjusted before adjusting F's fails. We
4299 # check here that E's gets restored.
4300
4301 E_mro_before = E.__mro__
4302 D_mro_before = D.__mro__
4303
4304 try:
4305 D.__bases__ = (C2,)
4306 except RuntimeError:
4307 self.assertEqual(E.__mro__, E_mro_before)
4308 self.assertEqual(D.__mro__, D_mro_before)
4309 else:
4310 self.fail("exception not propagated")
4311
4312 def test_mutable_bases_catch_mro_conflict(self):
4313 # Testing mutable bases catch mro conflict...
4314 class A(object):
4315 pass
4316
4317 class B(object):
4318 pass
4319
4320 class C(A, B):
4321 pass
4322
4323 class D(A, B):
4324 pass
4325
4326 class E(C, D):
4327 pass
4328
4329 try:
4330 C.__bases__ = (B, A)
4331 except TypeError:
4332 pass
4333 else:
4334 self.fail("didn't catch MRO conflict")
4335
4336 def test_mutable_names(self):
4337 # Testing mutable names...
4338 class C(object):
4339 pass
4340
4341 # C.__module__ could be 'test_descr' or '__main__'
4342 mod = C.__module__
4343
4344 C.__name__ = 'D'
4345 self.assertEqual((C.__module__, C.__name__), (mod, 'D'))
4346
4347 C.__name__ = 'D.E'
4348 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
4349
4350 def test_evil_type_name(self):
4351 # A badly placed Py_DECREF in type_set_name led to arbitrary code
4352 # execution while the type structure was not in a sane state, and a
4353 # possible segmentation fault as a result. See bug #16447.
4354 class Nasty(str):
4355 def __del__(self):
4356 C.__name__ = "other"
4357
4358 class C(object):
4359 pass
4360
4361 C.__name__ = Nasty("abc")
4362 C.__name__ = "normal"
4363
4364 def test_subclass_right_op(self):
4365 # Testing correct dispatch of subclass overloading __r<op>__...
4366
4367 # This code tests various cases where right-dispatch of a subclass
4368 # should be preferred over left-dispatch of a base class.
4369
4370 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4371
4372 class B(int):
4373 def __floordiv__(self, other):
4374 return "B.__floordiv__"
4375 def __rfloordiv__(self, other):
4376 return "B.__rfloordiv__"
4377
4378 self.assertEqual(B(1) // 1, "B.__floordiv__")
4379 self.assertEqual(1 // B(1), "B.__rfloordiv__")
4380
4381 # Case 2: subclass of object; this is just the baseline for case 3
4382
4383 class C(object):
4384 def __floordiv__(self, other):
4385 return "C.__floordiv__"
4386 def __rfloordiv__(self, other):
4387 return "C.__rfloordiv__"
4388
4389 self.assertEqual(C() // 1, "C.__floordiv__")
4390 self.assertEqual(1 // C(), "C.__rfloordiv__")
4391
4392 # Case 3: subclass of new-style class; here it gets interesting
4393
4394 class D(C):
4395 def __floordiv__(self, other):
4396 return "D.__floordiv__"
4397 def __rfloordiv__(self, other):
4398 return "D.__rfloordiv__"
4399
4400 self.assertEqual(D() // C(), "D.__floordiv__")
4401 self.assertEqual(C() // D(), "D.__rfloordiv__")
4402
4403 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4404
4405 class E(C):
4406 pass
4407
4408 self.assertEqual(E.__rfloordiv__, C.__rfloordiv__)
4409
4410 self.assertEqual(E() // 1, "C.__floordiv__")
4411 self.assertEqual(1 // E(), "C.__rfloordiv__")
4412 self.assertEqual(E() // C(), "C.__floordiv__")
4413 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4414
4415 @test_support.impl_detail("testing an internal kind of method object")
4416 def test_meth_class_get(self):
4417 # Testing __get__ method of METH_CLASS C methods...
4418 # Full coverage of descrobject.c::classmethod_get()
4419
4420 # Baseline
4421 arg = [1, 2, 3]
4422 res = {1: None, 2: None, 3: None}
4423 self.assertEqual(dict.fromkeys(arg), res)
4424 self.assertEqual({}.fromkeys(arg), res)
4425
4426 # Now get the descriptor
4427 descr = dict.__dict__["fromkeys"]
4428
4429 # More baseline using the descriptor directly
4430 self.assertEqual(descr.__get__(None, dict)(arg), res)
4431 self.assertEqual(descr.__get__({})(arg), res)
4432
4433 # Now check various error cases
4434 try:
4435 descr.__get__(None, None)
4436 except TypeError:
4437 pass
4438 else:
4439 self.fail("shouldn't have allowed descr.__get__(None, None)")
4440 try:
4441 descr.__get__(42)
4442 except TypeError:
4443 pass
4444 else:
4445 self.fail("shouldn't have allowed descr.__get__(42)")
4446 try:
4447 descr.__get__(None, 42)
4448 except TypeError:
4449 pass
4450 else:
4451 self.fail("shouldn't have allowed descr.__get__(None, 42)")
4452 try:
4453 descr.__get__(None, int)
4454 except TypeError:
4455 pass
4456 else:
4457 self.fail("shouldn't have allowed descr.__get__(None, int)")
4458
4459 def test_isinst_isclass(self):
4460 # Testing proxy isinstance() and isclass()...
4461 class Proxy(object):
4462 def __init__(self, obj):
4463 self.__obj = obj
4464 def __getattribute__(self, name):
4465 if name.startswith("_Proxy__"):
4466 return object.__getattribute__(self, name)
4467 else:
4468 return getattr(self.__obj, name)
4469 # Test with a classic class
4470 class C:
4471 pass
4472 a = C()
4473 pa = Proxy(a)
4474 self.assertIsInstance(a, C) # Baseline
4475 self.assertIsInstance(pa, C) # Test
4476 # Test with a classic subclass
4477 class D(C):
4478 pass
4479 a = D()
4480 pa = Proxy(a)
4481 self.assertIsInstance(a, C) # Baseline
4482 self.assertIsInstance(pa, C) # Test
4483 # Test with a new-style class
4484 class C(object):
4485 pass
4486 a = C()
4487 pa = Proxy(a)
4488 self.assertIsInstance(a, C) # Baseline
4489 self.assertIsInstance(pa, C) # Test
4490 # Test with a new-style subclass
4491 class D(C):
4492 pass
4493 a = D()
4494 pa = Proxy(a)
4495 self.assertIsInstance(a, C) # Baseline
4496 self.assertIsInstance(pa, C) # Test
4497
4498 def test_proxy_super(self):
4499 # Testing super() for a proxy object...
4500 class Proxy(object):
4501 def __init__(self, obj):
4502 self.__obj = obj
4503 def __getattribute__(self, name):
4504 if name.startswith("_Proxy__"):
4505 return object.__getattribute__(self, name)
4506 else:
4507 return getattr(self.__obj, name)
4508
4509 class B(object):
4510 def f(self):
4511 return "B.f"
4512
4513 class C(B):
4514 def f(self):
4515 return super(C, self).f() + "->C.f"
4516
4517 obj = C()
4518 p = Proxy(obj)
4519 self.assertEqual(C.__dict__["f"](p), "B.f->C.f")
4520
4521 def test_carloverre(self):
4522 # Testing prohibition of Carlo Verre's hack...
4523 try:
4524 object.__setattr__(str, "foo", 42)
4525 except TypeError:
4526 pass
4527 else:
4528 self.fail("Carlo Verre __setattr__ succeeded!")
4529 try:
4530 object.__delattr__(str, "lower")
4531 except TypeError:
4532 pass
4533 else:
4534 self.fail("Carlo Verre __delattr__ succeeded!")
4535
4536 def test_weakref_segfault(self):
4537 # Testing weakref segfault...
4538 # SF 742911
4539 import weakref
4540
4541 class Provoker:
4542 def __init__(self, referrent):
4543 self.ref = weakref.ref(referrent)
4544
4545 def __del__(self):
4546 x = self.ref()
4547
4548 class Oops(object):
4549 pass
4550
4551 o = Oops()
4552 o.whatever = Provoker(o)
4553 del o
4554
4555 def test_wrapper_segfault(self):
4556 # SF 927248: deeply nested wrappers could cause stack overflow
4557 f = lambda:None
4558 for i in xrange(1000000):
4559 f = f.__call__
4560 f = None
4561
4562 def test_file_fault(self):
4563 # Testing sys.stdout is changed in getattr...
4564 test_stdout = sys.stdout
4565 class StdoutGuard:
4566 def __getattr__(self, attr):
4567 sys.stdout = sys.__stdout__
4568 raise RuntimeError("Premature access to sys.stdout.%s" % attr)
4569 sys.stdout = StdoutGuard()
4570 try:
4571 print "Oops!"
4572 except RuntimeError:
4573 pass
4574 finally:
4575 sys.stdout = test_stdout
4576
4577 def test_vicious_descriptor_nonsense(self):
4578 # Testing vicious_descriptor_nonsense...
4579
4580 # A potential segfault spotted by Thomas Wouters in mail to
4581 # python-dev 2003-04-17, turned into an example & fixed by Michael
4582 # Hudson just less than four months later...
4583
4584 class Evil(object):
4585 def __hash__(self):
4586 return hash('attr')
4587 def __eq__(self, other):
4588 del C.attr
4589 return 0
4590
4591 class Descr(object):
4592 def __get__(self, ob, type=None):
4593 return 1
4594
4595 class C(object):
4596 attr = Descr()
4597
4598 c = C()
4599 c.__dict__[Evil()] = 0
4600
4601 self.assertEqual(c.attr, 1)
4602 # this makes a crash more likely:
4603 test_support.gc_collect()
4604 self.assertNotHasAttr(c, 'attr')
4605
4606 def test_init(self):
4607 # SF 1155938
4608 class Foo(object):
4609 def __init__(self):
4610 return 10
4611 try:
4612 Foo()
4613 except TypeError:
4614 pass
4615 else:
4616 self.fail("did not test __init__() for None return")
4617
4618 def test_method_wrapper(self):
4619 # Testing method-wrapper objects...
4620 # <type 'method-wrapper'> did not support any reflection before 2.5
4621
4622 l = []
4623 self.assertEqual(l.__add__, l.__add__)
4624 self.assertEqual(l.__add__, [].__add__)
4625 self.assertNotEqual(l.__add__, [5].__add__)
4626 self.assertNotEqual(l.__add__, l.__mul__)
4627 self.assertEqual(l.__add__.__name__, '__add__')
4628 if hasattr(l.__add__, '__self__'):
4629 # CPython
4630 self.assertIs(l.__add__.__self__, l)
4631 self.assertIs(l.__add__.__objclass__, list)
4632 else:
4633 # Python implementations where [].__add__ is a normal bound method
4634 self.assertIs(l.__add__.im_self, l)
4635 self.assertIs(l.__add__.im_class, list)
4636 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
4637 try:
4638 hash(l.__add__)
4639 except TypeError:
4640 pass
4641 else:
4642 self.fail("no TypeError from hash([].__add__)")
4643
4644 t = ()
4645 t += (7,)
4646 self.assertEqual(t.__add__, (7,).__add__)
4647 self.assertEqual(hash(t.__add__), hash((7,).__add__))
4648
4649 def test_not_implemented(self):
4650 # Testing NotImplemented...
4651 # all binary methods should be able to return a NotImplemented
4652 import operator
4653
4654 def specialmethod(self, other):
4655 return NotImplemented
4656
4657 def check(expr, x, y):
4658 try:
4659 exec expr in {'x': x, 'y': y, 'operator': operator}
4660 except TypeError:
4661 pass
4662 else:
4663 self.fail("no TypeError from %r" % (expr,))
4664
4665 N1 = sys.maxint + 1L # might trigger OverflowErrors instead of
4666 # TypeErrors
4667 N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
4668 # ValueErrors instead of TypeErrors
4669 for metaclass in [type, types.ClassType]:
4670 for name, expr, iexpr in [
4671 ('__add__', 'x + y', 'x += y'),
4672 ('__sub__', 'x - y', 'x -= y'),
4673 ('__mul__', 'x * y', 'x *= y'),
4674 ('__truediv__', 'operator.truediv(x, y)', None),
4675 ('__floordiv__', 'operator.floordiv(x, y)', None),
4676 ('__div__', 'x / y', 'x /= y'),
4677 ('__mod__', 'x % y', 'x %= y'),
4678 ('__divmod__', 'divmod(x, y)', None),
4679 ('__pow__', 'x ** y', 'x **= y'),
4680 ('__lshift__', 'x << y', 'x <<= y'),
4681 ('__rshift__', 'x >> y', 'x >>= y'),
4682 ('__and__', 'x & y', 'x &= y'),
4683 ('__or__', 'x | y', 'x |= y'),
4684 ('__xor__', 'x ^ y', 'x ^= y'),
4685 ('__coerce__', 'coerce(x, y)', None)]:
4686 if name == '__coerce__':
4687 rname = name
4688 else:
4689 rname = '__r' + name[2:]
4690 A = metaclass('A', (), {name: specialmethod})
4691 B = metaclass('B', (), {rname: specialmethod})
4692 a = A()
4693 b = B()
4694 check(expr, a, a)
4695 check(expr, a, b)
4696 check(expr, b, a)
4697 check(expr, b, b)
4698 check(expr, a, N1)
4699 check(expr, a, N2)
4700 check(expr, N1, b)
4701 check(expr, N2, b)
4702 if iexpr:
4703 check(iexpr, a, a)
4704 check(iexpr, a, b)
4705 check(iexpr, b, a)
4706 check(iexpr, b, b)
4707 check(iexpr, a, N1)
4708 check(iexpr, a, N2)
4709 iname = '__i' + name[2:]
4710 C = metaclass('C', (), {iname: specialmethod})
4711 c = C()
4712 check(iexpr, c, a)
4713 check(iexpr, c, b)
4714 check(iexpr, c, N1)
4715 check(iexpr, c, N2)
4716
4717 def test_assign_slice(self):
4718 # ceval.c's assign_slice used to check for
4719 # tp->tp_as_sequence->sq_slice instead of
4720 # tp->tp_as_sequence->sq_ass_slice
4721
4722 class C(object):
4723 def __setslice__(self, start, stop, value):
4724 self.value = value
4725
4726 c = C()
4727 c[1:2] = 3
4728 self.assertEqual(c.value, 3)
4729
4730 def test_set_and_no_get(self):
4731 # See
4732 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html
4733 class Descr(object):
4734
4735 def __init__(self, name):
4736 self.name = name
4737
4738 def __set__(self, obj, value):
4739 obj.__dict__[self.name] = value
4740 descr = Descr("a")
4741
4742 class X(object):
4743 a = descr
4744
4745 x = X()
4746 self.assertIs(x.a, descr)
4747 x.a = 42
4748 self.assertEqual(x.a, 42)
4749
4750 # Also check type_getattro for correctness.
4751 class Meta(type):
4752 pass
4753 class X(object):
4754 __metaclass__ = Meta
4755 X.a = 42
4756 Meta.a = Descr("a")
4757 self.assertEqual(X.a, 42)
4758
4759 def test_getattr_hooks(self):
4760 # issue 4230
4761
4762 class Descriptor(object):
4763 counter = 0
4764 def __get__(self, obj, objtype=None):
4765 def getter(name):
4766 self.counter += 1
4767 raise AttributeError(name)
4768 return getter
4769
4770 descr = Descriptor()
4771 class A(object):
4772 __getattribute__ = descr
4773 class B(object):
4774 __getattr__ = descr
4775 class C(object):
4776 __getattribute__ = descr
4777 __getattr__ = descr
4778
4779 self.assertRaises(AttributeError, getattr, A(), "attr")
4780 self.assertEqual(descr.counter, 1)
4781 self.assertRaises(AttributeError, getattr, B(), "attr")
4782 self.assertEqual(descr.counter, 2)
4783 self.assertRaises(AttributeError, getattr, C(), "attr")
4784 self.assertEqual(descr.counter, 4)
4785
4786 class EvilGetattribute(object):
4787 # This used to segfault
4788 def __getattr__(self, name):
4789 raise AttributeError(name)
4790 def __getattribute__(self, name):
4791 del EvilGetattribute.__getattr__
4792 for i in range(5):
4793 gc.collect()
4794 raise AttributeError(name)
4795
4796 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4797
4798 def test_type___getattribute__(self):
4799 self.assertRaises(TypeError, type.__getattribute__, list, type)
4800
4801 def test_abstractmethods(self):
4802 # type pretends not to have __abstractmethods__.
4803 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
4804 class meta(type):
4805 pass
4806 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
4807 class X(object):
4808 pass
4809 with self.assertRaises(AttributeError):
4810 del X.__abstractmethods__
4811
4812 def test_proxy_call(self):
4813 class FakeStr(object):
4814 __class__ = str
4815
4816 fake_str = FakeStr()
4817 # isinstance() reads __class__ on new style classes
4818 self.assertIsInstance(fake_str, str)
4819
4820 # call a method descriptor
4821 with self.assertRaises(TypeError):
4822 str.split(fake_str)
4823
4824 # call a slot wrapper descriptor
4825 with self.assertRaises(TypeError):
4826 str.__add__(fake_str, "abc")
4827
4828 def test_repr_as_str(self):
4829 # Issue #11603: crash or infinite loop when rebinding __str__ as
4830 # __repr__.
4831 class Foo(object):
4832 pass
4833 Foo.__repr__ = Foo.__str__
4834 foo = Foo()
4835 self.assertRaises(RuntimeError, str, foo)
4836 self.assertRaises(RuntimeError, repr, foo)
4837
4838 def test_mixing_slot_wrappers(self):
4839 class X(dict):
4840 __setattr__ = dict.__setitem__
4841 x = X()
4842 x.y = 42
4843 self.assertEqual(x["y"], 42)
4844
4845 def test_cycle_through_dict(self):
4846 # See bug #1469629
4847 class X(dict):
4848 def __init__(self):
4849 dict.__init__(self)
4850 self.__dict__ = self
4851 x = X()
4852 x.attr = 42
4853 wr = weakref.ref(x)
4854 del x
4855 test_support.gc_collect()
4856 self.assertIsNone(wr())
4857 for o in gc.get_objects():
4858 self.assertIsNot(type(o), X)
4859
4860
4861 class DictProxyTests(unittest.TestCase):
4862 def setUp(self):
4863 class C(object):
4864 def meth(self):
4865 pass
4866 self.C = C
4867
4868 def test_repr(self):
4869 self.assertIn('dict_proxy({', repr(vars(self.C)))
4870 self.assertIn("'meth':", repr(vars(self.C)))
4871
4872 def test_iter_keys(self):
4873 # Testing dict-proxy iterkeys...
4874 keys = [ key for key in self.C.__dict__.iterkeys() ]
4875 keys.sort()
4876 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4877 '__weakref__', 'meth'])
4878
4879 def test_iter_values(self):
4880 # Testing dict-proxy itervalues...
4881 values = [ values for values in self.C.__dict__.itervalues() ]
4882 self.assertEqual(len(values), 5)
4883
4884 def test_iter_items(self):
4885 # Testing dict-proxy iteritems...
4886 keys = [ key for (key, value) in self.C.__dict__.iteritems() ]
4887 keys.sort()
4888 self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
4889 '__weakref__', 'meth'])
4890
4891 def test_dict_type_with_metaclass(self):
4892 # Testing type of __dict__ when __metaclass__ set...
4893 class B(object):
4894 pass
4895 class M(type):
4896 pass
4897 class C:
4898 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4899 __metaclass__ = M
4900 self.assertEqual(type(C.__dict__), type(B.__dict__))
4901
4902
4903 class PTypesLongInitTest(unittest.TestCase):
4904 # This is in its own TestCase so that it can be run before any other tests.
4905 def test_pytype_long_ready(self):
4906 # Testing SF bug 551412 ...
4907
4908 # This dumps core when SF bug 551412 isn't fixed --
4909 # but only when test_descr.py is run separately.
4910 # (That can't be helped -- as soon as PyType_Ready()
4911 # is called for PyLong_Type, the bug is gone.)
4912 class UserLong(object):
4913 def __pow__(self, *args):
4914 pass
4915 try:
4916 pow(0L, UserLong(), 0L)
4917 except:
4918 pass
4919
4920 # Another segfault only when run early
4921 # (before PyType_Ready(tuple) is called)
4922 type.mro(tuple)
4923
4924
4925 class PicklingTests(unittest.TestCase):
4926
4927 def test_issue24097(self):
4928 # Slot name is freed inside __getattr__ and is later used.
4929 class S(str): # Not interned
4930 pass
4931 class A(object):
4932 __slotnames__ = [S('spam')]
4933 def __getattr__(self, attr):
4934 if attr == 'spam':
4935 A.__slotnames__[:] = [S('spam')]
4936 return 42
4937 else:
4938 raise AttributeError
4939
4940 import copy_reg
4941 expected = (copy_reg.__newobj__, (A,), ({}, {'spam': 42}), None, None)
4942 self.assertEqual(A().__reduce__(2), expected)
4943
4944
4945 def test_main():
4946 deprecations = [(r'complex divmod\(\), // and % are deprecated$',
4947 DeprecationWarning)]
4948 if sys.py3kwarning:
4949 deprecations += [
4950 ("classic (int|long) division", DeprecationWarning),
4951 ("coerce.. not supported", DeprecationWarning),
4952 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)]
4953 with test_support.check_warnings(*deprecations):
4954 # Run all local test cases, with PTypesLongInitTest first.
4955 test_support.run_unittest(PTypesLongInitTest, OperatorsTest,
4956 ClassPropertiesAndMethods, DictProxyTests,
4957 PicklingTests)
4958
4959 if __name__ == "__main__":
4960 test_main()