Changeset 391 for python/trunk/Lib/test/test_descr.py
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/test/test_descr.py
r2 r391 1 1 import __builtin__ 2 import gc 3 import sys 2 4 import types 3 5 import unittest 4 import w arnings6 import weakref 5 7 6 8 from copy import deepcopy … … 59 61 self.unops[name] = expr 60 62 61 def setUp(self):62 self.original_filters = warnings.filters[:]63 warnings.filterwarnings("ignore",64 r'complex divmod\(\), // and % are deprecated$',65 DeprecationWarning, r'(<string>|%s)$' % __name__)66 67 def tearDown(self):68 warnings.filters = self.original_filters69 70 63 def unop_test(self, a, res, expr="len(a)", meth="__len__"): 71 64 d = {'a': a} … … 77 70 while meth not in t.__dict__: 78 71 t = t.__bases__[0] 79 80 self.assertEqual(m, t.__dict__[meth]) 72 # in some implementations (e.g. PyPy), 'm' can be a regular unbound 73 # method object; the getattr() below obtains its underlying function. 74 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) 81 75 self.assertEqual(m(a), res) 82 76 bm = getattr(a, meth) … … 97 91 while meth not in t.__dict__: 98 92 t = t.__bases__[0] 99 self.assertEqual(m, t.__dict__[meth]) 93 # in some implementations (e.g. PyPy), 'm' can be a regular unbound 94 # method object; the getattr() below obtains its underlying function. 95 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) 100 96 self.assertEqual(m(a, b), res) 101 97 bm = getattr(a, meth) … … 109 105 while meth not in t.__dict__: 110 106 t = t.__bases__[0] 111 self.assertEqual(m, t.__dict__[meth]) 107 # in some implementations (e.g. PyPy), 'm' can be a regular unbound 108 # method object; the getattr() below obtains its underlying function. 109 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) 112 110 self.assertEqual(m(a, b, c), res) 113 111 bm = getattr(a, meth) … … 122 120 while meth not in t.__dict__: 123 121 t = t.__bases__[0] 124 self.assertEqual(m, t.__dict__[meth]) 122 # in some implementations (e.g. PyPy), 'm' can be a regular unbound 123 # method object; the getattr() below obtains its underlying function. 124 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) 125 125 d['a'] = deepcopy(a) 126 126 m(d['a'], b) … … 139 139 while meth not in t.__dict__: 140 140 t = t.__bases__[0] 141 self.assertEqual(m, t.__dict__[meth]) 141 # in some implementations (e.g. PyPy), 'm' can be a regular unbound 142 # method object; the getattr() below obtains its underlying function. 143 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) 142 144 d['a'] = deepcopy(a) 143 145 m(d['a'], b, c) … … 156 158 t = t.__bases__[0] 157 159 m = getattr(t, meth) 158 self.assertEqual(m, t.__dict__[meth]) 160 # in some implementations (e.g. PyPy), 'm' can be a regular unbound 161 # method object; the getattr() below obtains its underlying function. 162 self.assertEqual(getattr(m, 'im_func', m), t.__dict__[meth]) 159 163 dictionary['a'] = deepcopy(a) 160 164 m(dictionary['a'], b, c, d) … … 184 188 def test_dicts(self): 185 189 # Testing dict operations... 186 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") 190 if hasattr(dict, '__cmp__'): # PyPy has only rich comparison on dicts 191 self.binop_test({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") 192 else: 193 self.binop_test({1:2}, {2:1}, True, "a < b", "__lt__") 187 194 self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__") 188 195 self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__") … … 247 254 else: 248 255 self.fail("NotImplemented should have caused TypeError") 249 import sys250 256 try: 251 257 C(sys.maxint+1) … … 295 301 self.assertEqual(a.prec, 12) 296 302 303 @test_support.impl_detail("the module 'xxsubtype' is internal") 297 304 def test_spam_lists(self): 298 305 # Testing spamlist operations... … … 338 345 self.assertEqual(a.getstate(), 42) 339 346 347 @test_support.impl_detail("the module 'xxsubtype' is internal") 340 348 def test_spam_dicts(self): 341 349 # Testing spamdict operations... … … 393 401 def test_python_dicts(self): 394 402 # Testing Python subclass of dict... 395 self.assert _(issubclass(dict, dict))396 self.assert _(isinstance({}, dict))403 self.assertTrue(issubclass(dict, dict)) 404 self.assertIsInstance({}, dict) 397 405 d = dict() 398 406 self.assertEqual(d, {}) 399 self.assert _(d.__class__ is dict)400 self.assert _(isinstance(d, dict))407 self.assertTrue(d.__class__ is dict) 408 self.assertIsInstance(d, dict) 401 409 class C(dict): 402 410 state = -1 … … 411 419 return self.get(key, 0) 412 420 def __setitem__(self_local, key, value): 413 self.assert _(isinstance(key, type(0)))421 self.assertIsInstance(key, type(0)) 414 422 dict.__setitem__(self_local, key, value) 415 423 def setstate(self, state): … … 417 425 def getstate(self): 418 426 return self.state 419 self.assert _(issubclass(C, dict))427 self.assertTrue(issubclass(C, dict)) 420 428 a1 = C(12) 421 429 self.assertEqual(a1.state, 12) … … 511 519 self.assertEqual(C.name, 'C') 512 520 self.assertEqual(C.bases, ()) 513 self.assert _('spam' inC.dict)521 self.assertIn('spam', C.dict) 514 522 c = C() 515 523 self.assertEqual(c.spam(), 42) … … 578 586 self.__x = -x 579 587 a = A() 580 self.assert _(not hasattr(a, "x"))588 self.assertTrue(not hasattr(a, "x")) 581 589 a.x = 12 582 590 self.assertEqual(a.x, 12) … … 638 646 # Testing Python subclass of module... 639 647 log = [] 640 import types, sys641 648 MT = type(sys) 642 649 class MM(MT): … … 872 879 # by Kim Barrett et al. (OOPSLA 1996) 873 880 def test_consistency_with_epg(self): 874 # Testing consisten tcy with EPG...881 # Testing consistency with EPG... 875 882 class Pane(object): pass 876 883 class ScrollingMixin(object): pass … … 893 900 callable(*args) 894 901 except exc, msg: 895 if not str(msg).startswith(expected): 896 self.fail("Message %r, expected %r" % (str(msg), expected)) 902 # the exact msg is generally considered an impl detail 903 if test_support.check_impl_detail(): 904 if not str(msg).startswith(expected): 905 self.fail("Message %r, expected %r" % 906 (str(msg), expected)) 897 907 else: 898 908 self.fail("Expected %s" % exc) … … 1087 1097 self.assertEqual(Counted.counter, 3) 1088 1098 del x 1099 test_support.gc_collect() 1089 1100 self.assertEqual(Counted.counter, 0) 1090 1101 class D(C): … … 1095 1106 self.assertEqual(Counted.counter, 2) 1096 1107 del x 1108 test_support.gc_collect() 1097 1109 self.assertEqual(Counted.counter, 0) 1098 1110 class E(D): … … 1104 1116 self.assertEqual(Counted.counter, 3) 1105 1117 del x 1118 test_support.gc_collect() 1106 1119 self.assertEqual(Counted.counter, 0) 1107 1120 … … 1109 1122 class F(object): 1110 1123 __slots__ = ['a', 'b'] 1111 log = []1112 1124 s = F() 1113 1125 s.a = [Counted(), s] 1114 1126 self.assertEqual(Counted.counter, 1) 1115 1127 s = None 1116 import gc 1117 gc.collect() 1128 test_support.gc_collect() 1118 1129 self.assertEqual(Counted.counter, 0) 1119 1130 1120 1131 # Test lookup leaks [SF bug 572567] 1121 import sys,gc 1122 class G(object): 1123 def __cmp__(self, other): 1124 return 0 1125 __hash__ = None # Silence Py3k warning 1126 g = G() 1127 orig_objects = len(gc.get_objects()) 1128 for i in xrange(10): 1129 g==g 1130 new_objects = len(gc.get_objects()) 1131 self.assertEqual(orig_objects, new_objects) 1132 if hasattr(gc, 'get_objects'): 1133 class G(object): 1134 def __cmp__(self, other): 1135 return 0 1136 __hash__ = None # Silence Py3k warning 1137 g = G() 1138 orig_objects = len(gc.get_objects()) 1139 for i in xrange(10): 1140 g==g 1141 new_objects = len(gc.get_objects()) 1142 self.assertEqual(orig_objects, new_objects) 1143 1132 1144 class H(object): 1133 1145 __slots__ = ['a', 'b'] … … 1145 1157 class X(object): 1146 1158 __slots__ = "a" 1147 try:1159 with self.assertRaises(AttributeError): 1148 1160 del X().a 1149 except AttributeError:1150 pass1151 else:1152 self.fail("didn't raise AttributeError")1153 1161 1154 1162 def test_slots_special(self): … … 1157 1165 __slots__ = ["__dict__"] 1158 1166 a = D() 1159 self.assert _(hasattr(a, "__dict__"))1167 self.assertTrue(hasattr(a, "__dict__")) 1160 1168 self.assertFalse(hasattr(a, "__weakref__")) 1161 1169 a.foo = 42 … … 1165 1173 __slots__ = ["__weakref__"] 1166 1174 a = W() 1167 self.assert _(hasattr(a, "__weakref__"))1175 self.assertTrue(hasattr(a, "__weakref__")) 1168 1176 self.assertFalse(hasattr(a, "__dict__")) 1169 1177 try: … … 1177 1185 __slots__ = [] 1178 1186 a = C1() 1179 self.assert _(hasattr(a, "__dict__"))1180 self.assert _(hasattr(a, "__weakref__"))1187 self.assertTrue(hasattr(a, "__dict__")) 1188 self.assertTrue(hasattr(a, "__weakref__")) 1181 1189 a.foo = 42 1182 1190 self.assertEqual(a.__dict__, {"foo": 42}) … … 1185 1193 __slots__ = [] 1186 1194 a = C2() 1187 self.assert _(hasattr(a, "__dict__"))1188 self.assert _(hasattr(a, "__weakref__"))1195 self.assertTrue(hasattr(a, "__dict__")) 1196 self.assertTrue(hasattr(a, "__weakref__")) 1189 1197 a.foo = 42 1190 1198 self.assertEqual(a.__dict__, {"foo": 42}) … … 1203 1211 1204 1212 u = Unrelated() 1205 self.assert _(isinstance(u, MyABC))1213 self.assertIsInstance(u, MyABC) 1206 1214 1207 1215 # This used to crash … … 1386 1394 self.assertEqual(super(D,d).goo(), (D,)) 1387 1395 1388 # Verify that argument is checked for callability (SF bug 753451) 1389 try: 1390 classmethod(1).__get__(1) 1391 except TypeError: 1392 pass 1393 else: 1394 self.fail("classmethod should check for callability") 1396 # Verify that a non-callable will raise 1397 meth = classmethod(1).__get__(1) 1398 self.assertRaises(TypeError, meth) 1395 1399 1396 1400 # Verify that classmethod() doesn't allow keyword args … … 1402 1406 self.fail("classmethod shouldn't accept keyword args") 1403 1407 1408 @test_support.impl_detail("the module 'xxsubtype' is internal") 1404 1409 def test_classmethods_in_c(self): 1405 1410 # Testing C-based class methods... … … 1415 1420 self.assertEqual(a, a1) 1416 1421 self.assertEqual(d, d1) 1422 spam_cm = spam.spamlist.__dict__['classmeth'] 1423 x2, a2, d2 = spam_cm(spam.spamlist, *a, **d) 1424 self.assertEqual(x2, spam.spamlist) 1425 self.assertEqual(a2, a1) 1426 self.assertEqual(d2, d1) 1427 class SubSpam(spam.spamlist): pass 1428 x2, a2, d2 = spam_cm(SubSpam, *a, **d) 1429 self.assertEqual(x2, SubSpam) 1430 self.assertEqual(a2, a1) 1431 self.assertEqual(d2, d1) 1432 with self.assertRaises(TypeError): 1433 spam_cm() 1434 with self.assertRaises(TypeError): 1435 spam_cm(spam.spamlist()) 1436 with self.assertRaises(TypeError): 1437 spam_cm(list) 1417 1438 1418 1439 def test_staticmethods(self): … … 1433 1454 self.assertEqual(D.foo(d, 1), (d, 1)) 1434 1455 1456 @test_support.impl_detail("the module 'xxsubtype' is internal") 1435 1457 def test_staticmethods_in_c(self): 1436 1458 # Testing C-based static methods... … … 1466 1488 foo = C.foo 1467 1489 self.assertEqual(E().foo, C.foo) # i.e., unbound 1468 self.assert _(repr(C.foo.__get__(C())).startswith("<bound method "))1490 self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method ")) 1469 1491 1470 1492 def test_compattr(self): … … 1549 1571 def mro(self): 1550 1572 return [self, dict, object] 1573 # In CPython, the class creation above already raises 1574 # TypeError, as a protection against the fact that 1575 # instances of X would segfault it. In other Python 1576 # implementations it would be ok to let the class X 1577 # be created, but instead get a clean TypeError on the 1578 # __setitem__ below. 1579 x = object.__new__(X) 1580 x[5] = 6 1551 1581 except TypeError: 1552 1582 pass … … 1649 1679 foo = C.foo 1650 1680 self.assertEqual(E().foo, C.foo) # i.e., unbound 1651 self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method ")) 1681 self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method ")) 1682 1683 def test_special_method_lookup(self): 1684 # The lookup of special methods bypasses __getattr__ and 1685 # __getattribute__, but they still can be descriptors. 1686 1687 def run_context(manager): 1688 with manager: 1689 pass 1690 def iden(self): 1691 return self 1692 def hello(self): 1693 return "hello" 1694 def empty_seq(self): 1695 return [] 1696 def zero(self): 1697 return 0 1698 def complex_num(self): 1699 return 1j 1700 def stop(self): 1701 raise StopIteration 1702 def return_true(self, thing=None): 1703 return True 1704 def do_isinstance(obj): 1705 return isinstance(int, obj) 1706 def do_issubclass(obj): 1707 return issubclass(int, obj) 1708 def swallow(*args): 1709 pass 1710 def do_dict_missing(checker): 1711 class DictSub(checker.__class__, dict): 1712 pass 1713 self.assertEqual(DictSub()["hi"], 4) 1714 def some_number(self_, key): 1715 self.assertEqual(key, "hi") 1716 return 4 1717 def format_impl(self, spec): 1718 return "hello" 1719 1720 # It would be nice to have every special method tested here, but I'm 1721 # only listing the ones I can remember outside of typeobject.c, since it 1722 # does it right. 1723 specials = [ 1724 ("__unicode__", unicode, hello, set(), {}), 1725 ("__reversed__", reversed, empty_seq, set(), {}), 1726 ("__length_hint__", list, zero, set(), 1727 {"__iter__" : iden, "next" : stop}), 1728 ("__sizeof__", sys.getsizeof, zero, set(), {}), 1729 ("__instancecheck__", do_isinstance, return_true, set(), {}), 1730 ("__missing__", do_dict_missing, some_number, 1731 set(("__class__",)), {}), 1732 ("__subclasscheck__", do_issubclass, return_true, 1733 set(("__bases__",)), {}), 1734 ("__enter__", run_context, iden, set(), {"__exit__" : swallow}), 1735 ("__exit__", run_context, swallow, set(), {"__enter__" : iden}), 1736 ("__complex__", complex, complex_num, set(), {}), 1737 ("__format__", format, format_impl, set(), {}), 1738 ("__dir__", dir, empty_seq, set(), {}), 1739 ] 1740 1741 class Checker(object): 1742 def __getattr__(self, attr, test=self): 1743 test.fail("__getattr__ called with {0}".format(attr)) 1744 def __getattribute__(self, attr, test=self): 1745 if attr not in ok: 1746 test.fail("__getattribute__ called with {0}".format(attr)) 1747 return object.__getattribute__(self, attr) 1748 class SpecialDescr(object): 1749 def __init__(self, impl): 1750 self.impl = impl 1751 def __get__(self, obj, owner): 1752 record.append(1) 1753 return self.impl.__get__(obj, owner) 1754 class MyException(Exception): 1755 pass 1756 class ErrDescr(object): 1757 def __get__(self, obj, owner): 1758 raise MyException 1759 1760 for name, runner, meth_impl, ok, env in specials: 1761 class X(Checker): 1762 pass 1763 for attr, obj in env.iteritems(): 1764 setattr(X, attr, obj) 1765 setattr(X, name, meth_impl) 1766 runner(X()) 1767 1768 record = [] 1769 class X(Checker): 1770 pass 1771 for attr, obj in env.iteritems(): 1772 setattr(X, attr, obj) 1773 setattr(X, name, SpecialDescr(meth_impl)) 1774 runner(X()) 1775 self.assertEqual(record, [1], name) 1776 1777 class X(Checker): 1778 pass 1779 for attr, obj in env.iteritems(): 1780 setattr(X, attr, obj) 1781 setattr(X, name, ErrDescr()) 1782 try: 1783 runner(X()) 1784 except MyException: 1785 pass 1786 else: 1787 self.fail("{0!r} didn't raise".format(name)) 1652 1788 1653 1789 def test_specials(self): … … 1662 1798 c1 = C() 1663 1799 c2 = C() 1664 self.assert _(not not c1) # What?1800 self.assertTrue(not not c1) # What? 1665 1801 self.assertNotEqual(id(c1), id(c2)) 1666 1802 hash(c1) … … 1668 1804 self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2))) 1669 1805 self.assertEqual(c1, c1) 1670 self.assert _(c1 != c2)1671 self.assert _(not c1 != c1)1672 self.assert _(not c1 == c2)1806 self.assertTrue(c1 != c2) 1807 self.assertTrue(not c1 != c1) 1808 self.assertTrue(not c1 == c2) 1673 1809 # Note that the module name appears in str/repr, and that varies 1674 1810 # depending on whether this test is run standalone or from a framework. 1675 self.assert _(str(c1).find('C object at ') >= 0)1811 self.assertTrue(str(c1).find('C object at ') >= 0) 1676 1812 self.assertEqual(str(c1), repr(c1)) 1677 self.assert _(-1 not inc1)1813 self.assertNotIn(-1, c1) 1678 1814 for i in range(10): 1679 self.assert _(i inc1)1680 self.assert False(10 inc1)1815 self.assertIn(i, c1) 1816 self.assertNotIn(10, c1) 1681 1817 # Test the default behavior for dynamic classes 1682 1818 class D(object): … … 1686 1822 d1 = D() 1687 1823 d2 = D() 1688 self.assert _(not not d1)1824 self.assertTrue(not not d1) 1689 1825 self.assertNotEqual(id(d1), id(d2)) 1690 1826 hash(d1) … … 1693 1829 self.assertEqual(d1, d1) 1694 1830 self.assertNotEqual(d1, d2) 1695 self.assert _(not d1 != d1)1696 self.assert _(not d1 == d2)1831 self.assertTrue(not d1 != d1) 1832 self.assertTrue(not d1 == d2) 1697 1833 # Note that the module name appears in str/repr, and that varies 1698 1834 # depending on whether this test is run standalone or from a framework. 1699 self.assert _(str(d1).find('D object at ') >= 0)1835 self.assertTrue(str(d1).find('D object at ') >= 0) 1700 1836 self.assertEqual(str(d1), repr(d1)) 1701 self.assert _(-1 not ind1)1837 self.assertNotIn(-1, d1) 1702 1838 for i in range(10): 1703 self.assert _(i ind1)1704 self.assert False(10 ind1)1839 self.assertIn(i, d1) 1840 self.assertNotIn(10, d1) 1705 1841 # Test overridden behavior for static classes 1706 1842 class Proxy(object): … … 1727 1863 p_1 = Proxy(-1) 1728 1864 self.assertFalse(p0) 1729 self.assert _(not not p1)1865 self.assertTrue(not not p1) 1730 1866 self.assertEqual(hash(p0), hash(0)) 1731 1867 self.assertEqual(p0, p0) 1732 1868 self.assertNotEqual(p0, p1) 1733 self.assert _(not p0 != p0)1869 self.assertTrue(not p0 != p0) 1734 1870 self.assertEqual(not p0, p1) 1735 1871 self.assertEqual(cmp(p0, p1), -1) … … 1739 1875 self.assertEqual(repr(p0), "Proxy(0)") 1740 1876 p10 = Proxy(range(10)) 1741 self.assert False(-1 inp10)1877 self.assertNotIn(-1, p10) 1742 1878 for i in range(10): 1743 self.assert _(i inp10)1744 self.assert False(10 inp10)1879 self.assertIn(i, p10) 1880 self.assertNotIn(10, p10) 1745 1881 # Test overridden behavior for dynamic classes 1746 1882 class DProxy(object): … … 1767 1903 p_1 = DProxy(-1) 1768 1904 self.assertFalse(p0) 1769 self.assert _(not not p1)1905 self.assertTrue(not not p1) 1770 1906 self.assertEqual(hash(p0), hash(0)) 1771 1907 self.assertEqual(p0, p0) … … 1779 1915 self.assertEqual(repr(p0), "DProxy(0)") 1780 1916 p10 = DProxy(range(10)) 1781 self.assert False(-1 inp10)1917 self.assertNotIn(-1, p10) 1782 1918 for i in range(10): 1783 self.assert _(i inp10)1784 self.assert False(10 inp10)1919 self.assertIn(i, p10) 1920 self.assertNotIn(10, p10) 1785 1921 1786 1922 # Safety test for __cmp__ 1787 1923 def unsafecmp(a, b): 1788 if not hasattr(a.__class__, "__cmp__"): 1789 return 1924 if not hasattr(a, '__cmp__'): 1925 return # some types don't have a __cmp__ any more (so the 1926 # test doesn't make sense any more), or maybe they 1927 # never had a __cmp__ at all, e.g. in PyPy 1790 1928 try: 1791 1929 a.__class__.__cmp__(a, b) … … 1803 1941 unsafecmp(1L, 1) 1804 1942 1805 def test_recursions(self): 1943 @test_support.impl_detail("custom logic for printing to real file objects") 1944 def test_recursions_1(self): 1806 1945 # Testing recursion checks ... 1807 1946 class Letter(str): … … 1815 1954 return self 1816 1955 # sys.stdout needs to be the original to trigger the recursion bug 1817 import sys1818 1956 test_stdout = sys.stdout 1819 1957 sys.stdout = test_support.get_original_stdout() … … 1828 1966 sys.stdout = test_stdout 1829 1967 1968 def test_recursions_2(self): 1830 1969 # Bug #1202533. 1831 1970 class A(object): … … 1848 1987 self.assertEqual(r(), c) 1849 1988 del c 1989 test_support.gc_collect() 1850 1990 self.assertEqual(r(), None) 1851 1991 del r … … 1856 1996 weakref.ref(no) 1857 1997 except TypeError, msg: 1858 self.assert _(str(msg).find("weak reference") >= 0)1998 self.assertTrue(str(msg).find("weak reference") >= 0) 1859 1999 else: 1860 2000 self.fail("weakref.ref(no) should be illegal") … … 1865 2005 self.assertEqual(r(), yes) 1866 2006 del yes 2007 test_support.gc_collect() 1867 2008 self.assertEqual(r(), None) 1868 2009 del r … … 1892 2033 1893 2034 raw = C.__dict__['x'] 1894 self.assert _(isinstance(raw, property))2035 self.assertIsInstance(raw, property) 1895 2036 1896 2037 attrs = dir(raw) 1897 self.assert _("__doc__" inattrs)1898 self.assert _("fget" inattrs)1899 self.assert _("fset" inattrs)1900 self.assert _("fdel" inattrs)2038 self.assertIn("__doc__", attrs) 2039 self.assertIn("fget", attrs) 2040 self.assertIn("fset", attrs) 2041 self.assertIn("fdel", attrs) 1901 2042 1902 2043 self.assertEqual(raw.__doc__, "I'm the x property.") 1903 self.assert _(raw.fget is C.__dict__['getx'])1904 self.assert _(raw.fset is C.__dict__['setx'])1905 self.assert _(raw.fdel is C.__dict__['delx'])2044 self.assertTrue(raw.fget is C.__dict__['getx']) 2045 self.assertTrue(raw.fset is C.__dict__['setx']) 2046 self.assertTrue(raw.fdel is C.__dict__['delx']) 1906 2047 1907 2048 for attr in "__doc__", "fget", "fset", "fdel": … … 1928 2069 self.fail("expected ZeroDivisionError from bad property") 1929 2070 2071 @unittest.skipIf(sys.flags.optimize >= 2, 2072 "Docstrings are omitted with -O2 and above") 2073 def test_properties_doc_attrib(self): 1930 2074 class E(object): 1931 2075 def getter(self): … … 1940 2084 self.assertEqual(prop2.__doc__, None) 1941 2085 2086 def test_testcapi_no_segfault(self): 1942 2087 # this segfaulted in 2.5b2 1943 2088 try: … … 1965 2110 self.assertFalse(hasattr(c, "foo")) 1966 2111 c.foo = -42 1967 self.assert _(hasattr(c, '_foo'))2112 self.assertTrue(hasattr(c, '_foo')) 1968 2113 self.assertEqual(c._foo, 42) 1969 2114 self.assertEqual(c.foo, 42) … … 2116 2261 cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__'] 2117 2262 self.assertEqual(dir(C), cstuff) 2118 self.assert _('im_self' indir(C.Cmethod))2263 self.assertIn('im_self', dir(C.Cmethod)) 2119 2264 2120 2265 c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__. … … 2124 2269 c.cmethod = lambda self: 0 2125 2270 self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod']) 2126 self.assert _('im_self' indir(c.Cmethod))2271 self.assertIn('im_self', dir(c.Cmethod)) 2127 2272 2128 2273 class A(C): … … 2132 2277 astuff = ['Adata', 'Amethod'] + cstuff 2133 2278 self.assertEqual(dir(A), astuff) 2134 self.assert _('im_self' indir(A.Amethod))2279 self.assertIn('im_self', dir(A.Amethod)) 2135 2280 a = A() 2136 2281 self.assertEqual(dir(a), astuff) 2137 self.assert _('im_self' indir(a.Amethod))2282 self.assertIn('im_self', dir(a.Amethod)) 2138 2283 a.adata = 42 2139 2284 a.amethod = lambda self: 3 … … 2154 2299 c = C() 2155 2300 self.assertEqual(interesting(dir(c)), cstuff) 2156 self.assert _('im_self' indir(C.Cmethod))2301 self.assertIn('im_self', dir(C.Cmethod)) 2157 2302 2158 2303 c.cdata = 2 2159 2304 c.cmethod = lambda self: 0 2160 2305 self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) 2161 self.assert _('im_self' indir(c.Cmethod))2306 self.assertIn('im_self', dir(c.Cmethod)) 2162 2307 2163 2308 class A(C): … … 2167 2312 astuff = ['Adata', 'Amethod'] + cstuff 2168 2313 self.assertEqual(interesting(dir(A)), astuff) 2169 self.assert _('im_self' indir(A.Amethod))2314 self.assertIn('im_self', dir(A.Amethod)) 2170 2315 a = A() 2171 2316 self.assertEqual(interesting(dir(a)), astuff) … … 2173 2318 a.amethod = lambda self: 3 2174 2319 self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod']) 2175 self.assert _('im_self' indir(a.Amethod))2320 self.assertIn('im_self', dir(a.Amethod)) 2176 2321 2177 2322 # Try a module subclass. 2178 import sys2179 2323 class M(type(sys)): 2180 2324 pass … … 2201 2345 # Two essentially featureless objects, just inheriting stuff from 2202 2346 # object. 2203 self.assertEqual(dir(None), dir(Ellipsis)) 2347 self.assertEqual(dir(NotImplemented), dir(Ellipsis)) 2348 if test_support.check_impl_detail(): 2349 # None differs in PyPy: it has a __nonzero__ 2350 self.assertEqual(dir(None), dir(Ellipsis)) 2204 2351 2205 2352 # Nasty test case for proxied objects … … 2354 2501 self.assertEqual(a, 12345) 2355 2502 self.assertEqual(int(a), 12345) 2356 self.assert _(int(a).__class__ is int)2503 self.assertTrue(int(a).__class__ is int) 2357 2504 self.assertEqual(hash(a), hash(12345)) 2358 self.assert _((+a).__class__ is int)2359 self.assert _((a >> 0).__class__ is int)2360 self.assert _((a << 0).__class__ is int)2361 self.assert _((hexint(0) << 12).__class__ is int)2362 self.assert _((hexint(0) >> 12).__class__ is int)2505 self.assertTrue((+a).__class__ is int) 2506 self.assertTrue((a >> 0).__class__ is int) 2507 self.assertTrue((a << 0).__class__ is int) 2508 self.assertTrue((hexint(0) << 12).__class__ is int) 2509 self.assertTrue((hexint(0) >> 12).__class__ is int) 2363 2510 2364 2511 class octlong(long): … … 2380 2527 self.assertEqual(long(a), 12345L) 2381 2528 self.assertEqual(hash(a), hash(12345L)) 2382 self.assert _(long(a).__class__ is long)2383 self.assert _((+a).__class__ is long)2384 self.assert _((-a).__class__ is long)2385 self.assert _((-octlong(0)).__class__ is long)2386 self.assert _((a >> 0).__class__ is long)2387 self.assert _((a << 0).__class__ is long)2388 self.assert _((a - 0).__class__ is long)2389 self.assert _((a * 1).__class__ is long)2390 self.assert _((a ** 1).__class__ is long)2391 self.assert _((a // 1).__class__ is long)2392 self.assert _((1 * a).__class__ is long)2393 self.assert _((a | 0).__class__ is long)2394 self.assert _((a ^ 0).__class__ is long)2395 self.assert _((a & -1L).__class__ is long)2396 self.assert _((octlong(0) << 12).__class__ is long)2397 self.assert _((octlong(0) >> 12).__class__ is long)2398 self.assert _(abs(octlong(0)).__class__ is long)2529 self.assertTrue(long(a).__class__ is long) 2530 self.assertTrue((+a).__class__ is long) 2531 self.assertTrue((-a).__class__ is long) 2532 self.assertTrue((-octlong(0)).__class__ is long) 2533 self.assertTrue((a >> 0).__class__ is long) 2534 self.assertTrue((a << 0).__class__ is long) 2535 self.assertTrue((a - 0).__class__ is long) 2536 self.assertTrue((a * 1).__class__ is long) 2537 self.assertTrue((a ** 1).__class__ is long) 2538 self.assertTrue((a // 1).__class__ is long) 2539 self.assertTrue((1 * a).__class__ is long) 2540 self.assertTrue((a | 0).__class__ is long) 2541 self.assertTrue((a ^ 0).__class__ is long) 2542 self.assertTrue((a & -1L).__class__ is long) 2543 self.assertTrue((octlong(0) << 12).__class__ is long) 2544 self.assertTrue((octlong(0) >> 12).__class__ is long) 2545 self.assertTrue(abs(octlong(0)).__class__ is long) 2399 2546 2400 2547 # Because octlong overrides __add__, we can't check the absence of +0 … … 2403 2550 pass 2404 2551 a = longclone(1) 2405 self.assert _((a + 0).__class__ is long)2406 self.assert _((0 + a).__class__ is long)2552 self.assertTrue((a + 0).__class__ is long) 2553 self.assertTrue((0 + a).__class__ is long) 2407 2554 2408 2555 # Check that negative clones don't segfault 2409 2556 a = longclone(-1) 2410 2557 self.assertEqual(a.__dict__, {}) 2411 self.assertEqual(long(a), -1) # self.assert _PyNumber_Long() copies the sign bit2558 self.assertEqual(long(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit 2412 2559 2413 2560 class precfloat(float): … … 2421 2568 self.assertEqual(a, 12345.0) 2422 2569 self.assertEqual(float(a), 12345.0) 2423 self.assert _(float(a).__class__ is float)2570 self.assertTrue(float(a).__class__ is float) 2424 2571 self.assertEqual(hash(a), hash(12345.0)) 2425 self.assert _((+a).__class__ is float)2572 self.assertTrue((+a).__class__ is float) 2426 2573 2427 2574 class madcomplex(complex): … … 2471 2618 a = madtuple((1,2,3,4,5)) 2472 2619 self.assertEqual(tuple(a), (1,2,3,4,5)) 2473 self.assert _(tuple(a).__class__ is tuple)2620 self.assertTrue(tuple(a).__class__ is tuple) 2474 2621 self.assertEqual(hash(a), hash((1,2,3,4,5))) 2475 self.assert _(a[:].__class__ is tuple)2476 self.assert _((a * 1).__class__ is tuple)2477 self.assert _((a * 0).__class__ is tuple)2478 self.assert _((a + ()).__class__ is tuple)2622 self.assertTrue(a[:].__class__ is tuple) 2623 self.assertTrue((a * 1).__class__ is tuple) 2624 self.assertTrue((a * 0).__class__ is tuple) 2625 self.assertTrue((a + ()).__class__ is tuple) 2479 2626 a = madtuple(()) 2480 2627 self.assertEqual(tuple(a), ()) 2481 self.assert _(tuple(a).__class__ is tuple)2482 self.assert _((a + a).__class__ is tuple)2483 self.assert _((a * 0).__class__ is tuple)2484 self.assert _((a * 1).__class__ is tuple)2485 self.assert _((a * 2).__class__ is tuple)2486 self.assert _(a[:].__class__ is tuple)2628 self.assertTrue(tuple(a).__class__ is tuple) 2629 self.assertTrue((a + a).__class__ is tuple) 2630 self.assertTrue((a * 0).__class__ is tuple) 2631 self.assertTrue((a * 1).__class__ is tuple) 2632 self.assertTrue((a * 2).__class__ is tuple) 2633 self.assertTrue(a[:].__class__ is tuple) 2487 2634 2488 2635 class madstring(str): … … 2506 2653 s = madstring("12345") 2507 2654 self.assertEqual(str(s), "12345") 2508 self.assert _(str(s).__class__ is str)2655 self.assertTrue(str(s).__class__ is str) 2509 2656 2510 2657 base = "\x00" * 5 … … 2512 2659 self.assertEqual(s, base) 2513 2660 self.assertEqual(str(s), base) 2514 self.assert _(str(s).__class__ is str)2661 self.assertTrue(str(s).__class__ is str) 2515 2662 self.assertEqual(hash(s), hash(base)) 2516 2663 self.assertEqual({s: 1}[base], 1) 2517 2664 self.assertEqual({base: 1}[s], 1) 2518 self.assert _((s + "").__class__ is str)2665 self.assertTrue((s + "").__class__ is str) 2519 2666 self.assertEqual(s + "", base) 2520 self.assert _(("" + s).__class__ is str)2667 self.assertTrue(("" + s).__class__ is str) 2521 2668 self.assertEqual("" + s, base) 2522 self.assert _((s * 0).__class__ is str)2669 self.assertTrue((s * 0).__class__ is str) 2523 2670 self.assertEqual(s * 0, "") 2524 self.assert _((s * 1).__class__ is str)2671 self.assertTrue((s * 1).__class__ is str) 2525 2672 self.assertEqual(s * 1, base) 2526 self.assert _((s * 2).__class__ is str)2673 self.assertTrue((s * 2).__class__ is str) 2527 2674 self.assertEqual(s * 2, base + base) 2528 self.assert _(s[:].__class__ is str)2675 self.assertTrue(s[:].__class__ is str) 2529 2676 self.assertEqual(s[:], base) 2530 self.assert _(s[0:0].__class__ is str)2677 self.assertTrue(s[0:0].__class__ is str) 2531 2678 self.assertEqual(s[0:0], "") 2532 self.assert _(s.strip().__class__ is str)2679 self.assertTrue(s.strip().__class__ is str) 2533 2680 self.assertEqual(s.strip(), base) 2534 self.assert _(s.lstrip().__class__ is str)2681 self.assertTrue(s.lstrip().__class__ is str) 2535 2682 self.assertEqual(s.lstrip(), base) 2536 self.assert _(s.rstrip().__class__ is str)2683 self.assertTrue(s.rstrip().__class__ is str) 2537 2684 self.assertEqual(s.rstrip(), base) 2538 2685 identitytab = ''.join([chr(i) for i in range(256)]) 2539 self.assert _(s.translate(identitytab).__class__ is str)2686 self.assertTrue(s.translate(identitytab).__class__ is str) 2540 2687 self.assertEqual(s.translate(identitytab), base) 2541 self.assert _(s.translate(identitytab, "x").__class__ is str)2688 self.assertTrue(s.translate(identitytab, "x").__class__ is str) 2542 2689 self.assertEqual(s.translate(identitytab, "x"), base) 2543 2690 self.assertEqual(s.translate(identitytab, "\x00"), "") 2544 self.assert _(s.replace("x", "x").__class__ is str)2691 self.assertTrue(s.replace("x", "x").__class__ is str) 2545 2692 self.assertEqual(s.replace("x", "x"), base) 2546 self.assert _(s.ljust(len(s)).__class__ is str)2693 self.assertTrue(s.ljust(len(s)).__class__ is str) 2547 2694 self.assertEqual(s.ljust(len(s)), base) 2548 self.assert _(s.rjust(len(s)).__class__ is str)2695 self.assertTrue(s.rjust(len(s)).__class__ is str) 2549 2696 self.assertEqual(s.rjust(len(s)), base) 2550 self.assert _(s.center(len(s)).__class__ is str)2697 self.assertTrue(s.center(len(s)).__class__ is str) 2551 2698 self.assertEqual(s.center(len(s)), base) 2552 self.assert _(s.lower().__class__ is str)2699 self.assertTrue(s.lower().__class__ is str) 2553 2700 self.assertEqual(s.lower(), base) 2554 2701 … … 2569 2716 u = madunicode(base) 2570 2717 self.assertEqual(unicode(u), base) 2571 self.assert _(unicode(u).__class__ is unicode)2718 self.assertTrue(unicode(u).__class__ is unicode) 2572 2719 self.assertEqual(hash(u), hash(base)) 2573 2720 self.assertEqual({u: 1}[base], 1) 2574 2721 self.assertEqual({base: 1}[u], 1) 2575 self.assert _(u.strip().__class__ is unicode)2722 self.assertTrue(u.strip().__class__ is unicode) 2576 2723 self.assertEqual(u.strip(), base) 2577 self.assert _(u.lstrip().__class__ is unicode)2724 self.assertTrue(u.lstrip().__class__ is unicode) 2578 2725 self.assertEqual(u.lstrip(), base) 2579 self.assert _(u.rstrip().__class__ is unicode)2726 self.assertTrue(u.rstrip().__class__ is unicode) 2580 2727 self.assertEqual(u.rstrip(), base) 2581 self.assert _(u.replace(u"x", u"x").__class__ is unicode)2728 self.assertTrue(u.replace(u"x", u"x").__class__ is unicode) 2582 2729 self.assertEqual(u.replace(u"x", u"x"), base) 2583 self.assert _(u.replace(u"xy", u"xy").__class__ is unicode)2730 self.assertTrue(u.replace(u"xy", u"xy").__class__ is unicode) 2584 2731 self.assertEqual(u.replace(u"xy", u"xy"), base) 2585 self.assert _(u.center(len(u)).__class__ is unicode)2732 self.assertTrue(u.center(len(u)).__class__ is unicode) 2586 2733 self.assertEqual(u.center(len(u)), base) 2587 self.assert _(u.ljust(len(u)).__class__ is unicode)2734 self.assertTrue(u.ljust(len(u)).__class__ is unicode) 2588 2735 self.assertEqual(u.ljust(len(u)), base) 2589 self.assert _(u.rjust(len(u)).__class__ is unicode)2736 self.assertTrue(u.rjust(len(u)).__class__ is unicode) 2590 2737 self.assertEqual(u.rjust(len(u)), base) 2591 self.assert _(u.lower().__class__ is unicode)2738 self.assertTrue(u.lower().__class__ is unicode) 2592 2739 self.assertEqual(u.lower(), base) 2593 self.assert _(u.upper().__class__ is unicode)2740 self.assertTrue(u.upper().__class__ is unicode) 2594 2741 self.assertEqual(u.upper(), base) 2595 self.assert _(u.capitalize().__class__ is unicode)2742 self.assertTrue(u.capitalize().__class__ is unicode) 2596 2743 self.assertEqual(u.capitalize(), base) 2597 self.assert _(u.title().__class__ is unicode)2744 self.assertTrue(u.title().__class__ is unicode) 2598 2745 self.assertEqual(u.title(), base) 2599 self.assert _((u + u"").__class__ is unicode)2746 self.assertTrue((u + u"").__class__ is unicode) 2600 2747 self.assertEqual(u + u"", base) 2601 self.assert _((u"" + u).__class__ is unicode)2748 self.assertTrue((u"" + u).__class__ is unicode) 2602 2749 self.assertEqual(u"" + u, base) 2603 self.assert _((u * 0).__class__ is unicode)2750 self.assertTrue((u * 0).__class__ is unicode) 2604 2751 self.assertEqual(u * 0, u"") 2605 self.assert _((u * 1).__class__ is unicode)2752 self.assertTrue((u * 1).__class__ is unicode) 2606 2753 self.assertEqual(u * 1, base) 2607 self.assert _((u * 2).__class__ is unicode)2754 self.assertTrue((u * 2).__class__ is unicode) 2608 2755 self.assertEqual(u * 2, base + base) 2609 self.assert _(u[:].__class__ is unicode)2756 self.assertTrue(u[:].__class__ is unicode) 2610 2757 self.assertEqual(u[:], base) 2611 self.assert _(u[0:0].__class__ is unicode)2758 self.assertTrue(u[0:0].__class__ is unicode) 2612 2759 self.assertEqual(u[0:0], u"") 2613 2760 … … 2728 2875 self.assertEqual(d[cistr('tWo')], 2) 2729 2876 self.assertEqual(d[cistr('THrEE')], 3) 2730 self.assert _(cistr('ONe') ind)2877 self.assertIn(cistr('ONe'), d) 2731 2878 self.assertEqual(d.get(cistr('thrEE')), 3) 2732 2879 … … 2755 2902 for x in 1, 2, 3: 2756 2903 for y in 1, 2, 3: 2757 self.assert _(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))2904 self.assertTrue(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) 2758 2905 for op in "<", "<=", "==", "!=", ">", ">=": 2759 self.assert _(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),2906 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), 2760 2907 "x=%d, y=%d" % (x, y)) 2761 self.assert _(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y))2762 self.assert _(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y))2908 self.assertTrue(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) 2909 self.assertTrue(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) 2763 2910 2764 2911 def test_rich_comparisons(self): … … 2833 2980 for y in 1, 2, 3: 2834 2981 for op in "<", "<=", "==", "!=", ">", ">=": 2835 self.assert _(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),2982 self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), 2836 2983 "x=%d, y=%d" % (x, y)) 2837 self.assert _(eval("c[x] %s y" % op) == eval("x %s y" % op),2984 self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op), 2838 2985 "x=%d, y=%d" % (x, y)) 2839 self.assert _(eval("x %s c[y]" % op) == eval("x %s y" % op),2986 self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op), 2840 2987 "x=%d, y=%d" % (x, y)) 2841 2988 … … 2903 3050 x = cls() 2904 3051 x.__class__ = cls2 2905 self.assert _(x.__class__ is cls2)3052 self.assertTrue(x.__class__ is cls2) 2906 3053 x.__class__ = cls 2907 self.assert _(x.__class__ is cls)3054 self.assertTrue(x.__class__ is cls) 2908 3055 def cant(x, C): 2909 3056 try: … … 2915 3062 try: 2916 3063 delattr(x, "__class__") 2917 except TypeError:3064 except (TypeError, AttributeError): 2918 3065 pass 2919 3066 else: … … 2967 3114 x.a = 1 2968 3115 x.__class__ = cls2 2969 self.assert _(x.__class__ is cls2,3116 self.assertTrue(x.__class__ is cls2, 2970 3117 "assigning %r as __class__ for %r silently failed" % (cls2, x)) 2971 3118 self.assertEqual(x.a, 1) 2972 3119 x.__class__ = cls 2973 self.assert _(x.__class__ is cls,3120 self.assertTrue(x.__class__ is cls, 2974 3121 "assigning %r as __class__ for %r silently failed" % (cls, x)) 2975 3122 self.assertEqual(x.a, 1) … … 3059 3206 3060 3207 # Exception's __dict__ can be replaced, but not deleted 3208 # (at least not any more than regular exception's __dict__ can 3209 # be deleted; on CPython it is not the case, whereas on PyPy they 3210 # can, just like any other new-style instance's __dict__.) 3211 def can_delete_dict(e): 3212 try: 3213 del e.__dict__ 3214 except (TypeError, AttributeError): 3215 return False 3216 else: 3217 return True 3061 3218 class Exception1(Exception, Base): 3062 3219 pass … … 3067 3224 e.__dict__ = {"a": 1} 3068 3225 self.assertEqual(e.a, 1) 3069 try: 3070 del e.__dict__ 3071 except (TypeError, AttributeError): 3072 pass 3073 else: 3074 self.fail("%r's __dict__ can be deleted" % e) 3226 self.assertEqual(can_delete_dict(e), can_delete_dict(ValueError())) 3075 3227 3076 3228 def test_pickles(self): … … 3136 3288 s = p.dumps(cls, bin) 3137 3289 cls2 = p.loads(s) 3138 self.assert _(cls2 is cls)3290 self.assertTrue(cls2 is cls) 3139 3291 3140 3292 a = C1(1, 2); a.append(42); a.append(24) … … 3166 3318 for cls in C, C1, C2: 3167 3319 cls2 = copy.deepcopy(cls) 3168 self.assert _(cls2 is cls)3320 self.assertTrue(cls2 is cls) 3169 3321 3170 3322 a = C1(1, 2); a.append(42); a.append(24) … … 3365 3517 3366 3518 # Test a nasty bug in recurse_down_subclasses() 3367 import gc3368 3519 class A(object): 3369 3520 pass … … 3371 3522 pass 3372 3523 del B 3373 gc.collect()3524 test_support.gc_collect() 3374 3525 A.__setitem__ = lambda *a: None # crash 3375 3526 … … 3463 3614 self.assertEqual(log, []) 3464 3615 del c 3616 test_support.gc_collect() 3465 3617 self.assertEqual(log, [1]) 3466 3618 … … 3558 3710 self.assertEqual(hasattr(m, "__file__"), 0) 3559 3711 self.assertEqual(hasattr(m, "foo"), 0) 3560 self.assert Equal(m.__dict__, None)3712 self.assertFalse(m.__dict__) # None or {} are both reasonable answers 3561 3713 m.foo = 1 3562 3714 self.assertEqual(m.__dict__, {"foo": 1}) … … 3693 3845 c.attr = 42 3694 3846 3695 # The most interesting thing here is whether this blows up, due to flawed 3696 # GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 bug). 3847 # The most interesting thing here is whether this blows up, due to 3848 # flawed GC tracking logic in typeobject.c's call_finalizer() (a 2.2.1 3849 # bug). 3697 3850 del c 3698 3851 3699 3852 # If that didn't blow up, it's also interesting to see whether clearing 3700 # the last container slot works: that will attempt to delete c again, 3701 # which will cause c to get appended back to the container again "during" 3702 # the del. 3853 # the last container slot works: that will attempt to delete c again, 3854 # which will cause c to get appended back to the container again 3855 # "during" the del. (On non-CPython implementations, however, __del__ 3856 # is typically not called again.) 3857 test_support.gc_collect() 3858 self.assertEqual(len(C.container), 1) 3703 3859 del C.container[-1] 3704 self.assertEqual(len(C.container), 1) 3705 self.assertEqual(C.container[-1].attr, 42) 3860 if test_support.check_impl_detail(): 3861 test_support.gc_collect() 3862 self.assertEqual(len(C.container), 1) 3863 self.assertEqual(C.container[-1].attr, 42) 3706 3864 3707 3865 # Make c mortal again, so that the test framework with -l doesn't report … … 3729 3887 class C(A,B) : 3730 3888 __slots__=() 3731 self.assertEqual(C.__basicsize__, B.__basicsize__) 3732 self.assert_(hasattr(C, '__dict__')) 3733 self.assert_(hasattr(C, '__weakref__')) 3889 if test_support.check_impl_detail(): 3890 self.assertEqual(C.__basicsize__, B.__basicsize__) 3891 self.assertTrue(hasattr(C, '__dict__')) 3892 self.assertTrue(hasattr(C, '__weakref__')) 3734 3893 C().x = 2 3735 3894 … … 3785 3944 self.assertEqual(C2.__subclasses__(), [D]) 3786 3945 3787 # stuff that shouldn't:3788 class L(list):3789 pass3790 3791 try:3792 L.__bases__ = (dict,)3793 except TypeError:3794 pass3795 else:3796 self.fail("shouldn't turn list subclass into dict subclass")3797 3798 try:3799 list.__bases__ = (dict,)3800 except TypeError:3801 pass3802 else:3803 self.fail("shouldn't be able to assign to list.__bases__")3804 3805 try:3806 D.__bases__ = (C2, list)3807 except TypeError:3808 pass3809 else:3810 assert 0, "best_base calculation found wanting"3811 3812 3946 try: 3813 3947 del D.__bases__ 3814 except TypeError:3948 except (TypeError, AttributeError): 3815 3949 pass 3816 3950 else: … … 3879 4013 if tp is not object: 3880 4014 self.assertEqual(len(tp.__bases__), 1, tp) 4015 4016 class L(list): 4017 pass 4018 4019 class C(object): 4020 pass 4021 4022 class D(C): 4023 pass 4024 4025 try: 4026 L.__bases__ = (dict,) 4027 except TypeError: 4028 pass 4029 else: 4030 self.fail("shouldn't turn list subclass into dict subclass") 4031 4032 try: 4033 list.__bases__ = (dict,) 4034 except TypeError: 4035 pass 4036 else: 4037 self.fail("shouldn't be able to assign to list.__bases__") 4038 4039 try: 4040 D.__bases__ = (C, list) 4041 except TypeError: 4042 pass 4043 else: 4044 assert 0, "best_base calculation found wanting" 3881 4045 3882 4046 … … 3973 4137 self.assertEqual((C.__module__, C.__name__), (mod, 'D.E')) 3974 4138 4139 def test_evil_type_name(self): 4140 # A badly placed Py_DECREF in type_set_name led to arbitrary code 4141 # execution while the type structure was not in a sane state, and a 4142 # possible segmentation fault as a result. See bug #16447. 4143 class Nasty(str): 4144 def __del__(self): 4145 C.__name__ = "other" 4146 4147 class C(object): 4148 pass 4149 4150 C.__name__ = Nasty("abc") 4151 C.__name__ = "normal" 4152 3975 4153 def test_subclass_right_op(self): 3976 4154 # Testing correct dispatch of subclass overloading __r<op>__... … … 4024 4202 self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail 4025 4203 4204 @test_support.impl_detail("testing an internal kind of method object") 4026 4205 def test_meth_class_get(self): 4027 4206 # Testing __get__ method of METH_CLASS C methods... … … 4082 4261 a = C() 4083 4262 pa = Proxy(a) 4084 self.assert _(isinstance(a, C)) # Baseline4085 self.assert _(isinstance(pa, C)) # Test4263 self.assertIsInstance(a, C) # Baseline 4264 self.assertIsInstance(pa, C) # Test 4086 4265 # Test with a classic subclass 4087 4266 class D(C): … … 4089 4268 a = D() 4090 4269 pa = Proxy(a) 4091 self.assert _(isinstance(a, C)) # Baseline4092 self.assert _(isinstance(pa, C)) # Test4270 self.assertIsInstance(a, C) # Baseline 4271 self.assertIsInstance(pa, C) # Test 4093 4272 # Test with a new-style class 4094 4273 class C(object): … … 4096 4275 a = C() 4097 4276 pa = Proxy(a) 4098 self.assert _(isinstance(a, C)) # Baseline4099 self.assert _(isinstance(pa, C)) # Test4277 self.assertIsInstance(a, C) # Baseline 4278 self.assertIsInstance(pa, C) # Test 4100 4279 # Test with a new-style subclass 4101 4280 class D(C): … … 4103 4282 a = D() 4104 4283 pa = Proxy(a) 4105 self.assert _(isinstance(a, C)) # Baseline4106 self.assert _(isinstance(pa, C)) # Test4284 self.assertIsInstance(a, C) # Baseline 4285 self.assertIsInstance(pa, C) # Test 4107 4286 4108 4287 def test_proxy_super(self): … … 4136 4315 pass 4137 4316 else: 4138 self.fail("Carlo Verre __setattr__ suc eeded!")4317 self.fail("Carlo Verre __setattr__ succeeded!") 4139 4318 try: 4140 4319 object.__delattr__(str, "lower") … … 4172 4351 def test_file_fault(self): 4173 4352 # Testing sys.stdout is changed in getattr... 4174 import sys4353 test_stdout = sys.stdout 4175 4354 class StdoutGuard: 4176 4355 def __getattr__(self, attr): … … 4182 4361 except RuntimeError: 4183 4362 pass 4363 finally: 4364 sys.stdout = test_stdout 4184 4365 4185 4366 def test_vicious_descriptor_nonsense(self): … … 4209 4390 self.assertEqual(c.attr, 1) 4210 4391 # this makes a crash more likely: 4211 import gc; gc.collect()4392 test_support.gc_collect() 4212 4393 self.assertEqual(hasattr(c, 'attr'), False) 4213 4394 … … 4231 4412 self.assertEqual(l.__add__, l.__add__) 4232 4413 self.assertEqual(l.__add__, [].__add__) 4233 self.assert_(l.__add__ != [5].__add__) 4234 self.assert_(l.__add__ != l.__mul__) 4235 self.assert_(l.__add__.__name__ == '__add__') 4236 self.assert_(l.__add__.__self__ is l) 4237 self.assert_(l.__add__.__objclass__ is list) 4414 self.assertTrue(l.__add__ != [5].__add__) 4415 self.assertTrue(l.__add__ != l.__mul__) 4416 self.assertTrue(l.__add__.__name__ == '__add__') 4417 if hasattr(l.__add__, '__self__'): 4418 # CPython 4419 self.assertTrue(l.__add__.__self__ is l) 4420 self.assertTrue(l.__add__.__objclass__ is list) 4421 else: 4422 # Python implementations where [].__add__ is a normal bound method 4423 self.assertTrue(l.__add__.im_self is l) 4424 self.assertTrue(l.__add__.im_class is list) 4238 4425 self.assertEqual(l.__add__.__doc__, list.__add__.__doc__) 4239 4426 try: … … 4252 4439 # Testing NotImplemented... 4253 4440 # all binary methods should be able to return a NotImplemented 4254 import sys4255 import types4256 4441 import operator 4257 4442 … … 4332 4517 self.assertEqual(c.value, 3) 4333 4518 4519 def test_set_and_no_get(self): 4520 # See 4521 # http://mail.python.org/pipermail/python-dev/2010-January/095637.html 4522 class Descr(object): 4523 4524 def __init__(self, name): 4525 self.name = name 4526 4527 def __set__(self, obj, value): 4528 obj.__dict__[self.name] = value 4529 descr = Descr("a") 4530 4531 class X(object): 4532 a = descr 4533 4534 x = X() 4535 self.assertIs(x.a, descr) 4536 x.a = 42 4537 self.assertEqual(x.a, 42) 4538 4539 # Also check type_getattro for correctness. 4540 class Meta(type): 4541 pass 4542 class X(object): 4543 __metaclass__ = Meta 4544 X.a = 42 4545 Meta.a = Descr("a") 4546 self.assertEqual(X.a, 42) 4547 4334 4548 def test_getattr_hooks(self): 4335 4549 # issue 4230 … … 4353 4567 4354 4568 self.assertRaises(AttributeError, getattr, A(), "attr") 4355 self.assertEqual s(descr.counter, 1)4569 self.assertEqual(descr.counter, 1) 4356 4570 self.assertRaises(AttributeError, getattr, B(), "attr") 4357 self.assertEqual s(descr.counter, 2)4571 self.assertEqual(descr.counter, 2) 4358 4572 self.assertRaises(AttributeError, getattr, C(), "attr") 4359 self.assertEquals(descr.counter, 4) 4360 4361 import gc 4573 self.assertEqual(descr.counter, 4) 4574 4362 4575 class EvilGetattribute(object): 4363 4576 # This used to segfault … … 4372 4585 self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr") 4373 4586 4587 def test_type___getattribute__(self): 4588 self.assertRaises(TypeError, type.__getattribute__, list, type) 4589 4590 def test_abstractmethods(self): 4591 # type pretends not to have __abstractmethods__. 4592 self.assertRaises(AttributeError, getattr, type, "__abstractmethods__") 4593 class meta(type): 4594 pass 4595 self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__") 4596 class X(object): 4597 pass 4598 with self.assertRaises(AttributeError): 4599 del X.__abstractmethods__ 4600 4601 def test_proxy_call(self): 4602 class FakeStr(object): 4603 __class__ = str 4604 4605 fake_str = FakeStr() 4606 # isinstance() reads __class__ on new style classes 4607 self.assertTrue(isinstance(fake_str, str)) 4608 4609 # call a method descriptor 4610 with self.assertRaises(TypeError): 4611 str.split(fake_str) 4612 4613 # call a slot wrapper descriptor 4614 with self.assertRaises(TypeError): 4615 str.__add__(fake_str, "abc") 4616 4617 def test_repr_as_str(self): 4618 # Issue #11603: crash or infinite loop when rebinding __str__ as 4619 # __repr__. 4620 class Foo(object): 4621 pass 4622 Foo.__repr__ = Foo.__str__ 4623 foo = Foo() 4624 self.assertRaises(RuntimeError, str, foo) 4625 self.assertRaises(RuntimeError, repr, foo) 4626 4627 def test_mixing_slot_wrappers(self): 4628 class X(dict): 4629 __setattr__ = dict.__setitem__ 4630 x = X() 4631 x.y = 42 4632 self.assertEqual(x["y"], 42) 4633 4634 def test_cycle_through_dict(self): 4635 # See bug #1469629 4636 class X(dict): 4637 def __init__(self): 4638 dict.__init__(self) 4639 self.__dict__ = self 4640 x = X() 4641 x.attr = 42 4642 wr = weakref.ref(x) 4643 del x 4644 test_support.gc_collect() 4645 self.assertIsNone(wr()) 4646 for o in gc.get_objects(): 4647 self.assertIsNot(type(o), X) 4374 4648 4375 4649 class DictProxyTests(unittest.TestCase): … … 4380 4654 self.C = C 4381 4655 4656 def test_repr(self): 4657 self.assertIn('dict_proxy({', repr(vars(self.C))) 4658 self.assertIn("'meth':", repr(vars(self.C))) 4659 4382 4660 def test_iter_keys(self): 4383 4661 # Testing dict-proxy iterkeys... 4384 4662 keys = [ key for key in self.C.__dict__.iterkeys() ] 4385 4663 keys.sort() 4386 self.assertEqual s(keys, ['__dict__', '__doc__', '__module__',4664 self.assertEqual(keys, ['__dict__', '__doc__', '__module__', 4387 4665 '__weakref__', 'meth']) 4388 4666 … … 4434 4712 4435 4713 def test_main(): 4436 # Run all local test cases, with PTypesLongInitTest first. 4437 test_support.run_unittest(PTypesLongInitTest, OperatorsTest, 4438 ClassPropertiesAndMethods, DictProxyTests) 4714 deprecations = [(r'complex divmod\(\), // and % are deprecated$', 4715 DeprecationWarning)] 4716 if sys.py3kwarning: 4717 deprecations += [ 4718 ("classic (int|long) division", DeprecationWarning), 4719 ("coerce.. not supported", DeprecationWarning), 4720 (".+__(get|set|del)slice__ has been removed", DeprecationWarning)] 4721 with test_support.check_warnings(*deprecations): 4722 # Run all local test cases, with PTypesLongInitTest first. 4723 test_support.run_unittest(PTypesLongInitTest, OperatorsTest, 4724 ClassPropertiesAndMethods, DictProxyTests) 4439 4725 4440 4726 if __name__ == "__main__":
Note:
See TracChangeset
for help on using the changeset viewer.