7 from copy
import deepcopy
8 from test
import test_support
11 class OperatorsTest(unittest
.TestCase
):
13 def __init__(self
, *args
, **kwargs
):
14 unittest
.TestCase
.__init
__(self
, *args
, **kwargs
)
36 for name
, expr
in self
.binops
.items():
38 expr
= expr
+ "(a, b)"
40 expr
= 'a %s b' % expr
41 self
.binops
[name
] = expr
55 for name
, expr
in self
.unops
.items():
60 self
.unops
[name
] = expr
63 self
.original_filters
= warnings
.filters
[:]
64 warnings
.filterwarnings("ignore",
65 r
'complex divmod\(\), // and % are deprecated$',
66 DeprecationWarning, r
'(<string>|%s)$' % __name__
)
69 warnings
.filters
= self
.original_filters
71 def unop_test(self
, a
, res
, expr
="len(a)", meth
="__len__"):
73 self
.assertEqual(eval(expr
, d
), res
)
77 # Find method in parent class
78 while meth
not in t
.__dict
__:
80 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
81 # method object; the getattr() below obtains its underlying function.
82 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
83 self
.assertEqual(m(a
), res
)
85 self
.assertEqual(bm(), res
)
87 def binop_test(self
, a
, b
, res
, expr
="a+b", meth
="__add__"):
90 # XXX Hack so this passes before 2.3 when -Qnew is specified.
91 if meth
== "__div__" and 1/2 == 0.5:
94 if meth
== '__divmod__': pass
96 self
.assertEqual(eval(expr
, d
), res
)
99 while meth
not in t
.__dict
__:
101 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
102 # method object; the getattr() below obtains its underlying function.
103 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
104 self
.assertEqual(m(a
, b
), res
)
105 bm
= getattr(a
, meth
)
106 self
.assertEqual(bm(b
), res
)
108 def ternop_test(self
, a
, b
, c
, res
, expr
="a[b:c]", meth
="__getslice__"):
109 d
= {'a': a
, 'b': b
, 'c': c
}
110 self
.assertEqual(eval(expr
, d
), res
)
113 while meth
not in t
.__dict
__:
115 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
116 # method object; the getattr() below obtains its underlying function.
117 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
118 self
.assertEqual(m(a
, b
, c
), res
)
119 bm
= getattr(a
, meth
)
120 self
.assertEqual(bm(b
, c
), res
)
122 def setop_test(self
, a
, b
, res
, stmt
="a+=b", meth
="__iadd__"):
123 d
= {'a': deepcopy(a
), 'b': b
}
125 self
.assertEqual(d
['a'], res
)
128 while meth
not in t
.__dict
__:
130 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
131 # method object; the getattr() below obtains its underlying function.
132 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
135 self
.assertEqual(d
['a'], res
)
137 bm
= getattr(d
['a'], meth
)
139 self
.assertEqual(d
['a'], res
)
141 def set2op_test(self
, a
, b
, c
, res
, stmt
="a[b]=c", meth
="__setitem__"):
142 d
= {'a': deepcopy(a
), 'b': b
, 'c': c
}
144 self
.assertEqual(d
['a'], res
)
147 while meth
not in t
.__dict
__:
149 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
150 # method object; the getattr() below obtains its underlying function.
151 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
154 self
.assertEqual(d
['a'], res
)
156 bm
= getattr(d
['a'], meth
)
158 self
.assertEqual(d
['a'], res
)
160 def set3op_test(self
, a
, b
, c
, d
, res
, stmt
="a[b:c]=d", meth
="__setslice__"):
161 dictionary
= {'a': deepcopy(a
), 'b': b
, 'c': c
, 'd': d
}
162 exec stmt
in dictionary
163 self
.assertEqual(dictionary
['a'], res
)
165 while meth
not in t
.__dict
__:
168 # in some implementations (e.g. PyPy), 'm' can be a regular unbound
169 # method object; the getattr() below obtains its underlying function.
170 self
.assertEqual(getattr(m
, 'im_func', m
), t
.__dict
__[meth
])
171 dictionary
['a'] = deepcopy(a
)
172 m(dictionary
['a'], b
, c
, d
)
173 self
.assertEqual(dictionary
['a'], res
)
174 dictionary
['a'] = deepcopy(a
)
175 bm
= getattr(dictionary
['a'], meth
)
177 self
.assertEqual(dictionary
['a'], res
)
179 def test_lists(self
):
180 # Testing list operations...
181 # Asserts are within individual test methods
182 self
.binop_test([1], [2], [1,2], "a+b", "__add__")
183 self
.binop_test([1,2,3], 2, 1, "b in a", "__contains__")
184 self
.binop_test([1,2,3], 4, 0, "b in a", "__contains__")
185 self
.binop_test([1,2,3], 1, 2, "a[b]", "__getitem__")
186 self
.ternop_test([1,2,3], 0, 2, [1,2], "a[b:c]", "__getslice__")
187 self
.setop_test([1], [2], [1,2], "a+=b", "__iadd__")
188 self
.setop_test([1,2], 3, [1,2,1,2,1,2], "a*=b", "__imul__")
189 self
.unop_test([1,2,3], 3, "len(a)", "__len__")
190 self
.binop_test([1,2], 3, [1,2,1,2,1,2], "a*b", "__mul__")
191 self
.binop_test([1,2], 3, [1,2,1,2,1,2], "b*a", "__rmul__")
192 self
.set2op_test([1,2], 1, 3, [1,3], "a[b]=c", "__setitem__")
193 self
.set3op_test([1,2,3,4], 1, 3, [5,6], [1,5,6,4], "a[b:c]=d",
196 def test_dicts(self
):
197 # Testing dict operations...
198 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts
199 self
.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__")
201 self
.binop_test({1:2}, {2:1}, True, "a < b", "__lt__")
202 self
.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
203 self
.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
204 self
.binop_test({1:2,3:4}, 1, 2, "a[b]", "__getitem__")
213 self
.assertEqual(l
, l1
)
215 for i
in d
.__iter
__():
217 self
.assertEqual(l
, l1
)
219 for i
in dict.__iter
__(d
):
221 self
.assertEqual(l
, l1
)
223 self
.unop_test(d
, 2, "len(a)", "__len__")
224 self
.assertEqual(eval(repr(d
), {}), d
)
225 self
.assertEqual(eval(d
.__repr
__(), {}), d
)
226 self
.set2op_test({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c",
229 # Tests for unary and binary operators
230 def number_operators(self
, a
, b
, skip
=[]):
231 dict = {'a': a
, 'b': b
}
233 for name
, expr
in self
.binops
.items():
235 name
= "__%s__" % name
237 res
= eval(expr
, dict)
238 self
.binop_test(a
, b
, res
, expr
, name
)
240 for name
, expr
in self
.unops
.items():
242 name
= "__%s__" % name
244 res
= eval(expr
, dict)
245 self
.unop_test(a
, res
, expr
, name
)
248 # Testing int operations...
249 self
.number_operators(100, 3)
250 # The following crashes in Python 2.2
251 self
.assertEqual((1).__nonzero
__(), 1)
252 self
.assertEqual((0).__nonzero
__(), 0)
253 # This returns 'NotImplemented' in Python 2.2
255 def __add__(self
, other
):
256 return NotImplemented
257 self
.assertEqual(C(5L), 5)
263 self
.fail("NotImplemented should have caused TypeError")
267 except OverflowError:
270 self
.fail("should have raised OverflowError")
272 def test_longs(self
):
273 # Testing long operations...
274 self
.number_operators(100L, 3L)
276 def test_floats(self
):
277 # Testing float operations...
278 self
.number_operators(100.0, 3.0)
280 def test_complexes(self
):
281 # Testing complex operations...
282 self
.number_operators(100.0j
, 3.0j
, skip
=['lt', 'le', 'gt', 'ge',
283 'int', 'long', 'float'])
285 class Number(complex):
287 def __new__(cls
, *args
, **kwds
):
288 result
= complex.__new
__(cls
, *args
)
289 result
.prec
= kwds
.get('prec', 12)
294 return "%.*g" % (prec
, self
.real
)
296 return "%.*gj" % (prec
, self
.imag
)
297 return "(%.*g+%.*gj)" % (prec
, self
.real
, prec
, self
.imag
)
300 a
= Number(3.14, prec
=6)
301 self
.assertEqual(repr(a
), "3.14")
302 self
.assertEqual(a
.prec
, 6)
304 a
= Number(a
, prec
=2)
305 self
.assertEqual(repr(a
), "3.1")
306 self
.assertEqual(a
.prec
, 2)
309 self
.assertEqual(repr(a
), "234.5")
310 self
.assertEqual(a
.prec
, 12)
312 @test_support.impl_detail("the module 'xxsubtype' is internal")
313 def test_spam_lists(self
):
314 # Testing spamlist operations...
315 import copy
, xxsubtype
as spam
317 def spamlist(l
, memo
=None):
318 import xxsubtype
as spam
319 return spam
.spamlist(l
)
321 # This is an ugly hack:
322 copy
._deepcopy
_dispatch
[spam
.spamlist
] = spamlist
324 self
.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
326 self
.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
327 self
.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
328 self
.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
329 self
.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
331 self
.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
333 self
.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
335 self
.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
336 self
.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
338 self
.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
340 self
.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
342 self
.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
343 spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
345 class C(spam
.spamlist
):
346 def foo(self
): return 1
348 self
.assertEqual(a
, [])
349 self
.assertEqual(a
.foo(), 1)
351 self
.assertEqual(a
, [100])
352 self
.assertEqual(a
.getstate(), 0)
354 self
.assertEqual(a
.getstate(), 42)
356 @test_support.impl_detail("the module 'xxsubtype' is internal")
357 def test_spam_dicts(self
):
358 # Testing spamdict operations...
359 import copy
, xxsubtype
as spam
360 def spamdict(d
, memo
=None):
361 import xxsubtype
as spam
363 for k
, v
in d
.items():
366 # This is an ugly hack:
367 copy
._deepcopy
_dispatch
[spam
.spamdict
] = spamdict
369 self
.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
371 self
.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
372 self
.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
373 self
.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
374 d
= spamdict({1:2,3:4})
381 self
.assertEqual(l
, l1
)
383 for i
in d
.__iter
__():
385 self
.assertEqual(l
, l1
)
387 for i
in type(spamdict({})).__iter
__(d
):
389 self
.assertEqual(l
, l1
)
390 straightd
= {1:2, 3:4}
391 spamd
= spamdict(straightd
)
392 self
.unop_test(spamd
, 2, "len(a)", "__len__")
393 self
.unop_test(spamd
, repr(straightd
), "repr(a)", "__repr__")
394 self
.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
395 "a[b]=c", "__setitem__")
397 class C(spam
.spamdict
):
398 def foo(self
): return 1
400 self
.assertEqual(a
.items(), [])
401 self
.assertEqual(a
.foo(), 1)
403 self
.assertEqual(a
.items(), [('foo', 'bar')])
404 self
.assertEqual(a
.getstate(), 0)
406 self
.assertEqual(a
.getstate(), 100)
408 class ClassPropertiesAndMethods(unittest
.TestCase
):
410 def test_python_dicts(self
):
411 # Testing Python subclass of dict...
412 self
.assertTrue(issubclass(dict, dict))
413 self
.assertTrue(isinstance({}, dict))
415 self
.assertEqual(d
, {})
416 self
.assertTrue(d
.__class
__ is dict)
417 self
.assertTrue(isinstance(d
, dict))
420 def __init__(self_local
, *a
, **kw
):
422 self
.assertEqual(len(a
), 1)
423 self_local
.state
= a
[0]
425 for k
, v
in kw
.items():
427 def __getitem__(self
, key
):
428 return self
.get(key
, 0)
429 def __setitem__(self_local
, key
, value
):
430 self
.assertTrue(isinstance(key
, type(0)))
431 dict.__setitem
__(self_local
, key
, value
)
432 def setstate(self
, state
):
436 self
.assertTrue(issubclass(C
, dict))
438 self
.assertEqual(a1
.state
, 12)
440 self
.assertEqual(a2
[1] == 'foo' and a2
[2], 'bar')
442 self
.assertEqual(a
.state
, -1)
443 self
.assertEqual(a
.getstate(), -1)
445 self
.assertEqual(a
.state
, 0)
446 self
.assertEqual(a
.getstate(), 0)
448 self
.assertEqual(a
.state
, 10)
449 self
.assertEqual(a
.getstate(), 10)
450 self
.assertEqual(a
[42], 0)
452 self
.assertEqual(a
[42], 24)
460 self
.assertEqual(a
[i
][j
], i
*j
)
462 def test_python_lists(self
):
463 # Testing Python subclass of list...
465 def __getitem__(self
, i
):
466 return list.__getitem
__(self
, i
) + 100
467 def __getslice__(self
, i
, j
):
471 self
.assertEqual(a
[0], 100)
472 self
.assertEqual(a
[1], 101)
473 self
.assertEqual(a
[2], 102)
474 self
.assertEqual(a
[100:200], (100,200))
476 def test_metaclass(self
):
477 # Testing __metaclass__...
484 def setstate(self
, state
):
487 self
.assertEqual(a
.getstate(), 0)
489 self
.assertEqual(a
.getstate(), 10)
491 class __metaclass__(type):
492 def myself(cls
): return cls
493 self
.assertEqual(D
.myself(), D
)
495 self
.assertEqual(d
.__class
__, D
)
497 def __new__(cls
, name
, bases
, dict):
499 return type.__new
__(cls
, name
, bases
, dict)
502 self
.assertEqual(C
.__spam
__, 1)
504 self
.assertEqual(c
.__spam
__, 1)
506 class _instance(object):
510 def __new__(cls
, name
, bases
, dict):
511 self
= object.__new
__(cls
)
518 # Early binding of methods
519 for key
in self
.dict:
520 if key
.startswith("__"):
522 setattr(it
, key
, self
.dict[key
].__get
__(it
, self
))
528 self
.assertEqual(C
.name
, 'C')
529 self
.assertEqual(C
.bases
, ())
530 self
.assertTrue('spam' in C
.dict)
532 self
.assertEqual(c
.spam(), 42)
534 # More metaclass examples
536 class autosuper(type):
537 # Automatically add __super to the class
538 # This trick only works for dynamic classes
539 def __new__(metaclass
, name
, bases
, dict):
540 cls
= super(autosuper
, metaclass
).__new
__(metaclass
,
542 # Name mangling for __super removes leading underscores
543 while name
[:1] == "_":
546 name
= "_%s__super" % name
549 setattr(cls
, name
, super(cls
))
552 __metaclass__
= autosuper
557 return "B" + self
.__super
.meth()
560 return "C" + self
.__super
.meth()
563 return "D" + self
.__super
.meth()
564 self
.assertEqual(D().meth(), "DCBA")
567 return "E" + self
.__super
.meth()
568 self
.assertEqual(E().meth(), "EBCA")
570 class autoproperty(type):
571 # Automatically create property attributes when methods
572 # named _get_x and/or _set_x are found
573 def __new__(metaclass
, name
, bases
, dict):
575 for key
, val
in dict.iteritems():
576 if key
.startswith("_get_"):
578 get
, set = hits
.get(key
, (None, None))
581 elif key
.startswith("_set_"):
583 get
, set = hits
.get(key
, (None, None))
586 for key
, (get
, set) in hits
.iteritems():
587 dict[key
] = property(get
, set)
588 return super(autoproperty
, metaclass
).__new
__(metaclass
,
591 __metaclass__
= autoproperty
597 self
.assertTrue(not hasattr(a
, "x"))
599 self
.assertEqual(a
.x
, 12)
600 self
.assertEqual(a
._A
__x
, -12)
602 class multimetaclass(autoproperty
, autosuper
):
603 # Merge of multiple cooperating metaclasses
606 __metaclass__
= multimetaclass
611 return "B" + self
.__super
._get
_x
()
614 return "C" + self
.__super
._get
_x
()
617 return "D" + self
.__super
._get
_x
()
618 self
.assertEqual(D().x
, "DCBA")
620 # Make sure type(x) doesn't call x.__class__.__init__
623 def __init__(self
, *args
):
627 self
.assertEqual(T
.counter
, 1)
629 self
.assertEqual(type(a
), C
)
630 self
.assertEqual(T
.counter
, 1)
632 class C(object): pass
635 except TypeError: pass
636 else: self
.fail("calling object w/o call method should raise "
639 # Testing code to find most derived baseclass
641 def __new__(*args
, **kwargs
):
642 return type.__new
__(*args
, **kwargs
)
650 # The most derived metaclass of D is A rather than type.
654 def test_module_subclasses(self
):
655 # Testing Python subclass of module...
660 def __init__(self
, name
):
661 MT
.__init
__(self
, name
)
662 def __getattribute__(self
, name
):
663 log
.append(("getattr", name
))
664 return MT
.__getattribute
__(self
, name
)
665 def __setattr__(self
, name
, value
):
666 log
.append(("setattr", name
, value
))
667 MT
.__setattr
__(self
, name
, value
)
668 def __delattr__(self
, name
):
669 log
.append(("delattr", name
))
670 MT
.__delattr
__(self
, name
)
675 self
.assertEqual(log
, [("setattr", "foo", 12),
679 # http://python.org/sf/1174712
681 class Module(types
.ModuleType
, str):
686 self
.fail("inheriting from ModuleType and str at the same time "
689 def test_multiple_inheritence(self
):
690 # Testing multiple inheritance...
696 def setstate(self
, state
):
699 self
.assertEqual(a
.getstate(), 0)
701 self
.assertEqual(a
.getstate(), 10)
704 type({}).__init
__(self
)
707 self
.assertEqual(d
.keys(), [])
709 self
.assertEqual(d
.items(), [("hello", "world")])
710 self
.assertEqual(d
["hello"], "world")
711 self
.assertEqual(d
.getstate(), 0)
713 self
.assertEqual(d
.getstate(), 10)
714 self
.assertEqual(D
.__mro
__, (D
, dict, C
, object))
719 return int(self
.foo())
722 class Frag(Node
, list):
725 self
.assertEqual(Node().__int
__(), 23)
726 self
.assertEqual(int(Node()), 23)
727 self
.assertEqual(Frag().__int
__(), 42)
728 self
.assertEqual(int(Frag()), 42)
730 # MI mixing classic and new-style classes.
743 self
.assertEqual(D
.x
, 1)
745 # Classic MRO is preserved for a classic base class.
748 self
.assertEqual(E
.__mro
__, (E
, D
, B
, A
, C
, object))
749 self
.assertEqual(E
.x
, 1)
751 # But with a mix of classic bases, their MROs are combined using
753 class F(B
, C
, object):
755 self
.assertEqual(F
.__mro
__, (F
, B
, C
, A
, object))
756 self
.assertEqual(F
.x
, 2)
758 # Try something else.
762 def all_method(self
):
768 def all_method(self
):
771 self
.assertEqual(M1
.__mro__
, (M1
, C
, object))
773 self
.assertEqual(m
.cmethod(), "C a")
774 self
.assertEqual(m
.m1method(), "M1 a")
775 self
.assertEqual(m
.all_method(), "M1 b")
780 def all_method(self
):
786 def all_method(self
):
789 self
.assertEqual(M2
.__mro__
, (M2
, D
, C
, object))
791 self
.assertEqual(m
.cmethod(), "C a")
792 self
.assertEqual(m
.dmethod(), "D a")
793 self
.assertEqual(m
.m2method(), "M2 a")
794 self
.assertEqual(m
.all_method(), "M2 b")
796 class M3(M1
, M2
, object):
799 def all_method(self
):
801 self
.assertEqual(M3
.__mro__
, (M3
, M1
, M2
, D
, C
, object))
803 self
.assertEqual(m
.cmethod(), "C a")
804 self
.assertEqual(m
.dmethod(), "D a")
805 self
.assertEqual(m
.m1method(), "M1 a")
806 self
.assertEqual(m
.m2method(), "M2 a")
807 self
.assertEqual(m
.m3method(), "M3 a")
808 self
.assertEqual(m
.all_method(), "M3 b")
818 self
.fail("new class with only classic bases - shouldn't be")
820 def test_diamond_inheritence(self
):
821 # Testing multiple inheritance special cases...
823 def spam(self
): return "A"
824 self
.assertEqual(A().spam(), "A")
826 def boo(self
): return "B"
827 def spam(self
): return "B"
828 self
.assertEqual(B().spam(), "B")
829 self
.assertEqual(B().boo(), "B")
831 def boo(self
): return "C"
832 self
.assertEqual(C().spam(), "A")
833 self
.assertEqual(C().boo(), "C")
835 self
.assertEqual(D().spam(), "B")
836 self
.assertEqual(D().boo(), "B")
837 self
.assertEqual(D
.__mro
__, (D
, B
, C
, A
, object))
839 self
.assertEqual(E().spam(), "B")
840 self
.assertEqual(E().boo(), "C")
841 self
.assertEqual(E
.__mro
__, (E
, C
, B
, A
, object))
842 # MRO order disagreement
848 self
.fail("expected MRO order disagreement (F)")
854 self
.fail("expected MRO order disagreement (G)")
856 # see thread python-dev/2002-October/029035.html
857 def test_ex5_from_c3_switch(self
):
858 # Testing ex5 from C3 switch discussion...
859 class A(object): pass
860 class B(object): pass
861 class C(object): pass
864 class Z(X
,B
,Y
,C
): pass
865 self
.assertEqual(Z
.__mro
__, (Z
, X
, B
, Y
, A
, C
, object))
867 # see "A Monotonic Superclass Linearization for Dylan",
868 # by Kim Barrett et al. (OOPSLA 1996)
869 def test_monotonicity(self
):
870 # Testing MRO monotonicity...
871 class Boat(object): pass
872 class DayBoat(Boat
): pass
873 class WheelBoat(Boat
): pass
874 class EngineLess(DayBoat
): pass
875 class SmallMultihull(DayBoat
): pass
876 class PedalWheelBoat(EngineLess
,WheelBoat
): pass
877 class SmallCatamaran(SmallMultihull
): pass
878 class Pedalo(PedalWheelBoat
,SmallCatamaran
): pass
880 self
.assertEqual(PedalWheelBoat
.__mro
__,
881 (PedalWheelBoat
, EngineLess
, DayBoat
, WheelBoat
, Boat
, object))
882 self
.assertEqual(SmallCatamaran
.__mro
__,
883 (SmallCatamaran
, SmallMultihull
, DayBoat
, Boat
, object))
884 self
.assertEqual(Pedalo
.__mro
__,
885 (Pedalo
, PedalWheelBoat
, EngineLess
, SmallCatamaran
,
886 SmallMultihull
, DayBoat
, WheelBoat
, Boat
, object))
888 # see "A Monotonic Superclass Linearization for Dylan",
889 # by Kim Barrett et al. (OOPSLA 1996)
890 def test_consistency_with_epg(self
):
891 # Testing consistentcy with EPG...
892 class Pane(object): pass
893 class ScrollingMixin(object): pass
894 class EditingMixin(object): pass
895 class ScrollablePane(Pane
,ScrollingMixin
): pass
896 class EditablePane(Pane
,EditingMixin
): pass
897 class EditableScrollablePane(ScrollablePane
,EditablePane
): pass
899 self
.assertEqual(EditableScrollablePane
.__mro
__,
900 (EditableScrollablePane
, ScrollablePane
, EditablePane
, Pane
,
901 ScrollingMixin
, EditingMixin
, object))
903 def test_mro_disagreement(self
):
904 # Testing error messages for MRO disagreement...
905 mro_err_msg
= """Cannot create a consistent method resolution
906 order (MRO) for bases """
908 def raises(exc
, expected
, callable, *args
):
912 # the exact msg is generally considered an impl detail
913 if test_support
.check_impl_detail():
914 if not str(msg
).startswith(expected
):
915 self
.fail("Message %r, expected %r" %
916 (str(msg
), expected
))
918 self
.fail("Expected %s" % exc
)
920 class A(object): pass
922 class C(object): pass
924 # Test some very simple errors
925 raises(TypeError, "duplicate base class A",
926 type, "X", (A
, A
), {})
927 raises(TypeError, mro_err_msg
,
928 type, "X", (A
, B
), {})
929 raises(TypeError, mro_err_msg
,
930 type, "X", (A
, C
, B
), {})
931 # Test a slightly more complex error
932 class GridLayout(object): pass
933 class HorizontalGrid(GridLayout
): pass
934 class VerticalGrid(GridLayout
): pass
935 class HVGrid(HorizontalGrid
, VerticalGrid
): pass
936 class VHGrid(VerticalGrid
, HorizontalGrid
): pass
937 raises(TypeError, mro_err_msg
,
938 type, "ConfusedGrid", (HVGrid
, VHGrid
), {})
940 def test_object_class(self
):
941 # Testing object class...
943 self
.assertEqual(a
.__class
__, object)
944 self
.assertEqual(type(a
), object)
946 self
.assertNotEqual(a
, b
)
947 self
.assertFalse(hasattr(a
, "foo"))
950 except (AttributeError, TypeError):
953 self
.fail("object() should not allow setting a foo attribute")
954 self
.assertFalse(hasattr(object(), "__dict__"))
959 self
.assertEqual(x
.__dict
__, {})
961 self
.assertEqual(x
.foo
, 1)
962 self
.assertEqual(x
.__dict
__, {'foo': 1})
964 def test_slots(self
):
965 # Testing __slots__...
969 self
.assertFalse(hasattr(x
, "__dict__"))
970 self
.assertFalse(hasattr(x
, "foo"))
975 self
.assertFalse(hasattr(x
, "__dict__"))
976 self
.assertFalse(hasattr(x
, "a"))
978 self
.assertEqual(x
.a
, 1)
980 self
.assertEqual(x
.a
, None)
982 self
.assertFalse(hasattr(x
, "a"))
985 __slots__
= ['a', 'b', 'c']
987 self
.assertFalse(hasattr(x
, "__dict__"))
988 self
.assertFalse(hasattr(x
, 'a'))
989 self
.assertFalse(hasattr(x
, 'b'))
990 self
.assertFalse(hasattr(x
, 'c'))
994 self
.assertEqual(x
.a
, 1)
995 self
.assertEqual(x
.b
, 2)
996 self
.assertEqual(x
.c
, 3)
999 """Validate name mangling"""
1001 def __init__(self
, value
):
1006 self
.assertFalse(hasattr(x
, '__dict__'))
1007 self
.assertFalse(hasattr(x
, '__a'))
1008 self
.assertEqual(x
.get(), 5)
1011 except AttributeError:
1014 self
.fail("Double underscored names not mangled")
1016 # Make sure slot names are proper identifiers
1023 self
.fail("[None] slots not caught")
1026 __slots__
= ["foo bar"]
1030 self
.fail("['foo bar'] slots not caught")
1033 __slots__
= ["foo\0bar"]
1037 self
.fail("['foo\\0bar'] slots not caught")
1044 self
.fail("['1'] slots not caught")
1051 self
.fail("[''] slots not caught")
1053 __slots__
= ["a", "a_b", "_a", "A0123456789Z"]
1054 # XXX(nnorwitz): was there supposed to be something tested
1055 # from the class above?
1057 # Test a single string is not expanded as a sequence.
1062 self
.assertEqual(c
.abc
, 5)
1064 # Test unicode slot names
1070 # Test a single unicode string is not expanded as a sequence.
1072 __slots__
= unicode("abc")
1075 self
.assertEqual(c
.abc
, 5)
1077 # _unicode_to_string used to modify slots in certain circumstances
1078 slots
= (unicode("foo"), unicode("bar"))
1083 self
.assertEqual(x
.foo
, 5)
1084 self
.assertEqual(type(slots
[0]), unicode)
1085 # this used to leak references
1088 __slots__
= [unichr(128)]
1089 except (TypeError, UnicodeEncodeError):
1092 self
.fail("[unichr(128)] slots not caught")
1095 class Counted(object):
1096 counter
= 0 # counts the number of instances alive
1098 Counted
.counter
+= 1
1100 Counted
.counter
-= 1
1102 __slots__
= ['a', 'b', 'c']
1107 self
.assertEqual(Counted
.counter
, 3)
1109 test_support
.gc_collect()
1110 self
.assertEqual(Counted
.counter
, 0)
1116 self
.assertEqual(Counted
.counter
, 2)
1118 test_support
.gc_collect()
1119 self
.assertEqual(Counted
.counter
, 0)
1126 self
.assertEqual(Counted
.counter
, 3)
1128 test_support
.gc_collect()
1129 self
.assertEqual(Counted
.counter
, 0)
1131 # Test cyclical leaks [SF bug 519621]
1133 __slots__
= ['a', 'b']
1136 s
.a
= [Counted(), s
]
1137 self
.assertEqual(Counted
.counter
, 1)
1139 test_support
.gc_collect()
1140 self
.assertEqual(Counted
.counter
, 0)
1142 # Test lookup leaks [SF bug 572567]
1144 if hasattr(gc
, 'get_objects'):
1146 def __cmp__(self
, other
):
1148 __hash__
= None # Silence Py3k warning
1150 orig_objects
= len(gc
.get_objects())
1151 for i
in xrange(10):
1153 new_objects
= len(gc
.get_objects())
1154 self
.assertEqual(orig_objects
, new_objects
)
1157 __slots__
= ['a', 'b']
1162 self
.assertEqual(self_
.a
, 1)
1163 self
.assertEqual(self_
.b
, 2)
1164 with test_support
.captured_output('stderr') as s
:
1167 self
.assertEqual(s
.getvalue(), '')
1171 with self
.assertRaises(AttributeError):
1174 def test_slots_special(self
):
1175 # Testing __dict__ and __weakref__ in __slots__...
1177 __slots__
= ["__dict__"]
1179 self
.assertTrue(hasattr(a
, "__dict__"))
1180 self
.assertFalse(hasattr(a
, "__weakref__"))
1182 self
.assertEqual(a
.__dict
__, {"foo": 42})
1185 __slots__
= ["__weakref__"]
1187 self
.assertTrue(hasattr(a
, "__weakref__"))
1188 self
.assertFalse(hasattr(a
, "__dict__"))
1191 except AttributeError:
1194 self
.fail("shouldn't be allowed to set a.foo")
1199 self
.assertTrue(hasattr(a
, "__dict__"))
1200 self
.assertTrue(hasattr(a
, "__weakref__"))
1202 self
.assertEqual(a
.__dict
__, {"foo": 42})
1207 self
.assertTrue(hasattr(a
, "__dict__"))
1208 self
.assertTrue(hasattr(a
, "__weakref__"))
1210 self
.assertEqual(a
.__dict
__, {"foo": 42})
1212 def test_slots_descriptor(self
):
1213 # Issue2115: slot descriptors did not correctly check
1214 # the type of the given object
1217 __metaclass__
= abc
.ABCMeta
1220 class Unrelated(object):
1222 MyABC
.register(Unrelated
)
1225 self
.assertTrue(isinstance(u
, MyABC
))
1227 # This used to crash
1228 self
.assertRaises(TypeError, MyABC
.a
.__set
__, u
, 3)
1230 def test_metaclass_cmp(self
):
1233 def __cmp__(self
, other
):
1237 self
.assertTrue(X
< M
)
1239 def test_dynamics(self
):
1240 # Testing class attribute propagation...
1248 self
.assertEqual(D
.foo
, 1)
1249 # Test that dynamic attributes are inherited
1250 self
.assertEqual(E
.foo
, 1)
1251 self
.assertEqual(F
.foo
, 1)
1252 # Test dynamic instances
1256 self
.assertFalse(hasattr(a
, "foobar"))
1258 self
.assertEqual(a
.foobar
, 2)
1259 C
.method
= lambda self
: 42
1260 self
.assertEqual(a
.method(), 42)
1261 C
.__repr
__ = lambda self
: "C()"
1262 self
.assertEqual(repr(a
), "C()")
1263 C
.__int
__ = lambda self
: 100
1264 self
.assertEqual(int(a
), 100)
1265 self
.assertEqual(a
.foobar
, 2)
1266 self
.assertFalse(hasattr(a
, "spam"))
1267 def mygetattr(self
, name
):
1270 raise AttributeError
1271 C
.__getattr
__ = mygetattr
1272 self
.assertEqual(a
.spam
, "spam")
1274 self
.assertEqual(a
.new
, 12)
1275 def mysetattr(self
, name
, value
):
1277 raise AttributeError
1278 return object.__setattr
__(self
, name
, value
)
1279 C
.__setattr
__ = mysetattr
1282 except AttributeError:
1285 self
.fail("expected AttributeError")
1286 self
.assertEqual(a
.spam
, "spam")
1291 self
.assertEqual(d
.foo
, 1)
1293 # Test handling of int*seq and seq*int
1296 self
.assertEqual("a"*I(2), "aa")
1297 self
.assertEqual(I(2)*"a", "aa")
1298 self
.assertEqual(2*I(3), 6)
1299 self
.assertEqual(I(3)*2, 6)
1300 self
.assertEqual(I(3)*I(2), 6)
1302 # Test handling of long*seq and seq*long
1305 self
.assertEqual("a"*L(2L), "aa")
1306 self
.assertEqual(L(2L)*"a", "aa")
1307 self
.assertEqual(2*L(3), 6)
1308 self
.assertEqual(L(3)*2, 6)
1309 self
.assertEqual(L(3)*L(2), 6)
1311 # Test comparison of classes with dynamic metaclasses
1312 class dynamicmetaclass(type):
1315 __metaclass__
= dynamicmetaclass
1316 self
.assertNotEqual(someclass
, object)
1318 def test_errors(self
):
1321 class C(list, dict):
1326 self
.fail("inheritance from both list and dict should be illegal")
1329 class C(object, None):
1334 self
.fail("inheritance from non-type should be illegal")
1344 self
.fail("inheritance from CFunction should be illegal")
1352 self
.fail("__slots__ = 1 should be illegal")
1360 self
.fail("__slots__ = [1] should be illegal")
1376 self
.fail("finding the most derived metaclass should have failed")
1378 def test_classmethods(self
):
1379 # Testing class methods...
1381 def foo(*a
): return a
1382 goo
= classmethod(foo
)
1384 self
.assertEqual(C
.goo(1), (C
, 1))
1385 self
.assertEqual(c
.goo(1), (C
, 1))
1386 self
.assertEqual(c
.foo(1), (c
, 1))
1390 self
.assertEqual(D
.goo(1), (D
, 1))
1391 self
.assertEqual(d
.goo(1), (D
, 1))
1392 self
.assertEqual(d
.foo(1), (d
, 1))
1393 self
.assertEqual(D
.foo(d
, 1), (d
, 1))
1394 # Test for a specific crash (SF bug 528132)
1395 def f(cls
, arg
): return (cls
, arg
)
1397 self
.assertEqual(ff
.__get
__(0, int)(42), (int, 42))
1398 self
.assertEqual(ff
.__get
__(0)(42), (int, 42))
1400 # Test super() with classmethods (SF bug 535444)
1401 self
.assertEqual(C
.goo
.im_self
, C
)
1402 self
.assertEqual(D
.goo
.im_self
, D
)
1403 self
.assertEqual(super(D
,D
).goo
.im_self
, D
)
1404 self
.assertEqual(super(D
,d
).goo
.im_self
, D
)
1405 self
.assertEqual(super(D
,D
).goo(), (D
,))
1406 self
.assertEqual(super(D
,d
).goo(), (D
,))
1408 # Verify that a non-callable will raise
1409 meth
= classmethod(1).__get
__(1)
1410 self
.assertRaises(TypeError, meth
)
1412 # Verify that classmethod() doesn't allow keyword args
1414 classmethod(f
, kw
=1)
1418 self
.fail("classmethod shouldn't accept keyword args")
1420 @test_support.impl_detail("the module 'xxsubtype' is internal")
1421 def test_classmethods_in_c(self
):
1422 # Testing C-based class methods...
1423 import xxsubtype
as spam
1426 x
, a1
, d1
= spam
.spamlist
.classmeth(*a
, **d
)
1427 self
.assertEqual(x
, spam
.spamlist
)
1428 self
.assertEqual(a
, a1
)
1429 self
.assertEqual(d
, d1
)
1430 x
, a1
, d1
= spam
.spamlist().classmeth(*a
, **d
)
1431 self
.assertEqual(x
, spam
.spamlist
)
1432 self
.assertEqual(a
, a1
)
1433 self
.assertEqual(d
, d1
)
1435 def test_staticmethods(self
):
1436 # Testing static methods...
1438 def foo(*a
): return a
1439 goo
= staticmethod(foo
)
1441 self
.assertEqual(C
.goo(1), (1,))
1442 self
.assertEqual(c
.goo(1), (1,))
1443 self
.assertEqual(c
.foo(1), (c
, 1,))
1447 self
.assertEqual(D
.goo(1), (1,))
1448 self
.assertEqual(d
.goo(1), (1,))
1449 self
.assertEqual(d
.foo(1), (d
, 1))
1450 self
.assertEqual(D
.foo(d
, 1), (d
, 1))
1452 @test_support.impl_detail("the module 'xxsubtype' is internal")
1453 def test_staticmethods_in_c(self
):
1454 # Testing C-based static methods...
1455 import xxsubtype
as spam
1458 x
, a1
, d1
= spam
.spamlist
.staticmeth(*a
, **d
)
1459 self
.assertEqual(x
, None)
1460 self
.assertEqual(a
, a1
)
1461 self
.assertEqual(d
, d1
)
1462 x
, a1
, d2
= spam
.spamlist().staticmeth(*a
, **d
)
1463 self
.assertEqual(x
, None)
1464 self
.assertEqual(a
, a1
)
1465 self
.assertEqual(d
, d1
)
1467 def test_classic(self
):
1468 # Testing classic classes...
1470 def foo(*a
): return a
1471 goo
= classmethod(foo
)
1473 self
.assertEqual(C
.goo(1), (C
, 1))
1474 self
.assertEqual(c
.goo(1), (C
, 1))
1475 self
.assertEqual(c
.foo(1), (c
, 1))
1479 self
.assertEqual(D
.goo(1), (D
, 1))
1480 self
.assertEqual(d
.goo(1), (D
, 1))
1481 self
.assertEqual(d
.foo(1), (d
, 1))
1482 self
.assertEqual(D
.foo(d
, 1), (d
, 1))
1483 class E
: # *not* subclassing from C
1485 self
.assertEqual(E().foo
, C
.foo
) # i.e., unbound
1486 self
.assertTrue(repr(C
.foo
.__get
__(C())).startswith("<bound method "))
1488 def test_compattr(self
):
1489 # Testing computed attributes...
1491 class computed_attribute(object):
1492 def __init__(self
, get
, set=None, delete
=None):
1495 self
.__delete
= delete
1496 def __get__(self
, obj
, type=None):
1497 return self
.__get
(obj
)
1498 def __set__(self
, obj
, value
):
1499 return self
.__set
(obj
, value
)
1500 def __delete__(self
, obj
):
1501 return self
.__delete
(obj
)
1508 def __set_x(self
, x
):
1510 def __delete_x(self
):
1512 x
= computed_attribute(__get_x
, __set_x
, __delete_x
)
1514 self
.assertEqual(a
.x
, 0)
1515 self
.assertEqual(a
.x
, 1)
1517 self
.assertEqual(a
.x
, 10)
1518 self
.assertEqual(a
.x
, 11)
1520 self
.assertEqual(hasattr(a
, 'x'), 0)
1522 def test_newslots(self
):
1523 # Testing __new__ slot override...
1526 self
= list.__new
__(cls
)
1530 self
.foo
= self
.foo
+ 2
1532 self
.assertEqual(a
.foo
, 3)
1533 self
.assertEqual(a
.__class
__, C
)
1537 self
.assertEqual(b
.foo
, 3)
1538 self
.assertEqual(b
.__class
__, D
)
1540 def test_altmro(self
):
1541 # Testing mro() and overriding it...
1543 def f(self
): return "A"
1547 def f(self
): return "C"
1550 self
.assertEqual(D
.mro(), [D
, B
, C
, A
, object])
1551 self
.assertEqual(D
.__mro
__, (D
, B
, C
, A
, object))
1552 self
.assertEqual(D().f(), "C")
1554 class PerverseMetaType(type):
1560 __metaclass__
= PerverseMetaType
1561 self
.assertEqual(X
.__mro
__, (object, A
, C
, B
, D
, X
))
1562 self
.assertEqual(X().f(), "A")
1566 class __metaclass__(type):
1568 return [self
, dict, object]
1569 # In CPython, the class creation above already raises
1570 # TypeError, as a protection against the fact that
1571 # instances of X would segfault it. In other Python
1572 # implementations it would be ok to let the class X
1573 # be created, but instead get a clean TypeError on the
1574 # __setitem__ below.
1575 x
= object.__new
__(X
)
1580 self
.fail("devious mro() return not caught")
1584 class __metaclass__(type):
1590 self
.fail("non-class mro() return not caught")
1594 class __metaclass__(type):
1600 self
.fail("non-sequence mro() return not caught")
1602 def test_overloading(self
):
1603 # Testing operator overloading...
1606 "Intermediate class because object doesn't have a __setattr__"
1609 def __getattr__(self
, name
):
1611 return ("getattr", name
)
1613 raise AttributeError
1614 def __setattr__(self
, name
, value
):
1616 self
.setattr = (name
, value
)
1618 return B
.__setattr
__(self
, name
, value
)
1619 def __delattr__(self
, name
):
1623 return B
.__delattr
__(self
, name
)
1625 def __getitem__(self
, key
):
1626 return ("getitem", key
)
1627 def __setitem__(self
, key
, value
):
1628 self
.setitem
= (key
, value
)
1629 def __delitem__(self
, key
):
1632 def __getslice__(self
, i
, j
):
1633 return ("getslice", i
, j
)
1634 def __setslice__(self
, i
, j
, value
):
1635 self
.setslice
= (i
, j
, value
)
1636 def __delslice__(self
, i
, j
):
1637 self
.delslice
= (i
, j
)
1640 self
.assertEqual(a
.foo
, ("getattr", "foo"))
1642 self
.assertEqual(a
.setattr, ("foo", 12))
1644 self
.assertEqual(a
.delattr, "foo")
1646 self
.assertEqual(a
[12], ("getitem", 12))
1648 self
.assertEqual(a
.setitem
, (12, 21))
1650 self
.assertEqual(a
.delitem
, 12)
1652 self
.assertEqual(a
[0:10], ("getslice", 0, 10))
1654 self
.assertEqual(a
.setslice
, (0, 10, "foo"))
1656 self
.assertEqual(a
.delslice
, (0, 10))
1658 def test_methods(self
):
1659 # Testing methods...
1661 def __init__(self
, x
):
1666 self
.assertEqual(c1
.foo(), 1)
1671 self
.assertEqual(d2
.foo(), 2)
1672 self
.assertEqual(d2
.boo(), 2)
1673 self
.assertEqual(d2
.goo(), 1)
1676 self
.assertEqual(E().foo
, C
.foo
) # i.e., unbound
1677 self
.assertTrue(repr(C
.foo
.__get
__(C(1))).startswith("<bound method "))
1679 def test_special_method_lookup(self
):
1680 # The lookup of special methods bypasses __getattr__ and
1681 # __getattribute__, but they still can be descriptors.
1683 def run_context(manager
):
1690 def empty_seq(self
):
1694 def complex_num(self
):
1698 def return_true(self
, thing
=None):
1700 def do_isinstance(obj
):
1701 return isinstance(int, obj
)
1702 def do_issubclass(obj
):
1703 return issubclass(int, obj
)
1706 def do_dict_missing(checker
):
1707 class DictSub(checker
.__class
__, dict):
1709 self
.assertEqual(DictSub()["hi"], 4)
1710 def some_number(self_
, key
):
1711 self
.assertEqual(key
, "hi")
1714 # It would be nice to have every special method tested here, but I'm
1715 # only listing the ones I can remember outside of typeobject.c, since it
1718 ("__unicode__", unicode, hello
, set(), {}),
1719 ("__reversed__", reversed, empty_seq
, set(), {}),
1720 ("__length_hint__", list, zero
, set(),
1721 {"__iter__" : iden
, "next" : stop
}),
1722 ("__sizeof__", sys
.getsizeof
, zero
, set(), {}),
1723 ("__instancecheck__", do_isinstance
, return_true
, set(), {}),
1724 ("__missing__", do_dict_missing
, some_number
,
1725 set(("__class__",)), {}),
1726 ("__subclasscheck__", do_issubclass
, return_true
,
1727 set(("__bases__",)), {}),
1728 ("__enter__", run_context
, iden
, set(), {"__exit__" : swallow
}),
1729 ("__exit__", run_context
, swallow
, set(), {"__enter__" : iden
}),
1730 ("__complex__", complex, complex_num
, set(), {}),
1733 class Checker(object):
1734 def __getattr__(self
, attr
, test
=self
):
1735 test
.fail("__getattr__ called with {0}".format(attr
))
1736 def __getattribute__(self
, attr
, test
=self
):
1738 test
.fail("__getattribute__ called with {0}".format(attr
))
1739 return object.__getattribute
__(self
, attr
)
1740 class SpecialDescr(object):
1741 def __init__(self
, impl
):
1743 def __get__(self
, obj
, owner
):
1745 return self
.impl
.__get
__(obj
, owner
)
1746 class MyException(Exception):
1748 class ErrDescr(object):
1749 def __get__(self
, obj
, owner
):
1752 for name
, runner
, meth_impl
, ok
, env
in specials
:
1755 for attr
, obj
in env
.iteritems():
1756 setattr(X
, attr
, obj
)
1757 setattr(X
, name
, meth_impl
)
1763 for attr
, obj
in env
.iteritems():
1764 setattr(X
, attr
, obj
)
1765 setattr(X
, name
, SpecialDescr(meth_impl
))
1767 self
.assertEqual(record
, [1], name
)
1771 for attr
, obj
in env
.iteritems():
1772 setattr(X
, attr
, obj
)
1773 setattr(X
, name
, ErrDescr())
1779 self
.fail("{0!r} didn't raise".format(name
))
1781 def test_specials(self
):
1782 # Testing special operators...
1783 # Test operators like __hash__ for which a built-in default exists
1785 # Test the default behavior for static classes
1787 def __getitem__(self
, i
):
1788 if 0 <= i
< 10: return i
1792 self
.assertTrue(not not c1
) # What?
1793 self
.assertNotEqual(id(c1
), id(c2
))
1796 self
.assertEqual(cmp(c1
, c2
), cmp(id(c1
), id(c2
)))
1797 self
.assertEqual(c1
, c1
)
1798 self
.assertTrue(c1
!= c2
)
1799 self
.assertTrue(not c1
!= c1
)
1800 self
.assertTrue(not c1
== c2
)
1801 # Note that the module name appears in str/repr, and that varies
1802 # depending on whether this test is run standalone or from a framework.
1803 self
.assertTrue(str(c1
).find('C object at ') >= 0)
1804 self
.assertEqual(str(c1
), repr(c1
))
1805 self
.assertTrue(-1 not in c1
)
1807 self
.assertTrue(i
in c1
)
1808 self
.assertFalse(10 in c1
)
1809 # Test the default behavior for dynamic classes
1811 def __getitem__(self
, i
):
1812 if 0 <= i
< 10: return i
1816 self
.assertTrue(not not d1
)
1817 self
.assertNotEqual(id(d1
), id(d2
))
1820 self
.assertEqual(cmp(d1
, d2
), cmp(id(d1
), id(d2
)))
1821 self
.assertEqual(d1
, d1
)
1822 self
.assertNotEqual(d1
, d2
)
1823 self
.assertTrue(not d1
!= d1
)
1824 self
.assertTrue(not d1
== d2
)
1825 # Note that the module name appears in str/repr, and that varies
1826 # depending on whether this test is run standalone or from a framework.
1827 self
.assertTrue(str(d1
).find('D object at ') >= 0)
1828 self
.assertEqual(str(d1
), repr(d1
))
1829 self
.assertTrue(-1 not in d1
)
1831 self
.assertTrue(i
in d1
)
1832 self
.assertFalse(10 in d1
)
1833 # Test overridden behavior for static classes
1834 class Proxy(object):
1835 def __init__(self
, x
):
1837 def __nonzero__(self
):
1838 return not not self
.x
1841 def __eq__(self
, other
):
1842 return self
.x
== other
1843 def __ne__(self
, other
):
1844 return self
.x
!= other
1845 def __cmp__(self
, other
):
1846 return cmp(self
.x
, other
.x
)
1848 return "Proxy:%s" % self
.x
1850 return "Proxy(%r)" % self
.x
1851 def __contains__(self
, value
):
1852 return value
in self
.x
1856 self
.assertFalse(p0
)
1857 self
.assertTrue(not not p1
)
1858 self
.assertEqual(hash(p0
), hash(0))
1859 self
.assertEqual(p0
, p0
)
1860 self
.assertNotEqual(p0
, p1
)
1861 self
.assertTrue(not p0
!= p0
)
1862 self
.assertEqual(not p0
, p1
)
1863 self
.assertEqual(cmp(p0
, p1
), -1)
1864 self
.assertEqual(cmp(p0
, p0
), 0)
1865 self
.assertEqual(cmp(p0
, p_1
), 1)
1866 self
.assertEqual(str(p0
), "Proxy:0")
1867 self
.assertEqual(repr(p0
), "Proxy(0)")
1868 p10
= Proxy(range(10))
1869 self
.assertFalse(-1 in p10
)
1871 self
.assertTrue(i
in p10
)
1872 self
.assertFalse(10 in p10
)
1873 # Test overridden behavior for dynamic classes
1874 class DProxy(object):
1875 def __init__(self
, x
):
1877 def __nonzero__(self
):
1878 return not not self
.x
1881 def __eq__(self
, other
):
1882 return self
.x
== other
1883 def __ne__(self
, other
):
1884 return self
.x
!= other
1885 def __cmp__(self
, other
):
1886 return cmp(self
.x
, other
.x
)
1888 return "DProxy:%s" % self
.x
1890 return "DProxy(%r)" % self
.x
1891 def __contains__(self
, value
):
1892 return value
in self
.x
1896 self
.assertFalse(p0
)
1897 self
.assertTrue(not not p1
)
1898 self
.assertEqual(hash(p0
), hash(0))
1899 self
.assertEqual(p0
, p0
)
1900 self
.assertNotEqual(p0
, p1
)
1901 self
.assertNotEqual(not p0
, p0
)
1902 self
.assertEqual(not p0
, p1
)
1903 self
.assertEqual(cmp(p0
, p1
), -1)
1904 self
.assertEqual(cmp(p0
, p0
), 0)
1905 self
.assertEqual(cmp(p0
, p_1
), 1)
1906 self
.assertEqual(str(p0
), "DProxy:0")
1907 self
.assertEqual(repr(p0
), "DProxy(0)")
1908 p10
= DProxy(range(10))
1909 self
.assertFalse(-1 in p10
)
1911 self
.assertTrue(i
in p10
)
1912 self
.assertFalse(10 in p10
)
1914 # Safety test for __cmp__
1915 def unsafecmp(a
, b
):
1916 if not hasattr(a
, '__cmp__'):
1917 return # some types don't have a __cmp__ any more (so the
1918 # test doesn't make sense any more), or maybe they
1919 # never had a __cmp__ at all, e.g. in PyPy
1921 a
.__class
__.__cmp
__(a
, b
)
1925 self
.fail("shouldn't allow %s.__cmp__(%r, %r)" % (
1928 unsafecmp(u
"123", "123")
1929 unsafecmp("123", u
"123")
1935 @test_support.impl_detail("custom logic for printing to real file objects")
1936 def test_recursions_1(self
):
1937 # Testing recursion checks ...
1939 def __new__(cls
, letter
):
1941 return str.__new
__(cls
)
1942 return str.__new
__(cls
, letter
)
1947 # sys.stdout needs to be the original to trigger the recursion bug
1949 test_stdout
= sys
.stdout
1950 sys
.stdout
= test_support
.get_original_stdout()
1952 # nothing should actually be printed, this should raise an exception
1954 except RuntimeError:
1957 self
.fail("expected a RuntimeError for print recursion")
1959 sys
.stdout
= test_stdout
1961 def test_recursions_2(self
):
1965 A
.__mul
__ = types
.MethodType(lambda self
, x
: self
* x
, None, A
)
1968 except RuntimeError:
1971 self
.fail("expected a RuntimeError")
1973 def test_weakrefs(self
):
1974 # Testing weak references...
1980 self
.assertEqual(r(), c
)
1982 test_support
.gc_collect()
1983 self
.assertEqual(r(), None)
1985 class NoWeak(object):
1990 except TypeError, msg
:
1991 self
.assertTrue(str(msg
).find("weak reference") >= 0)
1993 self
.fail("weakref.ref(no) should be illegal")
1995 __slots__
= ['foo', '__weakref__']
1997 r
= weakref
.ref(yes
)
1998 self
.assertEqual(r(), yes
)
2000 test_support
.gc_collect()
2001 self
.assertEqual(r(), None)
2004 def test_properties(self
):
2005 # Testing property...
2009 def setx(self
, value
):
2013 x
= property(getx
, setx
, delx
, doc
="I'm the x property.")
2015 self
.assertFalse(hasattr(a
, "x"))
2017 self
.assertEqual(a
._C
__x
, 42)
2018 self
.assertEqual(a
.x
, 42)
2020 self
.assertFalse(hasattr(a
, "x"))
2021 self
.assertFalse(hasattr(a
, "_C__x"))
2023 self
.assertEqual(C
.x
.__get
__(a
), 100)
2025 self
.assertFalse(hasattr(a
, "x"))
2027 raw
= C
.__dict
__['x']
2028 self
.assertTrue(isinstance(raw
, property))
2031 self
.assertTrue("__doc__" in attrs
)
2032 self
.assertTrue("fget" in attrs
)
2033 self
.assertTrue("fset" in attrs
)
2034 self
.assertTrue("fdel" in attrs
)
2036 self
.assertEqual(raw
.__doc
__, "I'm the x property.")
2037 self
.assertTrue(raw
.fget
is C
.__dict
__['getx'])
2038 self
.assertTrue(raw
.fset
is C
.__dict
__['setx'])
2039 self
.assertTrue(raw
.fdel
is C
.__dict
__['delx'])
2041 for attr
in "__doc__", "fget", "fset", "fdel":
2043 setattr(raw
, attr
, 42)
2044 except TypeError, msg
:
2045 if str(msg
).find('readonly') < 0:
2046 self
.fail("when setting readonly attr %r on a property, "
2047 "got unexpected TypeError msg %r" % (attr
, str(msg
)))
2049 self
.fail("expected TypeError from trying to set readonly %r "
2050 "attr on a property" % attr
)
2053 __getitem__
= property(lambda s
: 1/0)
2059 except ZeroDivisionError:
2062 self
.fail("expected ZeroDivisionError from bad property")
2068 def setter(self_
, value
):
2071 prop
= property(getter
)
2072 self
.assertEqual(prop
.__doc
__, "getter method")
2073 prop2
= property(fset
=setter
)
2074 self
.assertEqual(prop2
.__doc__
, None)
2076 # this segfaulted in 2.5b2
2083 p
= property(_testcapi
.test_with_docstring
)
2085 def test_properties_plus(self
):
2087 foo
= property(doc
="hello")
2092 def foo(self
, value
):
2093 self
._foo
= abs(value
)
2098 self
.assertEqual(C
.foo
.__doc
__, "hello")
2099 self
.assertFalse(hasattr(c
, "foo"))
2101 self
.assertTrue(hasattr(c
, '_foo'))
2102 self
.assertEqual(c
._foo
, 42)
2103 self
.assertEqual(c
.foo
, 42)
2105 self
.assertFalse(hasattr(c
, '_foo'))
2106 self
.assertFalse(hasattr(c
, "foo"))
2113 except AttributeError:
2117 self
.assertEqual(d
.foo
, 24)
2126 def foo(self
, value
):
2129 def foo(self
, value
):
2130 self
._foo
= abs(value
)
2132 def foo(self
, value
=None):
2137 self
.assertEqual(e
.foo
, 42)
2145 def foo(self
, value
):
2146 self
._foo
= max(0, value
)
2149 self
.assertEqual(f
.foo
, 0)
2152 def test_dict_constructors(self
):
2153 # Testing dict constructor ...
2155 self
.assertEqual(d
, {})
2157 self
.assertEqual(d
, {})
2158 d
= dict({1: 2, 'a': 'b'})
2159 self
.assertEqual(d
, {1: 2, 'a': 'b'})
2160 self
.assertEqual(d
, dict(d
.items()))
2161 self
.assertEqual(d
, dict(d
.iteritems()))
2162 d
= dict({'one':1, 'two':2})
2163 self
.assertEqual(d
, dict(one
=1, two
=2))
2164 self
.assertEqual(d
, dict(**d
))
2165 self
.assertEqual(d
, dict({"one": 1}, two
=2))
2166 self
.assertEqual(d
, dict([("two", 2)], one
=1))
2167 self
.assertEqual(d
, dict([("one", 100), ("two", 200)], **d
))
2168 self
.assertEqual(d
, dict(**d
))
2170 for badarg
in 0, 0L, 0j
, "0", [0], (0,):
2177 # It's a sequence, and its elements are also sequences (gotta
2178 # love strings <wink>), but they aren't of length 2, so this
2179 # one seemed better as a ValueError than a TypeError.
2182 self
.fail("no TypeError from dict(%r)" % badarg
)
2184 self
.fail("no TypeError from dict(%r)" % badarg
)
2191 self
.fail("no TypeError from dict({}, {})")
2194 # Lacks a .keys() method; will be added later.
2195 dict = {1:2, 3:4, 'a':1j
}
2202 self
.fail("no TypeError from dict(incomplete mapping)")
2204 Mapping
.keys
= lambda self
: self
.dict.keys()
2205 Mapping
.__getitem
__ = lambda self
, i
: self
.dict[i
]
2207 self
.assertEqual(d
, Mapping
.dict)
2209 # Init from sequence of iterable objects, each producing a 2-sequence.
2210 class AddressBookEntry
:
2211 def __init__(self
, first
, last
):
2215 return iter([self
.first
, self
.last
])
2217 d
= dict([AddressBookEntry('Tim', 'Warsaw'),
2218 AddressBookEntry('Barry', 'Peters'),
2219 AddressBookEntry('Tim', 'Peters'),
2220 AddressBookEntry('Barry', 'Warsaw')])
2221 self
.assertEqual(d
, {'Barry': 'Warsaw', 'Tim': 'Peters'})
2223 d
= dict(zip(range(4), range(1, 5)))
2224 self
.assertEqual(d
, dict([(i
, i
+1) for i
in range(4)]))
2226 # Bad sequence lengths.
2227 for bad
in [('tooshort',)], [('too', 'long', 'by 1')]:
2233 self
.fail("no ValueError from dict(%r)" % bad
)
2238 self
.assertEqual(dir(), ['junk', 'self'])
2241 # Just make sure these don't blow up!
2242 for arg
in 2, 2L, 2j
, 2e0
, [2], "2", u
"2", (2,), {2:2}, type, self
.test_dir
:
2245 # Try classic classes.
2248 def Cmethod(self
): pass
2250 cstuff
= ['Cdata', 'Cmethod', '__doc__', '__module__']
2251 self
.assertEqual(dir(C
), cstuff
)
2252 self
.assertTrue('im_self' in dir(C
.Cmethod
))
2254 c
= C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
2255 self
.assertEqual(dir(c
), cstuff
)
2258 c
.cmethod
= lambda self
: 0
2259 self
.assertEqual(dir(c
), cstuff
+ ['cdata', 'cmethod'])
2260 self
.assertTrue('im_self' in dir(c
.Cmethod
))
2264 def Amethod(self
): pass
2266 astuff
= ['Adata', 'Amethod'] + cstuff
2267 self
.assertEqual(dir(A
), astuff
)
2268 self
.assertTrue('im_self' in dir(A
.Amethod
))
2270 self
.assertEqual(dir(a
), astuff
)
2271 self
.assertTrue('im_self' in dir(a
.Amethod
))
2273 a
.amethod
= lambda self
: 3
2274 self
.assertEqual(dir(a
), astuff
+ ['adata', 'amethod'])
2276 # The same, but with new-style classes. Since these have object as a
2277 # base class, a lot more gets sucked in.
2278 def interesting(strings
):
2279 return [s
for s
in strings
if not s
.startswith('_')]
2283 def Cmethod(self
): pass
2285 cstuff
= ['Cdata', 'Cmethod']
2286 self
.assertEqual(interesting(dir(C
)), cstuff
)
2289 self
.assertEqual(interesting(dir(c
)), cstuff
)
2290 self
.assertTrue('im_self' in dir(C
.Cmethod
))
2293 c
.cmethod
= lambda self
: 0
2294 self
.assertEqual(interesting(dir(c
)), cstuff
+ ['cdata', 'cmethod'])
2295 self
.assertTrue('im_self' in dir(c
.Cmethod
))
2299 def Amethod(self
): pass
2301 astuff
= ['Adata', 'Amethod'] + cstuff
2302 self
.assertEqual(interesting(dir(A
)), astuff
)
2303 self
.assertTrue('im_self' in dir(A
.Amethod
))
2305 self
.assertEqual(interesting(dir(a
)), astuff
)
2307 a
.amethod
= lambda self
: 3
2308 self
.assertEqual(interesting(dir(a
)), astuff
+ ['adata', 'amethod'])
2309 self
.assertTrue('im_self' in dir(a
.Amethod
))
2311 # Try a module subclass.
2318 names
= [x
for x
in dir(minstance
) if x
not in ["__name__", "__doc__"]]
2319 self
.assertEqual(names
, ['a', 'b'])
2323 return "Not a dict!"
2324 __dict__
= property(getdict
)
2326 m2instance
= M2("m2")
2329 self
.assertEqual(m2instance
.__dict
__, "Not a dict!")
2335 # Two essentially featureless objects, just inheriting stuff from
2337 self
.assertEqual(dir(NotImplemented), dir(Ellipsis))
2338 if test_support
.check_impl_detail():
2339 # None differs in PyPy: it has a __nonzero__
2340 self
.assertEqual(dir(None), dir(Ellipsis))
2342 # Nasty test case for proxied objects
2343 class Wrapper(object):
2344 def __init__(self
, obj
):
2347 return "Wrapper(%s)" % repr(self
.__obj
)
2348 def __getitem__(self
, key
):
2349 return Wrapper(self
.__obj
[key
])
2351 return len(self
.__obj
)
2352 def __getattr__(self
, name
):
2353 return Wrapper(getattr(self
.__obj
, name
))
2356 def __getclass(self
):
2357 return Wrapper(type(self
))
2358 __class__
= property(__getclass
)
2360 dir(C()) # This used to segfault
2362 def test_supers(self
):
2369 self
.assertEqual(A().meth(1), "A(1)")
2373 self
.__super
= super(B
, self
)
2375 return "B(%r)" % a
+ self
.__super
.meth(a
)
2377 self
.assertEqual(B().meth(2), "B(2)A(2)")
2381 return "C(%r)" % a
+ self
.__super
.meth(a
)
2382 C
._C
__super
= super(C
)
2384 self
.assertEqual(C().meth(3), "C(3)A(3)")
2388 return "D(%r)" % a
+ super(D
, self
).meth(a
)
2390 self
.assertEqual(D().meth(4), "D(4)C(4)B(4)A(4)")
2392 # Test for subclassing super
2394 class mysuper(super):
2395 def __init__(self
, *args
):
2396 return super(mysuper
, self
).__init
__(*args
)
2400 return "E(%r)" % a
+ mysuper(E
, self
).meth(a
)
2402 self
.assertEqual(E().meth(5), "E(5)D(5)C(5)B(5)A(5)")
2406 s
= self
.__super
# == mysuper(F, self)
2407 return "F(%r)[%s]" % (a
, s
.__class
__.__name
__) + s
.meth(a
)
2408 F
._F
__super
= mysuper(F
)
2410 self
.assertEqual(F().meth(6), "F(6)[mysuper]E(6)D(6)C(6)B(6)A(6)")
2412 # Make sure certain errors are raised
2419 self
.fail("shouldn't allow super(D, 42)")
2426 self
.fail("shouldn't allow super(D, C())")
2429 super(D
).__get
__(12)
2433 self
.fail("shouldn't allow super(D).__get__(12)")
2436 super(D
).__get
__(C())
2440 self
.fail("shouldn't allow super(D).__get__(C())")
2442 # Make sure data descriptors can be overridden and accessed via super
2443 # (new feature in Python 2.3)
2445 class DDbase(object):
2446 def getx(self
): return 42
2449 class DDsub(DDbase
):
2450 def getx(self
): return "hello"
2454 self
.assertEqual(dd
.x
, "hello")
2455 self
.assertEqual(super(DDsub
, dd
).x
, 42)
2457 # Ensure that super() lookup of descriptor from classmethod
2458 # works (SF ID# 743627)
2461 aProp
= property(lambda self
: "foo")
2466 return super(Sub
,klass
).aProp
2468 self
.assertEqual(Sub
.test(), Base
.aProp
)
2470 # Verify that super() doesn't allow keyword args
2476 self
.assertEqual("super shouldn't accept keyword args")
2478 def test_basic_inheritance(self
):
2479 # Testing inheritance from basic types...
2484 def __add__(self
, other
):
2485 return hexint(int.__add
__(self
, other
))
2486 # (Note that overriding __radd__ doesn't work,
2487 # because the int type gets first dibs.)
2488 self
.assertEqual(repr(hexint(7) + 9), "0x10")
2489 self
.assertEqual(repr(hexint(1000) + 7), "0x3ef")
2491 self
.assertEqual(a
, 12345)
2492 self
.assertEqual(int(a
), 12345)
2493 self
.assertTrue(int(a
).__class
__ is int)
2494 self
.assertEqual(hash(a
), hash(12345))
2495 self
.assertTrue((+a
).__class
__ is int)
2496 self
.assertTrue((a
>> 0).__class
__ is int)
2497 self
.assertTrue((a
<< 0).__class
__ is int)
2498 self
.assertTrue((hexint(0) << 12).__class
__ is int)
2499 self
.assertTrue((hexint(0) >> 12).__class
__ is int)
2501 class octlong(long):
2508 def __add__(self
, other
):
2509 return self
.__class
__(super(octlong
, self
).__add
__(other
))
2511 self
.assertEqual(str(octlong(3) + 5), "010")
2512 # (Note that overriding __radd__ here only seems to work
2513 # because the example uses a short int left argument.)
2514 self
.assertEqual(str(5 + octlong(3000)), "05675")
2516 self
.assertEqual(a
, 12345L)
2517 self
.assertEqual(long(a
), 12345L)
2518 self
.assertEqual(hash(a
), hash(12345L))
2519 self
.assertTrue(long(a
).__class
__ is long)
2520 self
.assertTrue((+a
).__class
__ is long)
2521 self
.assertTrue((-a
).__class
__ is long)
2522 self
.assertTrue((-octlong(0)).__class
__ is long)
2523 self
.assertTrue((a
>> 0).__class
__ is long)
2524 self
.assertTrue((a
<< 0).__class
__ is long)
2525 self
.assertTrue((a
- 0).__class
__ is long)
2526 self
.assertTrue((a
* 1).__class
__ is long)
2527 self
.assertTrue((a
** 1).__class
__ is long)
2528 self
.assertTrue((a
// 1).__class
__ is long)
2529 self
.assertTrue((1 * a
).__class
__ is long)
2530 self
.assertTrue((a |
0).__class
__ is long)
2531 self
.assertTrue((a ^
0).__class
__ is long)
2532 self
.assertTrue((a
& -1L).__class
__ is long)
2533 self
.assertTrue((octlong(0) << 12).__class
__ is long)
2534 self
.assertTrue((octlong(0) >> 12).__class
__ is long)
2535 self
.assertTrue(abs(octlong(0)).__class
__ is long)
2537 # Because octlong overrides __add__, we can't check the absence of +0
2538 # optimizations using octlong.
2539 class longclone(long):
2542 self
.assertTrue((a
+ 0).__class
__ is long)
2543 self
.assertTrue((0 + a
).__class
__ is long)
2545 # Check that negative clones don't segfault
2547 self
.assertEqual(a
.__dict
__, {})
2548 self
.assertEqual(long(a
), -1) # self.assertTrue PyNumber_Long() copies the sign bit
2550 class precfloat(float):
2551 __slots__
= ['prec']
2552 def __init__(self
, value
=0.0, prec
=12):
2553 self
.prec
= int(prec
)
2555 return "%.*g" % (self
.prec
, self
)
2556 self
.assertEqual(repr(precfloat(1.1)), "1.1")
2557 a
= precfloat(12345)
2558 self
.assertEqual(a
, 12345.0)
2559 self
.assertEqual(float(a
), 12345.0)
2560 self
.assertTrue(float(a
).__class
__ is float)
2561 self
.assertEqual(hash(a
), hash(12345.0))
2562 self
.assertTrue((+a
).__class
__ is float)
2564 class madcomplex(complex):
2566 return "%.17gj%+.17g" % (self
.imag
, self
.real
)
2567 a
= madcomplex(-3, 4)
2568 self
.assertEqual(repr(a
), "4j-3")
2569 base
= complex(-3, 4)
2570 self
.assertEqual(base
.__class
__, complex)
2571 self
.assertEqual(a
, base
)
2572 self
.assertEqual(complex(a
), base
)
2573 self
.assertEqual(complex(a
).__class
__, complex)
2574 a
= madcomplex(a
) # just trying another form of the constructor
2575 self
.assertEqual(repr(a
), "4j-3")
2576 self
.assertEqual(a
, base
)
2577 self
.assertEqual(complex(a
), base
)
2578 self
.assertEqual(complex(a
).__class
__, complex)
2579 self
.assertEqual(hash(a
), hash(base
))
2580 self
.assertEqual((+a
).__class
__, complex)
2581 self
.assertEqual((a
+ 0).__class
__, complex)
2582 self
.assertEqual(a
+ 0, base
)
2583 self
.assertEqual((a
- 0).__class
__, complex)
2584 self
.assertEqual(a
- 0, base
)
2585 self
.assertEqual((a
* 1).__class
__, complex)
2586 self
.assertEqual(a
* 1, base
)
2587 self
.assertEqual((a
/ 1).__class
__, complex)
2588 self
.assertEqual(a
/ 1, base
)
2590 class madtuple(tuple):
2593 if self
._rev
is not None:
2597 self
._rev
= self
.__class
__(L
)
2599 a
= madtuple((1,2,3,4,5,6,7,8,9,0))
2600 self
.assertEqual(a
, (1,2,3,4,5,6,7,8,9,0))
2601 self
.assertEqual(a
.rev(), madtuple((0,9,8,7,6,5,4,3,2,1)))
2602 self
.assertEqual(a
.rev().rev(), madtuple((1,2,3,4,5,6,7,8,9,0)))
2603 for i
in range(512):
2604 t
= madtuple(range(i
))
2607 self
.assertEqual(v
, t
)
2608 a
= madtuple((1,2,3,4,5))
2609 self
.assertEqual(tuple(a
), (1,2,3,4,5))
2610 self
.assertTrue(tuple(a
).__class
__ is tuple)
2611 self
.assertEqual(hash(a
), hash((1,2,3,4,5)))
2612 self
.assertTrue(a
[:].__class
__ is tuple)
2613 self
.assertTrue((a
* 1).__class
__ is tuple)
2614 self
.assertTrue((a
* 0).__class
__ is tuple)
2615 self
.assertTrue((a
+ ()).__class
__ is tuple)
2617 self
.assertEqual(tuple(a
), ())
2618 self
.assertTrue(tuple(a
).__class
__ is tuple)
2619 self
.assertTrue((a
+ a
).__class
__ is tuple)
2620 self
.assertTrue((a
* 0).__class
__ is tuple)
2621 self
.assertTrue((a
* 1).__class
__ is tuple)
2622 self
.assertTrue((a
* 2).__class
__ is tuple)
2623 self
.assertTrue(a
[:].__class
__ is tuple)
2625 class madstring(str):
2628 if self
._rev
is not None:
2632 self
._rev
= self
.__class
__("".join(L
))
2634 s
= madstring("abcdefghijklmnopqrstuvwxyz")
2635 self
.assertEqual(s
, "abcdefghijklmnopqrstuvwxyz")
2636 self
.assertEqual(s
.rev(), madstring("zyxwvutsrqponmlkjihgfedcba"))
2637 self
.assertEqual(s
.rev().rev(), madstring("abcdefghijklmnopqrstuvwxyz"))
2638 for i
in range(256):
2639 s
= madstring("".join(map(chr, range(i
))))
2642 self
.assertEqual(u
, s
)
2643 s
= madstring("12345")
2644 self
.assertEqual(str(s
), "12345")
2645 self
.assertTrue(str(s
).__class
__ is str)
2649 self
.assertEqual(s
, base
)
2650 self
.assertEqual(str(s
), base
)
2651 self
.assertTrue(str(s
).__class
__ is str)
2652 self
.assertEqual(hash(s
), hash(base
))
2653 self
.assertEqual({s
: 1}[base
], 1)
2654 self
.assertEqual({base
: 1}[s
], 1)
2655 self
.assertTrue((s
+ "").__class
__ is str)
2656 self
.assertEqual(s
+ "", base
)
2657 self
.assertTrue(("" + s
).__class
__ is str)
2658 self
.assertEqual("" + s
, base
)
2659 self
.assertTrue((s
* 0).__class
__ is str)
2660 self
.assertEqual(s
* 0, "")
2661 self
.assertTrue((s
* 1).__class
__ is str)
2662 self
.assertEqual(s
* 1, base
)
2663 self
.assertTrue((s
* 2).__class
__ is str)
2664 self
.assertEqual(s
* 2, base
+ base
)
2665 self
.assertTrue(s
[:].__class
__ is str)
2666 self
.assertEqual(s
[:], base
)
2667 self
.assertTrue(s
[0:0].__class
__ is str)
2668 self
.assertEqual(s
[0:0], "")
2669 self
.assertTrue(s
.strip().__class
__ is str)
2670 self
.assertEqual(s
.strip(), base
)
2671 self
.assertTrue(s
.lstrip().__class
__ is str)
2672 self
.assertEqual(s
.lstrip(), base
)
2673 self
.assertTrue(s
.rstrip().__class
__ is str)
2674 self
.assertEqual(s
.rstrip(), base
)
2675 identitytab
= ''.join([chr(i
) for i
in range(256)])
2676 self
.assertTrue(s
.translate(identitytab
).__class
__ is str)
2677 self
.assertEqual(s
.translate(identitytab
), base
)
2678 self
.assertTrue(s
.translate(identitytab
, "x").__class
__ is str)
2679 self
.assertEqual(s
.translate(identitytab
, "x"), base
)
2680 self
.assertEqual(s
.translate(identitytab
, "\x00"), "")
2681 self
.assertTrue(s
.replace("x", "x").__class
__ is str)
2682 self
.assertEqual(s
.replace("x", "x"), base
)
2683 self
.assertTrue(s
.ljust(len(s
)).__class
__ is str)
2684 self
.assertEqual(s
.ljust(len(s
)), base
)
2685 self
.assertTrue(s
.rjust(len(s
)).__class
__ is str)
2686 self
.assertEqual(s
.rjust(len(s
)), base
)
2687 self
.assertTrue(s
.center(len(s
)).__class
__ is str)
2688 self
.assertEqual(s
.center(len(s
)), base
)
2689 self
.assertTrue(s
.lower().__class
__ is str)
2690 self
.assertEqual(s
.lower(), base
)
2692 class madunicode(unicode):
2695 if self
._rev
is not None:
2699 self
._rev
= self
.__class
__(u
"".join(L
))
2701 u
= madunicode("ABCDEF")
2702 self
.assertEqual(u
, u
"ABCDEF")
2703 self
.assertEqual(u
.rev(), madunicode(u
"FEDCBA"))
2704 self
.assertEqual(u
.rev().rev(), madunicode(u
"ABCDEF"))
2706 u
= madunicode(base
)
2707 self
.assertEqual(unicode(u
), base
)
2708 self
.assertTrue(unicode(u
).__class
__ is unicode)
2709 self
.assertEqual(hash(u
), hash(base
))
2710 self
.assertEqual({u
: 1}[base
], 1)
2711 self
.assertEqual({base
: 1}[u
], 1)
2712 self
.assertTrue(u
.strip().__class
__ is unicode)
2713 self
.assertEqual(u
.strip(), base
)
2714 self
.assertTrue(u
.lstrip().__class
__ is unicode)
2715 self
.assertEqual(u
.lstrip(), base
)
2716 self
.assertTrue(u
.rstrip().__class
__ is unicode)
2717 self
.assertEqual(u
.rstrip(), base
)
2718 self
.assertTrue(u
.replace(u
"x", u
"x").__class
__ is unicode)
2719 self
.assertEqual(u
.replace(u
"x", u
"x"), base
)
2720 self
.assertTrue(u
.replace(u
"xy", u
"xy").__class
__ is unicode)
2721 self
.assertEqual(u
.replace(u
"xy", u
"xy"), base
)
2722 self
.assertTrue(u
.center(len(u
)).__class
__ is unicode)
2723 self
.assertEqual(u
.center(len(u
)), base
)
2724 self
.assertTrue(u
.ljust(len(u
)).__class
__ is unicode)
2725 self
.assertEqual(u
.ljust(len(u
)), base
)
2726 self
.assertTrue(u
.rjust(len(u
)).__class
__ is unicode)
2727 self
.assertEqual(u
.rjust(len(u
)), base
)
2728 self
.assertTrue(u
.lower().__class
__ is unicode)
2729 self
.assertEqual(u
.lower(), base
)
2730 self
.assertTrue(u
.upper().__class
__ is unicode)
2731 self
.assertEqual(u
.upper(), base
)
2732 self
.assertTrue(u
.capitalize().__class
__ is unicode)
2733 self
.assertEqual(u
.capitalize(), base
)
2734 self
.assertTrue(u
.title().__class
__ is unicode)
2735 self
.assertEqual(u
.title(), base
)
2736 self
.assertTrue((u
+ u
"").__class
__ is unicode)
2737 self
.assertEqual(u
+ u
"", base
)
2738 self
.assertTrue((u
"" + u
).__class
__ is unicode)
2739 self
.assertEqual(u
"" + u
, base
)
2740 self
.assertTrue((u
* 0).__class
__ is unicode)
2741 self
.assertEqual(u
* 0, u
"")
2742 self
.assertTrue((u
* 1).__class
__ is unicode)
2743 self
.assertEqual(u
* 1, base
)
2744 self
.assertTrue((u
* 2).__class
__ is unicode)
2745 self
.assertEqual(u
* 2, base
+ base
)
2746 self
.assertTrue(u
[:].__class
__ is unicode)
2747 self
.assertEqual(u
[:], base
)
2748 self
.assertTrue(u
[0:0].__class
__ is unicode)
2749 self
.assertEqual(u
[0:0], u
"")
2751 class sublist(list):
2753 a
= sublist(range(5))
2754 self
.assertEqual(a
, range(5))
2756 self
.assertEqual(a
, range(5) + ["hello"])
2758 self
.assertEqual(a
, range(6))
2759 a
.extend(range(6, 20))
2760 self
.assertEqual(a
, range(20))
2762 self
.assertEqual(a
, range(15))
2764 self
.assertEqual(len(a
), 10)
2765 self
.assertEqual(a
, range(10))
2766 self
.assertEqual(list(a
), range(10))
2767 self
.assertEqual(a
[0], 0)
2768 self
.assertEqual(a
[9], 9)
2769 self
.assertEqual(a
[-10], 0)
2770 self
.assertEqual(a
[-1], 9)
2771 self
.assertEqual(a
[:5], range(5))
2773 class CountedInput(file):
2774 """Counts lines read by self.readline().
2776 self.lineno is the 0-based ordinal of the last line read, up to
2777 a maximum of one greater than the number of lines in the file.
2779 self.ateof is true if and only if the final "" line has been read,
2780 at which point self.lineno stops incrementing, and further calls
2781 to readline() continue to return "".
2789 s
= file.readline(self
)
2790 # Next line works too.
2791 # s = super(CountedInput, self).readline()
2797 f
= file(name
=test_support
.TESTFN
, mode
='w')
2798 lines
= ['a\n', 'b\n', 'c\n']
2802 f
= CountedInput(test_support
.TESTFN
)
2803 for (i
, expected
) in zip(range(1, 5) + [4], lines
+ 2 * [""]):
2805 self
.assertEqual(expected
, got
)
2806 self
.assertEqual(f
.lineno
, i
)
2807 self
.assertEqual(f
.ateof
, (i
> len(lines
)))
2814 test_support
.unlink(test_support
.TESTFN
)
2816 def test_keywords(self
):
2817 # Testing keyword args to basic type constructors ...
2818 self
.assertEqual(int(x
=1), 1)
2819 self
.assertEqual(float(x
=2), 2.0)
2820 self
.assertEqual(long(x
=3), 3L)
2821 self
.assertEqual(complex(imag
=42, real
=666), complex(666, 42))
2822 self
.assertEqual(str(object=500), '500')
2823 self
.assertEqual(unicode(string
='abc', errors
='strict'), u
'abc')
2824 self
.assertEqual(tuple(sequence
=range(3)), (0, 1, 2))
2825 self
.assertEqual(list(sequence
=(0, 1, 2)), range(3))
2826 # note: as of Python 2.3, dict() no longer has an "items" keyword arg
2828 for constructor
in (int, float, long, complex, str, unicode,
2831 constructor(bogus_keyword_arg
=1)
2835 self
.fail("expected TypeError from bogus keyword argument to %r"
2838 def test_str_subclass_as_dict_key(self
):
2839 # Testing a str subclass used as dict key ..
2842 """Sublcass of str that computes __eq__ case-insensitively.
2844 Also computes a hash code of the string in canonical form.
2847 def __init__(self
, value
):
2848 self
.canonical
= value
.lower()
2849 self
.hashcode
= hash(self
.canonical
)
2851 def __eq__(self
, other
):
2852 if not isinstance(other
, cistr
):
2853 other
= cistr(other
)
2854 return self
.canonical
== other
.canonical
2857 return self
.hashcode
2859 self
.assertEqual(cistr('ABC'), 'abc')
2860 self
.assertEqual('aBc', cistr('ABC'))
2861 self
.assertEqual(str(cistr('ABC')), 'ABC')
2863 d
= {cistr('one'): 1, cistr('two'): 2, cistr('tHree'): 3}
2864 self
.assertEqual(d
[cistr('one')], 1)
2865 self
.assertEqual(d
[cistr('tWo')], 2)
2866 self
.assertEqual(d
[cistr('THrEE')], 3)
2867 self
.assertTrue(cistr('ONe') in d
)
2868 self
.assertEqual(d
.get(cistr('thrEE')), 3)
2870 def test_classic_comparisons(self
):
2871 # Testing classic comparisons...
2875 for base
in (classic
, int, object):
2877 def __init__(self
, value
):
2878 self
.value
= int(value
)
2879 def __cmp__(self
, other
):
2880 if isinstance(other
, C
):
2881 return cmp(self
.value
, other
.value
)
2882 if isinstance(other
, int) or isinstance(other
, long):
2883 return cmp(self
.value
, other
)
2884 return NotImplemented
2885 __hash__
= None # Silence Py3k warning
2890 self
.assertEqual(c1
, 1)
2891 c
= {1: c1
, 2: c2
, 3: c3
}
2894 self
.assertTrue(cmp(c
[x
], c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2895 for op
in "<", "<=", "==", "!=", ">", ">=":
2896 self
.assertTrue(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2897 "x=%d, y=%d" % (x
, y
))
2898 self
.assertTrue(cmp(c
[x
], y
) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2899 self
.assertTrue(cmp(x
, c
[y
]) == cmp(x
, y
), "x=%d, y=%d" % (x
, y
))
2901 def test_rich_comparisons(self
):
2902 # Testing rich comparisons...
2906 self
.assertEqual(z
, 1+0j
)
2907 self
.assertEqual(1+0j
, z
)
2909 def __eq__(self
, other
):
2911 return abs(self
- other
) <= 1e-6
2913 return NotImplemented
2914 __hash__
= None # Silence Py3k warning
2916 self
.assertEqual(zz
, 1+0j
)
2917 self
.assertEqual(1+0j
, zz
)
2921 for base
in (classic
, int, object, list):
2923 def __init__(self
, value
):
2924 self
.value
= int(value
)
2925 def __cmp__(self_
, other
):
2926 self
.fail("shouldn't call __cmp__")
2927 __hash__
= None # Silence Py3k warning
2928 def __eq__(self
, other
):
2929 if isinstance(other
, C
):
2930 return self
.value
== other
.value
2931 if isinstance(other
, int) or isinstance(other
, long):
2932 return self
.value
== other
2933 return NotImplemented
2934 def __ne__(self
, other
):
2935 if isinstance(other
, C
):
2936 return self
.value
!= other
.value
2937 if isinstance(other
, int) or isinstance(other
, long):
2938 return self
.value
!= other
2939 return NotImplemented
2940 def __lt__(self
, other
):
2941 if isinstance(other
, C
):
2942 return self
.value
< other
.value
2943 if isinstance(other
, int) or isinstance(other
, long):
2944 return self
.value
< other
2945 return NotImplemented
2946 def __le__(self
, other
):
2947 if isinstance(other
, C
):
2948 return self
.value
<= other
.value
2949 if isinstance(other
, int) or isinstance(other
, long):
2950 return self
.value
<= other
2951 return NotImplemented
2952 def __gt__(self
, other
):
2953 if isinstance(other
, C
):
2954 return self
.value
> other
.value
2955 if isinstance(other
, int) or isinstance(other
, long):
2956 return self
.value
> other
2957 return NotImplemented
2958 def __ge__(self
, other
):
2959 if isinstance(other
, C
):
2960 return self
.value
>= other
.value
2961 if isinstance(other
, int) or isinstance(other
, long):
2962 return self
.value
>= other
2963 return NotImplemented
2967 self
.assertEqual(c1
, 1)
2968 c
= {1: c1
, 2: c2
, 3: c3
}
2971 for op
in "<", "<=", "==", "!=", ">", ">=":
2972 self
.assertTrue(eval("c[x] %s c[y]" % op
) == eval("x %s y" % op
),
2973 "x=%d, y=%d" % (x
, y
))
2974 self
.assertTrue(eval("c[x] %s y" % op
) == eval("x %s y" % op
),
2975 "x=%d, y=%d" % (x
, y
))
2976 self
.assertTrue(eval("x %s c[y]" % op
) == eval("x %s y" % op
),
2977 "x=%d, y=%d" % (x
, y
))
2979 def test_coercions(self
):
2980 # Testing coercions...
2989 class F(float): pass
2996 class C(complex): pass
3006 def test_descrdoc(self
):
3007 # Testing descriptor doc strings...
3008 def check(descr
, what
):
3009 self
.assertEqual(descr
.__doc
__, what
)
3010 check(file.closed
, "True if the file is closed") # getset descriptor
3011 check(file.name
, "file name") # member descriptor
3013 def test_doc_descriptor(self
):
3014 # Testing __doc__ descriptor...
3016 class DocDescr(object):
3017 def __get__(self
, object, otype
):
3019 object = object.__class
__.__name
__ + ' instance'
3021 otype
= otype
.__name
__
3022 return 'object=%s; type=%s' % (object, otype
)
3024 __doc__
= DocDescr()
3025 class NewClass(object):
3026 __doc__
= DocDescr()
3027 self
.assertEqual(OldClass
.__doc
__, 'object=None; type=OldClass')
3028 self
.assertEqual(OldClass().__doc
__, 'object=OldClass instance; type=OldClass')
3029 self
.assertEqual(NewClass
.__doc
__, 'object=None; type=NewClass')
3030 self
.assertEqual(NewClass().__doc
__, 'object=NewClass instance; type=NewClass')
3032 def test_set_class(self
):
3033 # Testing __class__ assignment...
3034 class C(object): pass
3035 class D(object): pass
3036 class E(object): pass
3038 for cls
in C
, D
, E
, F
:
3039 for cls2
in C
, D
, E
, F
:
3042 self
.assertTrue(x
.__class
__ is cls2
)
3044 self
.assertTrue(x
.__class
__ is cls
)
3051 self
.fail("shouldn't allow %r.__class__ = %r" % (x
, C
))
3053 delattr(x
, "__class__")
3054 except (TypeError, AttributeError):
3057 self
.fail("shouldn't allow del %r.__class__" % x
)
3062 cant(object(), list)
3063 cant(list(), object)
3064 class Int(int): __slots__
= []
3074 __slots__
= ["a", "b"]
3076 __slots__
= ["b", "a"]
3081 __slots__
= ["a", "b"]
3084 __slots__
= [unicode("a"), unicode("b")]
3086 __slots__
= ["c", "b"]
3088 __slots__
= ["a", "b", "d"]
3094 __slots__
= ["__weakref__"]
3096 __slots__
= ["__dict__"]
3100 __slots__
= ["__dict__", "__weakref__"]
3102 for cls
, cls2
in ((G
, H
), (G
, I
), (I
, H
), (Q
, R
), (R
, Q
)):
3106 self
.assertTrue(x
.__class
__ is cls2
,
3107 "assigning %r as __class__ for %r silently failed" % (cls2
, x
))
3108 self
.assertEqual(x
.a
, 1)
3110 self
.assertTrue(x
.__class
__ is cls
,
3111 "assigning %r as __class__ for %r silently failed" % (cls
, x
))
3112 self
.assertEqual(x
.a
, 1)
3113 for cls
in G
, J
, K
, L
, M
, N
, P
, R
, list, Int
:
3114 for cls2
in G
, J
, K
, L
, M
, N
, P
, R
, list, Int
:
3119 # Issue5283: when __class__ changes in __del__, the wrong
3120 # type gets DECREF'd.
3126 l
= [A() for x
in range(100)]
3129 def test_set_dict(self
):
3130 # Testing __dict__ assignment...
3131 class C(object): pass
3133 a
.__dict
__ = {'b': 1}
3134 self
.assertEqual(a
.b
, 1)
3138 except (AttributeError, TypeError):
3141 self
.fail("shouldn't allow %r.__dict__ = %r" % (x
, dict))
3145 del a
.__dict
__ # Deleting __dict__ is allowed
3149 def verify_dict_readonly(x
):
3151 x has to be an instance of a class inheriting from Base.
3156 except (AttributeError, TypeError):
3159 self
.fail("shouldn't allow del %r.__dict__" % x
)
3160 dict_descr
= Base
.__dict
__["__dict__"]
3162 dict_descr
.__set
__(x
, {})
3163 except (AttributeError, TypeError):
3166 self
.fail("dict_descr allowed access to %r's dict" % x
)
3168 # Classes don't allow __dict__ assignment and have readonly dicts
3169 class Meta1(type, Base
):
3171 class Meta2(Base
, type):
3174 __metaclass__
= Meta1
3176 __metaclass__
= Meta2
3178 verify_dict_readonly(cls
)
3179 class_dict
= cls
.__dict
__
3181 class_dict
["spam"] = "eggs"
3185 self
.fail("%r's __dict__ can be modified" % cls
)
3187 # Modules also disallow __dict__ assignment
3188 class Module1(types
.ModuleType
, Base
):
3190 class Module2(Base
, types
.ModuleType
):
3192 for ModuleType
in Module1
, Module2
:
3193 mod
= ModuleType("spam")
3194 verify_dict_readonly(mod
)
3195 mod
.__dict
__["spam"] = "eggs"
3197 # Exception's __dict__ can be replaced, but not deleted
3198 # (at least not any more than regular exception's __dict__ can
3199 # be deleted; on CPython it is not the case, whereas on PyPy they
3200 # can, just like any other new-style instance's __dict__.)
3201 def can_delete_dict(e
):
3204 except (TypeError, AttributeError):
3208 class Exception1(Exception, Base
):
3210 class Exception2(Base
, Exception):
3212 for ExceptionType
in Exception, Exception1
, Exception2
:
3214 e
.__dict
__ = {"a": 1}
3215 self
.assertEqual(e
.a
, 1)
3216 self
.assertEqual(can_delete_dict(e
), can_delete_dict(ValueError()))
3218 def test_pickles(self
):
3219 # Testing pickling and copying new-style classes and objects...
3220 import pickle
, cPickle
3229 def __init__(self
, a
, b
):
3230 super(C
, self
).__init
__()
3234 return "C(%r, %r)" % (self
.a
, self
.b
)
3238 def __new__(cls
, a
, b
):
3239 return super(C1
, cls
).__new
__(cls
)
3240 def __getnewargs__(self
):
3241 return (self
.a
, self
.b
)
3242 def __init__(self
, a
, b
):
3246 return "C1(%r, %r)<%r>" % (self
.a
, self
.b
, list(self
))
3250 def __new__(cls
, a
, b
, val
=0):
3251 return super(C2
, cls
).__new
__(cls
, val
)
3252 def __getnewargs__(self
):
3253 return (self
.a
, self
.b
, int(self
))
3254 def __init__(self
, a
, b
, val
=0):
3258 return "C2(%r, %r)<%r>" % (self
.a
, self
.b
, int(self
))
3262 def __init__(self
, foo
):
3264 def __getstate__(self
):
3266 def __setstate__(self
, foo
):
3269 global C4classic
, C4
3270 class C4classic
: # classic
3272 class C4(C4classic
, object): # mixed inheritance
3275 for p
in pickle
, cPickle
:
3277 for cls
in C
, C1
, C2
:
3278 s
= p
.dumps(cls
, bin
)
3280 self
.assertTrue(cls2
is cls
)
3282 a
= C1(1, 2); a
.append(42); a
.append(24)
3283 b
= C2("hello", "world", 42)
3284 s
= p
.dumps((a
, b
), bin
)
3286 self
.assertEqual(x
.__class
__, a
.__class
__)
3287 self
.assertEqual(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
3288 self
.assertEqual(y
.__class
__, b
.__class
__)
3289 self
.assertEqual(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
3290 self
.assertEqual(repr(x
), repr(a
))
3291 self
.assertEqual(repr(y
), repr(b
))
3292 # Test for __getstate__ and __setstate__ on new style class
3296 self
.assertEqual(u
.__class
__, v
.__class
__)
3297 self
.assertEqual(u
.foo
, v
.foo
)
3298 # Test for picklability of hybrid class
3303 self
.assertEqual(u
.__class
__, v
.__class
__)
3304 self
.assertEqual(u
.foo
, v
.foo
)
3306 # Testing copy.deepcopy()
3308 for cls
in C
, C1
, C2
:
3309 cls2
= copy
.deepcopy(cls
)
3310 self
.assertTrue(cls2
is cls
)
3312 a
= C1(1, 2); a
.append(42); a
.append(24)
3313 b
= C2("hello", "world", 42)
3314 x
, y
= copy
.deepcopy((a
, b
))
3315 self
.assertEqual(x
.__class
__, a
.__class
__)
3316 self
.assertEqual(sorteditems(x
.__dict
__), sorteditems(a
.__dict
__))
3317 self
.assertEqual(y
.__class
__, b
.__class
__)
3318 self
.assertEqual(sorteditems(y
.__dict
__), sorteditems(b
.__dict
__))
3319 self
.assertEqual(repr(x
), repr(a
))
3320 self
.assertEqual(repr(y
), repr(b
))
3322 def test_pickle_slots(self
):
3323 # Testing pickling of classes with __slots__ ...
3324 import pickle
, cPickle
3325 # Pickling of classes with __slots__ but without __getstate__ should fail
3329 for base
in [object, B
]:
3339 self
.fail("should fail: pickle C instance - %s" % base
)
3345 self
.fail("should fail: cPickle C instance - %s" % base
)
3351 self
.fail("should fail: pickle D instance - %s" % base
)
3357 self
.fail("should fail: cPickle D instance - %s" % base
)
3358 # Give C a nice generic __getstate__ and __setstate__
3361 def __getstate__(self
):
3363 d
= self
.__dict
__.copy()
3364 except AttributeError:
3366 for cls
in self
.__class
__.__mro
__:
3367 for sn
in cls
.__dict
__.get('__slots__', ()):
3369 d
[sn
] = getattr(self
, sn
)
3370 except AttributeError:
3373 def __setstate__(self
, d
):
3374 for k
, v
in d
.items():
3378 # Now it should work
3380 y
= pickle
.loads(pickle
.dumps(x
))
3381 self
.assertEqual(hasattr(y
, 'a'), 0)
3382 y
= cPickle
.loads(cPickle
.dumps(x
))
3383 self
.assertEqual(hasattr(y
, 'a'), 0)
3385 y
= pickle
.loads(pickle
.dumps(x
))
3386 self
.assertEqual(y
.a
, 42)
3387 y
= cPickle
.loads(cPickle
.dumps(x
))
3388 self
.assertEqual(y
.a
, 42)
3392 y
= pickle
.loads(pickle
.dumps(x
))
3393 self
.assertEqual(y
.a
+ y
.b
, 142)
3394 y
= cPickle
.loads(cPickle
.dumps(x
))
3395 self
.assertEqual(y
.a
+ y
.b
, 142)
3396 # A subclass that adds a slot should also work
3402 y
= pickle
.loads(pickle
.dumps(x
))
3403 self
.assertEqual(y
.a
, x
.a
)
3404 self
.assertEqual(y
.b
, x
.b
)
3405 y
= cPickle
.loads(cPickle
.dumps(x
))
3406 self
.assertEqual(y
.a
, x
.a
)
3407 self
.assertEqual(y
.b
, x
.b
)
3409 def test_binary_operator_override(self
):
3410 # Testing overrides of binary operations...
3413 return "I(%r)" % int(self
)
3414 def __add__(self
, other
):
3415 return I(int(self
) + int(other
))
3417 def __pow__(self
, other
, mod
=None):
3419 return I(pow(int(self
), int(other
)))
3421 return I(pow(int(self
), int(other
), int(mod
)))
3422 def __rpow__(self
, other
, mod
=None):
3424 return I(pow(int(other
), int(self
), mod
))
3426 return I(pow(int(other
), int(self
), int(mod
)))
3428 self
.assertEqual(repr(I(1) + I(2)), "I(3)")
3429 self
.assertEqual(repr(I(1) + 2), "I(3)")
3430 self
.assertEqual(repr(1 + I(2)), "I(3)")
3431 self
.assertEqual(repr(I(2) ** I(3)), "I(8)")
3432 self
.assertEqual(repr(2 ** I(3)), "I(8)")
3433 self
.assertEqual(repr(I(2) ** 3), "I(8)")
3434 self
.assertEqual(repr(pow(I(2), I(3), I(5))), "I(3)")
3436 def __eq__(self
, other
):
3437 return self
.lower() == other
.lower()
3438 __hash__
= None # Silence Py3k warning
3440 def test_subclass_propagation(self
):
3441 # Testing propagation of slot functions to subclasses...
3451 orig_hash
= hash(d
) # related to id(d) in platform-dependent ways
3452 A
.__hash
__ = lambda self
: 42
3453 self
.assertEqual(hash(d
), 42)
3454 C
.__hash
__ = lambda self
: 314
3455 self
.assertEqual(hash(d
), 314)
3456 B
.__hash
__ = lambda self
: 144
3457 self
.assertEqual(hash(d
), 144)
3458 D
.__hash
__ = lambda self
: 100
3459 self
.assertEqual(hash(d
), 100)
3461 self
.assertRaises(TypeError, hash, d
)
3463 self
.assertEqual(hash(d
), 144)
3465 self
.assertRaises(TypeError, hash, d
)
3467 self
.assertEqual(hash(d
), 314)
3469 self
.assertRaises(TypeError, hash, d
)
3471 self
.assertEqual(hash(d
), 42)
3473 self
.assertRaises(TypeError, hash, d
)
3475 self
.assertEqual(hash(d
), orig_hash
)
3478 self
.assertEqual(d
.foo
, 42)
3479 self
.assertEqual(d
.bar
, 42)
3480 def __getattribute__(self
, name
):
3483 return object.__getattribute
__(self
, name
)
3484 A
.__getattribute
__ = __getattribute__
3485 self
.assertEqual(d
.foo
, 24)
3486 self
.assertEqual(d
.bar
, 42)
3487 def __getattr__(self
, name
):
3488 if name
in ("spam", "foo", "bar"):
3490 raise AttributeError, name
3491 B
.__getattr
__ = __getattr__
3492 self
.assertEqual(d
.spam
, "hello")
3493 self
.assertEqual(d
.foo
, 24)
3494 self
.assertEqual(d
.bar
, 42)
3495 del A
.__getattribute
__
3496 self
.assertEqual(d
.foo
, 42)
3498 self
.assertEqual(d
.foo
, "hello")
3499 self
.assertEqual(d
.bar
, 42)
3503 except AttributeError:
3506 self
.fail("d.foo should be undefined now")
3508 # Test a nasty bug in recurse_down_subclasses()
3515 test_support
.gc_collect()
3516 A
.__setitem
__ = lambda *a
: None # crash
3518 def test_buffer_inheritance(self
):
3519 # Testing that buffer interface is inherited ...
3522 # SF bug [#470040] ParseTuple t# vs subclasses.
3528 # b2a_hex uses the buffer interface to get its argument's value, via
3529 # PyArg_ParseTuple 't#' code.
3530 self
.assertEqual(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3532 # It's not clear that unicode will continue to support the character
3533 # buffer interface, and this test will fail if that's taken away.
3534 class MyUni(unicode):
3538 self
.assertEqual(binascii
.b2a_hex(m
), binascii
.b2a_hex(base
))
3545 self
.fail('subclass of int should not have a buffer interface')
3549 def test_str_of_str_subclass(self
):
3550 # Testing __str__ defined in subclass of str ...
3554 class octetstring(str):
3556 return binascii
.b2a_hex(self
)
3558 return self
+ " repr"
3560 o
= octetstring('A')
3561 self
.assertEqual(type(o
), octetstring
)
3562 self
.assertEqual(type(str(o
)), str)
3563 self
.assertEqual(type(repr(o
)), str)
3564 self
.assertEqual(ord(o
), 0x41)
3565 self
.assertEqual(str(o
), '41')
3566 self
.assertEqual(repr(o
), 'A repr')
3567 self
.assertEqual(o
.__str
__(), '41')
3568 self
.assertEqual(o
.__repr
__(), 'A repr')
3570 capture
= cStringIO
.StringIO()
3571 # Calling str() or not exercises different internal paths.
3573 print >> capture
, str(o
)
3574 self
.assertEqual(capture
.getvalue(), '41\n41\n')
3577 def test_keyword_arguments(self
):
3578 # Testing keyword arguments to __init__, __call__...
3580 self
.assertEqual(f
.__call
__(a
=42), 42)
3582 list.__init
__(a
, sequence
=[0, 1, 2])
3583 self
.assertEqual(a
, [0, 1, 2])
3585 def test_recursive_call(self
):
3586 # Testing recursive __call__() by setting to instance of class...
3593 except RuntimeError:
3596 self
.fail("Recursion limit should have been reached for __call__()")
3598 def test_delete_hook(self
):
3599 # Testing __del__ hook...
3605 self
.assertEqual(log
, [])
3607 test_support
.gc_collect()
3608 self
.assertEqual(log
, [1])
3610 class D(object): pass
3613 except TypeError: pass
3614 else: self
.fail("invalid del() didn't raise TypeError")
3616 def test_hash_inheritance(self
):
3617 # Testing hash of mutable subclasses...
3627 self
.fail("hash() of dict subclass should fail")
3637 self
.fail("hash() of list subclass should fail")
3639 def test_str_operations(self
):
3641 except TypeError: pass
3642 else: self
.fail("'' + 5 doesn't raise TypeError")
3645 except ValueError: pass
3646 else: self
.fail("''.split('') doesn't raise ValueError")
3649 except TypeError: pass
3650 else: self
.fail("''.join([0]) doesn't raise TypeError")
3653 except ValueError: pass
3654 else: self
.fail("''.rindex('5') doesn't raise ValueError")
3657 except TypeError: pass
3658 else: self
.fail("'%(n)s' % None doesn't raise TypeError")
3661 except ValueError: pass
3662 else: self
.fail("'%(n' % {} '' doesn't raise ValueError")
3664 try: '%*s' % ('abc')
3665 except TypeError: pass
3666 else: self
.fail("'%*s' % ('abc') doesn't raise TypeError")
3668 try: '%*.*s' % ('abc', 5)
3669 except TypeError: pass
3670 else: self
.fail("'%*.*s' % ('abc', 5) doesn't raise TypeError")
3673 except TypeError: pass
3674 else: self
.fail("'%s' % (1, 2) doesn't raise TypeError")
3677 except ValueError: pass
3678 else: self
.fail("'%' % None doesn't raise ValueError")
3680 self
.assertEqual('534253'.isdigit(), 1)
3681 self
.assertEqual('534253x'.isdigit(), 0)
3682 self
.assertEqual('%c' % 5, '\x05')
3683 self
.assertEqual('%c' % '5', '5')
3685 def test_deepcopy_recursive(self
):
3686 # Testing deepcopy of recursive objects...
3693 z
= deepcopy(a
) # This blew up before
3695 def test_unintialized_modules(self
):
3696 # Testing uninitialized module objects...
3697 from types
import ModuleType
as M
3700 self
.assertEqual(hasattr(m
, "__name__"), 0)
3701 self
.assertEqual(hasattr(m
, "__file__"), 0)
3702 self
.assertEqual(hasattr(m
, "foo"), 0)
3703 self
.assertFalse(m
.__dict
__) # None or {} are both reasonable answers
3705 self
.assertEqual(m
.__dict
__, {"foo": 1})
3707 def test_funny_new(self
):
3708 # Testing __new__ returning something unexpected...
3710 def __new__(cls
, arg
):
3711 if isinstance(arg
, str): return [1, 2, 3]
3712 elif isinstance(arg
, int): return object.__new
__(D
)
3713 else: return object.__new
__(cls
)
3715 def __init__(self
, arg
):
3717 self
.assertEqual(C("1"), [1, 2, 3])
3718 self
.assertEqual(D("1"), [1, 2, 3])
3720 self
.assertEqual(d
.foo
, None)
3722 self
.assertEqual(isinstance(d
, D
), True)
3723 self
.assertEqual(d
.foo
, 1)
3725 self
.assertEqual(isinstance(d
, D
), True)
3726 self
.assertEqual(d
.foo
, 1)
3728 def test_imul_bug(self
):
3729 # Testing for __imul__ problems...
3732 def __imul__(self
, other
):
3733 return (self
, other
)
3737 self
.assertEqual(y
, (x
, 1.0))
3740 self
.assertEqual(y
, (x
, 2))
3743 self
.assertEqual(y
, (x
, 3L))
3746 self
.assertEqual(y
, (x
, 1L<<100))
3749 self
.assertEqual(y
, (x
, None))
3752 self
.assertEqual(y
, (x
, "foo"))
3754 def test_copy_setstate(self
):
3755 # Testing that copy.*copy() correctly uses __setstate__...
3758 def __init__(self
, foo
=None):
3761 def setfoo(self
, foo
=None):
3765 def __getstate__(self
):
3767 def __setstate__(self_
, lst
):
3768 self
.assertEqual(len(lst
), 1)
3769 self_
.__foo
= self_
.foo
= lst
[0]
3772 self
.assertEqual(a
.foo
, 24)
3773 self
.assertEqual(a
.getfoo(), 42)
3775 self
.assertEqual(b
.foo
, 24)
3776 self
.assertEqual(b
.getfoo(), 24)
3777 b
= copy
.deepcopy(a
)
3778 self
.assertEqual(b
.foo
, 24)
3779 self
.assertEqual(b
.getfoo(), 24)
3781 def test_slices(self
):
3782 # Testing cases with slices and overridden __getitem__ ...
3785 self
.assertEqual("hello"[:4], "hell")
3786 self
.assertEqual("hello"[slice(4)], "hell")
3787 self
.assertEqual(str.__getitem
__("hello", slice(4)), "hell")
3789 def __getitem__(self
, x
):
3790 return str.__getitem
__(self
, x
)
3791 self
.assertEqual(S("hello")[:4], "hell")
3792 self
.assertEqual(S("hello")[slice(4)], "hell")
3793 self
.assertEqual(S("hello").__getitem
__(slice(4)), "hell")
3795 self
.assertEqual((1,2,3)[:2], (1,2))
3796 self
.assertEqual((1,2,3)[slice(2)], (1,2))
3797 self
.assertEqual(tuple.__getitem
__((1,2,3), slice(2)), (1,2))
3799 def __getitem__(self
, x
):
3800 return tuple.__getitem
__(self
, x
)
3801 self
.assertEqual(T((1,2,3))[:2], (1,2))
3802 self
.assertEqual(T((1,2,3))[slice(2)], (1,2))
3803 self
.assertEqual(T((1,2,3)).__getitem
__(slice(2)), (1,2))
3805 self
.assertEqual([1,2,3][:2], [1,2])
3806 self
.assertEqual([1,2,3][slice(2)], [1,2])
3807 self
.assertEqual(list.__getitem
__([1,2,3], slice(2)), [1,2])
3809 def __getitem__(self
, x
):
3810 return list.__getitem
__(self
, x
)
3811 self
.assertEqual(L([1,2,3])[:2], [1,2])
3812 self
.assertEqual(L([1,2,3])[slice(2)], [1,2])
3813 self
.assertEqual(L([1,2,3]).__getitem
__(slice(2)), [1,2])
3814 # Now do lists and __setitem__
3816 a
[slice(1, 3)] = [3,2]
3817 self
.assertEqual(a
, [1,3,2])
3818 a
[slice(0, 2, 1)] = [3,1]
3819 self
.assertEqual(a
, [3,1,2])
3820 a
.__setitem
__(slice(1, 3), [2,1])
3821 self
.assertEqual(a
, [3,2,1])
3822 a
.__setitem
__(slice(0, 2, 1), [2,3])
3823 self
.assertEqual(a
, [2,3,1])
3825 def test_subtype_resurrection(self
):
3826 # Testing resurrection of new-style instance...
3832 # resurrect the instance
3833 C
.container
.append(self
)
3838 # The most interesting thing here is whether this blows up, due to
3839 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1
3843 # If that didn't blow up, it's also interesting to see whether clearing
3844 # the last container slot works: that will attempt to delete c again,
3845 # which will cause c to get appended back to the container again
3846 # "during" the del. (On non-CPython implementations, however, __del__
3847 # is typically not called again.)
3848 test_support
.gc_collect()
3849 self
.assertEqual(len(C
.container
), 1)
3851 if test_support
.check_impl_detail():
3852 test_support
.gc_collect()
3853 self
.assertEqual(len(C
.container
), 1)
3854 self
.assertEqual(C
.container
[-1].attr
, 42)
3856 # Make c mortal again, so that the test framework with -l doesn't report
3860 def test_slots_trash(self
):
3861 # Testing slot trash...
3862 # Deallocating deeply nested slotted trash caused stack overflows
3863 class trash(object):
3865 def __init__(self
, x
):
3868 for i
in xrange(50000):
3872 def test_slots_multiple_inheritance(self
):
3873 # SF bug 575229, multiple inheritance w/ slots dumps core
3880 if test_support
.check_impl_detail():
3881 self
.assertEqual(C
.__basicsize
__, B
.__basicsize
__)
3882 self
.assertTrue(hasattr(C
, '__dict__'))
3883 self
.assertTrue(hasattr(C
, '__weakref__'))
3886 def test_rmul(self
):
3887 # Testing correct invocation of __rmul__...
3890 def __mul__(self
, other
):
3892 def __rmul__(self
, other
):
3895 self
.assertEqual(a
*2, "mul")
3896 self
.assertEqual(a
*2.2, "mul")
3897 self
.assertEqual(2*a
, "rmul")
3898 self
.assertEqual(2.2*a
, "rmul")
3900 def test_ipow(self
):
3901 # Testing correct invocation of __ipow__...
3904 def __ipow__(self
, other
):
3909 def test_mutable_bases(self
):
3910 # Testing mutable bases...
3912 # stuff that should work:
3916 def __getattribute__(self
, attr
):
3920 return super(C2
, self
).__getattribute
__(attr
)
3931 self
.assertEqual(d
.meth(), 1)
3932 self
.assertEqual(e
.meth(), 1)
3933 self
.assertEqual(d
.a
, 2)
3934 self
.assertEqual(e
.a
, 2)
3935 self
.assertEqual(C2
.__subclasses__(), [D
])
3939 except (TypeError, AttributeError):
3942 self
.fail("shouldn't be able to delete .__bases__")
3946 except TypeError, msg
:
3947 if str(msg
) == "a new-style class can't have only classic bases":
3948 self
.fail("wrong error message for .__bases__ = ()")
3950 self
.fail("shouldn't be able to set .__bases__ to ()")
3957 # actually, we'll have crashed by here...
3958 self
.fail("shouldn't be able to create inheritance cycles")
3961 D
.__bases
__ = (C
, C
)
3965 self
.fail("didn't detect repeated base classes")
3972 self
.fail("shouldn't be able to create inheritance cycles")
3974 # let's throw a classic class into the mix:
3979 D
.__bases
__ = (C
, Classic
)
3981 self
.assertEqual(d
.meth2(), 3)
3982 self
.assertEqual(e
.meth2(), 3)
3985 except AttributeError:
3988 self
.fail("attribute should have vanished")
3991 D
.__bases
__ = (Classic
,)
3995 self
.fail("new-style class must have a new-style base")
3997 def test_builtin_bases(self
):
3998 # Make sure all the builtin types can have their base queried without
3999 # segfaulting. See issue #5787.
4000 builtin_types
= [tp
for tp
in __builtin__
.__dict
__.itervalues()
4001 if isinstance(tp
, type)]
4002 for tp
in builtin_types
:
4003 object.__getattribute
__(tp
, "__bases__")
4004 if tp
is not object:
4005 self
.assertEqual(len(tp
.__bases
__), 1, tp
)
4017 L
.__bases
__ = (dict,)
4021 self
.fail("shouldn't turn list subclass into dict subclass")
4024 list.__bases
__ = (dict,)
4028 self
.fail("shouldn't be able to assign to list.__bases__")
4031 D
.__bases
__ = (C
, list)
4035 assert 0, "best_base calculation found wanting"
4038 def test_mutable_bases_with_failing_mro(self
):
4039 # Testing mutable bases with failing mro...
4040 class WorkOnce(type):
4041 def __new__(self
, name
, bases
, ns
):
4043 return super(WorkOnce
, self
).__new
__(WorkOnce
, name
, bases
, ns
)
4046 raise RuntimeError, "bozo"
4049 return type.mro(self
)
4051 class WorkAlways(type):
4053 # this is here to make sure that .mro()s aren't called
4054 # with an exception set (which was possible at one point).
4055 # An error message will be printed in a debug build.
4056 # What's a good way to test for this?
4057 return type.mro(self
)
4072 __metaclass__
= WorkOnce
4075 __metaclass__
= WorkAlways
4077 # Immediate subclasses have their mro's adjusted in alphabetical
4078 # order, so E's will get adjusted before adjusting F's fails. We
4079 # check here that E's gets restored.
4081 E_mro_before
= E
.__mro
__
4082 D_mro_before
= D
.__mro
__
4086 except RuntimeError:
4087 self
.assertEqual(E
.__mro
__, E_mro_before
)
4088 self
.assertEqual(D
.__mro
__, D_mro_before
)
4090 self
.fail("exception not propagated")
4092 def test_mutable_bases_catch_mro_conflict(self
):
4093 # Testing mutable bases catch mro conflict...
4110 C
.__bases
__ = (B
, A
)
4114 self
.fail("didn't catch MRO conflict")
4116 def test_mutable_names(self
):
4117 # Testing mutable names...
4121 # C.__module__ could be 'test_descr' or '__main__'
4125 self
.assertEqual((C
.__module
__, C
.__name
__), (mod
, 'D'))
4128 self
.assertEqual((C
.__module
__, C
.__name
__), (mod
, 'D.E'))
4130 def test_subclass_right_op(self
):
4131 # Testing correct dispatch of subclass overloading __r<op>__...
4133 # This code tests various cases where right-dispatch of a subclass
4134 # should be preferred over left-dispatch of a base class.
4136 # Case 1: subclass of int; this tests code in abstract.c::binary_op1()
4139 def __floordiv__(self
, other
):
4140 return "B.__floordiv__"
4141 def __rfloordiv__(self
, other
):
4142 return "B.__rfloordiv__"
4144 self
.assertEqual(B(1) // 1, "B.__floordiv__")
4145 self
.assertEqual(1 // B(1), "B.__rfloordiv__")
4147 # Case 2: subclass of object; this is just the baseline for case 3
4150 def __floordiv__(self
, other
):
4151 return "C.__floordiv__"
4152 def __rfloordiv__(self
, other
):
4153 return "C.__rfloordiv__"
4155 self
.assertEqual(C() // 1, "C.__floordiv__")
4156 self
.assertEqual(1 // C(), "C.__rfloordiv__")
4158 # Case 3: subclass of new-style class; here it gets interesting
4161 def __floordiv__(self
, other
):
4162 return "D.__floordiv__"
4163 def __rfloordiv__(self
, other
):
4164 return "D.__rfloordiv__"
4166 self
.assertEqual(D() // C(), "D.__floordiv__")
4167 self
.assertEqual(C() // D(), "D.__rfloordiv__")
4169 # Case 4: this didn't work right in 2.2.2 and 2.3a1
4174 self
.assertEqual(E
.__rfloordiv
__, C
.__rfloordiv
__)
4176 self
.assertEqual(E() // 1, "C.__floordiv__")
4177 self
.assertEqual(1 // E(), "C.__rfloordiv__")
4178 self
.assertEqual(E() // C(), "C.__floordiv__")
4179 self
.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
4181 @test_support.impl_detail("testing an internal kind of method object")
4182 def test_meth_class_get(self
):
4183 # Testing __get__ method of METH_CLASS C methods...
4184 # Full coverage of descrobject.c::classmethod_get()
4188 res
= {1: None, 2: None, 3: None}
4189 self
.assertEqual(dict.fromkeys(arg
), res
)
4190 self
.assertEqual({}.fromkeys(arg
), res
)
4192 # Now get the descriptor
4193 descr
= dict.__dict
__["fromkeys"]
4195 # More baseline using the descriptor directly
4196 self
.assertEqual(descr
.__get
__(None, dict)(arg
), res
)
4197 self
.assertEqual(descr
.__get
__({})(arg
), res
)
4199 # Now check various error cases
4201 descr
.__get
__(None, None)
4205 self
.fail("shouldn't have allowed descr.__get__(None, None)")
4211 self
.fail("shouldn't have allowed descr.__get__(42)")
4213 descr
.__get
__(None, 42)
4217 self
.fail("shouldn't have allowed descr.__get__(None, 42)")
4219 descr
.__get
__(None, int)
4223 self
.fail("shouldn't have allowed descr.__get__(None, int)")
4225 def test_isinst_isclass(self
):
4226 # Testing proxy isinstance() and isclass()...
4227 class Proxy(object):
4228 def __init__(self
, obj
):
4230 def __getattribute__(self
, name
):
4231 if name
.startswith("_Proxy__"):
4232 return object.__getattribute
__(self
, name
)
4234 return getattr(self
.__obj
, name
)
4235 # Test with a classic class
4240 self
.assertTrue(isinstance(a
, C
)) # Baseline
4241 self
.assertTrue(isinstance(pa
, C
)) # Test
4242 # Test with a classic subclass
4247 self
.assertTrue(isinstance(a
, C
)) # Baseline
4248 self
.assertTrue(isinstance(pa
, C
)) # Test
4249 # Test with a new-style class
4254 self
.assertTrue(isinstance(a
, C
)) # Baseline
4255 self
.assertTrue(isinstance(pa
, C
)) # Test
4256 # Test with a new-style subclass
4261 self
.assertTrue(isinstance(a
, C
)) # Baseline
4262 self
.assertTrue(isinstance(pa
, C
)) # Test
4264 def test_proxy_super(self
):
4265 # Testing super() for a proxy object...
4266 class Proxy(object):
4267 def __init__(self
, obj
):
4269 def __getattribute__(self
, name
):
4270 if name
.startswith("_Proxy__"):
4271 return object.__getattribute
__(self
, name
)
4273 return getattr(self
.__obj
, name
)
4281 return super(C
, self
).f() + "->C.f"
4285 self
.assertEqual(C
.__dict
__["f"](p
), "B.f->C.f")
4287 def test_carloverre(self
):
4288 # Testing prohibition of Carlo Verre's hack...
4290 object.__setattr
__(str, "foo", 42)
4294 self
.fail("Carlo Verre __setattr__ suceeded!")
4296 object.__delattr
__(str, "lower")
4300 self
.fail("Carlo Verre __delattr__ succeeded!")
4302 def test_weakref_segfault(self
):
4303 # Testing weakref segfault...
4308 def __init__(self
, referrent
):
4309 self
.ref
= weakref
.ref(referrent
)
4318 o
.whatever
= Provoker(o
)
4321 def test_wrapper_segfault(self
):
4322 # SF 927248: deeply nested wrappers could cause stack overflow
4324 for i
in xrange(1000000):
4328 def test_file_fault(self
):
4329 # Testing sys.stdout is changed in getattr...
4331 test_stdout
= sys
.stdout
4333 def __getattr__(self
, attr
):
4334 sys
.stdout
= sys
.__stdout
__
4335 raise RuntimeError("Premature access to sys.stdout.%s" % attr
)
4336 sys
.stdout
= StdoutGuard()
4339 except RuntimeError:
4342 sys
.stdout
= test_stdout
4344 def test_vicious_descriptor_nonsense(self
):
4345 # Testing vicious_descriptor_nonsense...
4347 # A potential segfault spotted by Thomas Wouters in mail to
4348 # python-dev 2003-04-17, turned into an example & fixed by Michael
4349 # Hudson just less than four months later...
4354 def __eq__(self
, other
):
4358 class Descr(object):
4359 def __get__(self
, ob
, type=None):
4366 c
.__dict
__[Evil()] = 0
4368 self
.assertEqual(c
.attr
, 1)
4369 # this makes a crash more likely:
4370 test_support
.gc_collect()
4371 self
.assertEqual(hasattr(c
, 'attr'), False)
4373 def test_init(self
):
4383 self
.fail("did not test __init__() for None return")
4385 def test_method_wrapper(self
):
4386 # Testing method-wrapper objects...
4387 # <type 'method-wrapper'> did not support any reflection before 2.5
4390 self
.assertEqual(l
.__add
__, l
.__add
__)
4391 self
.assertEqual(l
.__add
__, [].__add
__)
4392 self
.assertTrue(l
.__add
__ != [5].__add
__)
4393 self
.assertTrue(l
.__add
__ != l
.__mul
__)
4394 self
.assertTrue(l
.__add
__.__name
__ == '__add__')
4395 if hasattr(l
.__add
__, '__self__'):
4397 self
.assertTrue(l
.__add
__.__self
__ is l
)
4398 self
.assertTrue(l
.__add
__.__objclass
__ is list)
4400 # Python implementations where [].__add__ is a normal bound method
4401 self
.assertTrue(l
.__add
__.im_self
is l
)
4402 self
.assertTrue(l
.__add
__.im_class
is list)
4403 self
.assertEqual(l
.__add
__.__doc
__, list.__add
__.__doc
__)
4409 self
.fail("no TypeError from hash([].__add__)")
4413 self
.assertEqual(t
.__add
__, (7,).__add
__)
4414 self
.assertEqual(hash(t
.__add
__), hash((7,).__add
__))
4416 def test_not_implemented(self
):
4417 # Testing NotImplemented...
4418 # all binary methods should be able to return a NotImplemented
4423 def specialmethod(self
, other
):
4424 return NotImplemented
4426 def check(expr
, x
, y
):
4428 exec expr
in {'x': x
, 'y': y
, 'operator': operator
}
4432 self
.fail("no TypeError from %r" % (expr
,))
4434 N1
= sys
.maxint
+ 1L # might trigger OverflowErrors instead of
4436 N2
= sys
.maxint
# if sizeof(int) < sizeof(long), might trigger
4437 # ValueErrors instead of TypeErrors
4438 for metaclass
in [type, types
.ClassType
]:
4439 for name
, expr
, iexpr
in [
4440 ('__add__', 'x + y', 'x += y'),
4441 ('__sub__', 'x - y', 'x -= y'),
4442 ('__mul__', 'x * y', 'x *= y'),
4443 ('__truediv__', 'operator.truediv(x, y)', None),
4444 ('__floordiv__', 'operator.floordiv(x, y)', None),
4445 ('__div__', 'x / y', 'x /= y'),
4446 ('__mod__', 'x % y', 'x %= y'),
4447 ('__divmod__', 'divmod(x, y)', None),
4448 ('__pow__', 'x ** y', 'x **= y'),
4449 ('__lshift__', 'x << y', 'x <<= y'),
4450 ('__rshift__', 'x >> y', 'x >>= y'),
4451 ('__and__', 'x & y', 'x &= y'),
4452 ('__or__', 'x | y', 'x |= y'),
4453 ('__xor__', 'x ^ y', 'x ^= y'),
4454 ('__coerce__', 'coerce(x, y)', None)]:
4455 if name
== '__coerce__':
4458 rname
= '__r' + name
[2:]
4459 A
= metaclass('A', (), {name
: specialmethod
})
4460 B
= metaclass('B', (), {rname
: specialmethod
})
4478 iname
= '__i' + name
[2:]
4479 C
= metaclass('C', (), {iname
: specialmethod
})
4486 def test_assign_slice(self
):
4487 # ceval.c's assign_slice used to check for
4488 # tp->tp_as_sequence->sq_slice instead of
4489 # tp->tp_as_sequence->sq_ass_slice
4492 def __setslice__(self
, start
, stop
, value
):
4497 self
.assertEqual(c
.value
, 3)
4499 def test_getattr_hooks(self
):
4502 class Descriptor(object):
4504 def __get__(self
, obj
, objtype
=None):
4507 raise AttributeError(name
)
4510 descr
= Descriptor()
4512 __getattribute__
= descr
4516 __getattribute__
= descr
4519 self
.assertRaises(AttributeError, getattr, A(), "attr")
4520 self
.assertEquals(descr
.counter
, 1)
4521 self
.assertRaises(AttributeError, getattr, B(), "attr")
4522 self
.assertEquals(descr
.counter
, 2)
4523 self
.assertRaises(AttributeError, getattr, C(), "attr")
4524 self
.assertEquals(descr
.counter
, 4)
4527 class EvilGetattribute(object):
4528 # This used to segfault
4529 def __getattr__(self
, name
):
4530 raise AttributeError(name
)
4531 def __getattribute__(self
, name
):
4532 del EvilGetattribute
.__getattr
__
4535 raise AttributeError(name
)
4537 self
.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
4540 class DictProxyTests(unittest
.TestCase
):
4547 def test_iter_keys(self
):
4548 # Testing dict-proxy iterkeys...
4549 keys
= [ key
for key
in self
.C
.__dict
__.iterkeys() ]
4551 self
.assertEquals(keys
, ['__dict__', '__doc__', '__module__',
4552 '__weakref__', 'meth'])
4554 def test_iter_values(self
):
4555 # Testing dict-proxy itervalues...
4556 values
= [ values
for values
in self
.C
.__dict
__.itervalues() ]
4557 self
.assertEqual(len(values
), 5)
4559 def test_iter_items(self
):
4560 # Testing dict-proxy iteritems...
4561 keys
= [ key
for (key
, value
) in self
.C
.__dict
__.iteritems() ]
4563 self
.assertEqual(keys
, ['__dict__', '__doc__', '__module__',
4564 '__weakref__', 'meth'])
4566 def test_dict_type_with_metaclass(self
):
4567 # Testing type of __dict__ when __metaclass__ set...
4573 # In 2.3a1, C.__dict__ was a real dict rather than a dict proxy
4575 self
.assertEqual(type(C
.__dict
__), type(B
.__dict
__))
4578 class PTypesLongInitTest(unittest
.TestCase
):
4579 # This is in its own TestCase so that it can be run before any other tests.
4580 def test_pytype_long_ready(self
):
4581 # Testing SF bug 551412 ...
4583 # This dumps core when SF bug 551412 isn't fixed --
4584 # but only when test_descr.py is run separately.
4585 # (That can't be helped -- as soon as PyType_Ready()
4586 # is called for PyLong_Type, the bug is gone.)
4587 class UserLong(object):
4588 def __pow__(self
, *args
):
4591 pow(0L, UserLong(), 0L)
4595 # Another segfault only when run early
4596 # (before PyType_Ready(tuple) is called)
4601 # Run all local test cases, with PTypesLongInitTest first.
4602 test_support
.run_unittest(PTypesLongInitTest
, OperatorsTest
,
4603 ClassPropertiesAndMethods
, DictProxyTests
)
4605 if __name__
== "__main__":