Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/test/test_descr.py

    r2 r391  
    11import __builtin__
     2import gc
     3import sys
    24import types
    35import unittest
    4 import warnings
     6import weakref
    57
    68from copy import deepcopy
     
    5961            self.unops[name] = expr
    6062
    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_filters
    69 
    7063    def unop_test(self, a, res, expr="len(a)", meth="__len__"):
    7164        d = {'a': a}
     
    7770        while meth not in t.__dict__:
    7871            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])
    8175        self.assertEqual(m(a), res)
    8276        bm = getattr(a, meth)
     
    9791        while meth not in t.__dict__:
    9892            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])
    10096        self.assertEqual(m(a, b), res)
    10197        bm = getattr(a, meth)
     
    109105        while meth not in t.__dict__:
    110106            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])
    112110        self.assertEqual(m(a, b, c), res)
    113111        bm = getattr(a, meth)
     
    122120        while meth not in t.__dict__:
    123121            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])
    125125        d['a'] = deepcopy(a)
    126126        m(d['a'], b)
     
    139139        while meth not in t.__dict__:
    140140            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])
    142144        d['a'] = deepcopy(a)
    143145        m(d['a'], b, c)
     
    156158            t = t.__bases__[0]
    157159        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])
    159163        dictionary['a'] = deepcopy(a)
    160164        m(dictionary['a'], b, c, d)
     
    184188    def test_dicts(self):
    185189        # 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__")
    187194        self.binop_test({1:2,3:4}, 1, 1, "b in a", "__contains__")
    188195        self.binop_test({1:2,3:4}, 2, 0, "b in a", "__contains__")
     
    247254        else:
    248255            self.fail("NotImplemented should have caused TypeError")
    249         import sys
    250256        try:
    251257            C(sys.maxint+1)
     
    295301        self.assertEqual(a.prec, 12)
    296302
     303    @test_support.impl_detail("the module 'xxsubtype' is internal")
    297304    def test_spam_lists(self):
    298305        # Testing spamlist operations...
     
    338345        self.assertEqual(a.getstate(), 42)
    339346
     347    @test_support.impl_detail("the module 'xxsubtype' is internal")
    340348    def test_spam_dicts(self):
    341349        # Testing spamdict operations...
     
    393401    def test_python_dicts(self):
    394402        # 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)
    397405        d = dict()
    398406        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)
    401409        class C(dict):
    402410            state = -1
     
    411419                return self.get(key, 0)
    412420            def __setitem__(self_local, key, value):
    413                 self.assert_(isinstance(key, type(0)))
     421                self.assertIsInstance(key, type(0))
    414422                dict.__setitem__(self_local, key, value)
    415423            def setstate(self, state):
     
    417425            def getstate(self):
    418426                return self.state
    419         self.assert_(issubclass(C, dict))
     427        self.assertTrue(issubclass(C, dict))
    420428        a1 = C(12)
    421429        self.assertEqual(a1.state, 12)
     
    511519        self.assertEqual(C.name, 'C')
    512520        self.assertEqual(C.bases, ())
    513         self.assert_('spam' in C.dict)
     521        self.assertIn('spam', C.dict)
    514522        c = C()
    515523        self.assertEqual(c.spam(), 42)
     
    578586                self.__x = -x
    579587        a = A()
    580         self.assert_(not hasattr(a, "x"))
     588        self.assertTrue(not hasattr(a, "x"))
    581589        a.x = 12
    582590        self.assertEqual(a.x, 12)
     
    638646        # Testing Python subclass of module...
    639647        log = []
    640         import types, sys
    641648        MT = type(sys)
    642649        class MM(MT):
     
    872879    # by Kim Barrett et al. (OOPSLA 1996)
    873880    def test_consistency_with_epg(self):
    874         # Testing consistentcy with EPG...
     881        # Testing consistency with EPG...
    875882        class Pane(object): pass
    876883        class ScrollingMixin(object): pass
     
    893900                callable(*args)
    894901            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))
    897907            else:
    898908                self.fail("Expected %s" % exc)
     
    10871097        self.assertEqual(Counted.counter, 3)
    10881098        del x
     1099        test_support.gc_collect()
    10891100        self.assertEqual(Counted.counter, 0)
    10901101        class D(C):
     
    10951106        self.assertEqual(Counted.counter, 2)
    10961107        del x
     1108        test_support.gc_collect()
    10971109        self.assertEqual(Counted.counter, 0)
    10981110        class E(D):
     
    11041116        self.assertEqual(Counted.counter, 3)
    11051117        del x
     1118        test_support.gc_collect()
    11061119        self.assertEqual(Counted.counter, 0)
    11071120
     
    11091122        class F(object):
    11101123            __slots__ = ['a', 'b']
    1111         log = []
    11121124        s = F()
    11131125        s.a = [Counted(), s]
    11141126        self.assertEqual(Counted.counter, 1)
    11151127        s = None
    1116         import gc
    1117         gc.collect()
     1128        test_support.gc_collect()
    11181129        self.assertEqual(Counted.counter, 0)
    11191130
    11201131        # 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
    11321144        class H(object):
    11331145            __slots__ = ['a', 'b']
     
    11451157        class X(object):
    11461158            __slots__ = "a"
    1147         try:
     1159        with self.assertRaises(AttributeError):
    11481160            del X().a
    1149         except AttributeError:
    1150             pass
    1151         else:
    1152             self.fail("didn't raise AttributeError")
    11531161
    11541162    def test_slots_special(self):
     
    11571165            __slots__ = ["__dict__"]
    11581166        a = D()
    1159         self.assert_(hasattr(a, "__dict__"))
     1167        self.assertTrue(hasattr(a, "__dict__"))
    11601168        self.assertFalse(hasattr(a, "__weakref__"))
    11611169        a.foo = 42
     
    11651173            __slots__ = ["__weakref__"]
    11661174        a = W()
    1167         self.assert_(hasattr(a, "__weakref__"))
     1175        self.assertTrue(hasattr(a, "__weakref__"))
    11681176        self.assertFalse(hasattr(a, "__dict__"))
    11691177        try:
     
    11771185            __slots__ = []
    11781186        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__"))
    11811189        a.foo = 42
    11821190        self.assertEqual(a.__dict__, {"foo": 42})
     
    11851193            __slots__ = []
    11861194        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__"))
    11891197        a.foo = 42
    11901198        self.assertEqual(a.__dict__, {"foo": 42})
     
    12031211
    12041212        u = Unrelated()
    1205         self.assert_(isinstance(u, MyABC))
     1213        self.assertIsInstance(u, MyABC)
    12061214
    12071215        # This used to crash
     
    13861394        self.assertEqual(super(D,d).goo(), (D,))
    13871395
    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)
    13951399
    13961400        # Verify that classmethod() doesn't allow keyword args
     
    14021406            self.fail("classmethod shouldn't accept keyword args")
    14031407
     1408    @test_support.impl_detail("the module 'xxsubtype' is internal")
    14041409    def test_classmethods_in_c(self):
    14051410        # Testing C-based class methods...
     
    14151420        self.assertEqual(a, a1)
    14161421        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)
    14171438
    14181439    def test_staticmethods(self):
     
    14331454        self.assertEqual(D.foo(d, 1), (d, 1))
    14341455
     1456    @test_support.impl_detail("the module 'xxsubtype' is internal")
    14351457    def test_staticmethods_in_c(self):
    14361458        # Testing C-based static methods...
     
    14661488            foo = C.foo
    14671489        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 "))
    14691491
    14701492    def test_compattr(self):
     
    15491571                    def mro(self):
    15501572                        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
    15511581        except TypeError:
    15521582            pass
     
    16491679            foo = C.foo
    16501680        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))
    16521788
    16531789    def test_specials(self):
     
    16621798        c1 = C()
    16631799        c2 = C()
    1664         self.assert_(not not c1) # What?
     1800        self.assertTrue(not not c1) # What?
    16651801        self.assertNotEqual(id(c1), id(c2))
    16661802        hash(c1)
     
    16681804        self.assertEqual(cmp(c1, c2), cmp(id(c1), id(c2)))
    16691805        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)
    16731809        # Note that the module name appears in str/repr, and that varies
    16741810        # 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)
    16761812        self.assertEqual(str(c1), repr(c1))
    1677         self.assert_(-1 not in c1)
     1813        self.assertNotIn(-1, c1)
    16781814        for i in range(10):
    1679             self.assert_(i in c1)
    1680         self.assertFalse(10 in c1)
     1815            self.assertIn(i, c1)
     1816        self.assertNotIn(10, c1)
    16811817        # Test the default behavior for dynamic classes
    16821818        class D(object):
     
    16861822        d1 = D()
    16871823        d2 = D()
    1688         self.assert_(not not d1)
     1824        self.assertTrue(not not d1)
    16891825        self.assertNotEqual(id(d1), id(d2))
    16901826        hash(d1)
     
    16931829        self.assertEqual(d1, d1)
    16941830        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)
    16971833        # Note that the module name appears in str/repr, and that varies
    16981834        # 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)
    17001836        self.assertEqual(str(d1), repr(d1))
    1701         self.assert_(-1 not in d1)
     1837        self.assertNotIn(-1, d1)
    17021838        for i in range(10):
    1703             self.assert_(i in d1)
    1704         self.assertFalse(10 in d1)
     1839            self.assertIn(i, d1)
     1840        self.assertNotIn(10, d1)
    17051841        # Test overridden behavior for static classes
    17061842        class Proxy(object):
     
    17271863        p_1 = Proxy(-1)
    17281864        self.assertFalse(p0)
    1729         self.assert_(not not p1)
     1865        self.assertTrue(not not p1)
    17301866        self.assertEqual(hash(p0), hash(0))
    17311867        self.assertEqual(p0, p0)
    17321868        self.assertNotEqual(p0, p1)
    1733         self.assert_(not p0 != p0)
     1869        self.assertTrue(not p0 != p0)
    17341870        self.assertEqual(not p0, p1)
    17351871        self.assertEqual(cmp(p0, p1), -1)
     
    17391875        self.assertEqual(repr(p0), "Proxy(0)")
    17401876        p10 = Proxy(range(10))
    1741         self.assertFalse(-1 in p10)
     1877        self.assertNotIn(-1, p10)
    17421878        for i in range(10):
    1743             self.assert_(i in p10)
    1744         self.assertFalse(10 in p10)
     1879            self.assertIn(i, p10)
     1880        self.assertNotIn(10, p10)
    17451881        # Test overridden behavior for dynamic classes
    17461882        class DProxy(object):
     
    17671903        p_1 = DProxy(-1)
    17681904        self.assertFalse(p0)
    1769         self.assert_(not not p1)
     1905        self.assertTrue(not not p1)
    17701906        self.assertEqual(hash(p0), hash(0))
    17711907        self.assertEqual(p0, p0)
     
    17791915        self.assertEqual(repr(p0), "DProxy(0)")
    17801916        p10 = DProxy(range(10))
    1781         self.assertFalse(-1 in p10)
     1917        self.assertNotIn(-1, p10)
    17821918        for i in range(10):
    1783             self.assert_(i in p10)
    1784         self.assertFalse(10 in p10)
     1919            self.assertIn(i, p10)
     1920        self.assertNotIn(10, p10)
    17851921
    17861922        # Safety test for __cmp__
    17871923        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
    17901928            try:
    17911929                a.__class__.__cmp__(a, b)
     
    18031941        unsafecmp(1L, 1)
    18041942
    1805     def test_recursions(self):
     1943    @test_support.impl_detail("custom logic for printing to real file objects")
     1944    def test_recursions_1(self):
    18061945        # Testing recursion checks ...
    18071946        class Letter(str):
     
    18151954                return self
    18161955        # sys.stdout needs to be the original to trigger the recursion bug
    1817         import sys
    18181956        test_stdout = sys.stdout
    18191957        sys.stdout = test_support.get_original_stdout()
     
    18281966            sys.stdout = test_stdout
    18291967
     1968    def test_recursions_2(self):
    18301969        # Bug #1202533.
    18311970        class A(object):
     
    18481987        self.assertEqual(r(), c)
    18491988        del c
     1989        test_support.gc_collect()
    18501990        self.assertEqual(r(), None)
    18511991        del r
     
    18561996            weakref.ref(no)
    18571997        except TypeError, msg:
    1858             self.assert_(str(msg).find("weak reference") >= 0)
     1998            self.assertTrue(str(msg).find("weak reference") >= 0)
    18591999        else:
    18602000            self.fail("weakref.ref(no) should be illegal")
     
    18652005        self.assertEqual(r(), yes)
    18662006        del yes
     2007        test_support.gc_collect()
    18672008        self.assertEqual(r(), None)
    18682009        del r
     
    18922033
    18932034        raw = C.__dict__['x']
    1894         self.assert_(isinstance(raw, property))
     2035        self.assertIsInstance(raw, property)
    18952036
    18962037        attrs = dir(raw)
    1897         self.assert_("__doc__" in attrs)
    1898         self.assert_("fget" in attrs)
    1899         self.assert_("fset" in attrs)
    1900         self.assert_("fdel" in attrs)
     2038        self.assertIn("__doc__", attrs)
     2039        self.assertIn("fget", attrs)
     2040        self.assertIn("fset", attrs)
     2041        self.assertIn("fdel", attrs)
    19012042
    19022043        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'])
    19062047
    19072048        for attr in "__doc__", "fget", "fset", "fdel":
     
    19282069            self.fail("expected ZeroDivisionError from bad property")
    19292070
     2071    @unittest.skipIf(sys.flags.optimize >= 2,
     2072                     "Docstrings are omitted with -O2 and above")
     2073    def test_properties_doc_attrib(self):
    19302074        class E(object):
    19312075            def getter(self):
     
    19402084            self.assertEqual(prop2.__doc__, None)
    19412085
     2086    def test_testcapi_no_segfault(self):
    19422087        # this segfaulted in 2.5b2
    19432088        try:
     
    19652110        self.assertFalse(hasattr(c, "foo"))
    19662111        c.foo = -42
    1967         self.assert_(hasattr(c, '_foo'))
     2112        self.assertTrue(hasattr(c, '_foo'))
    19682113        self.assertEqual(c._foo, 42)
    19692114        self.assertEqual(c.foo, 42)
     
    21162261        cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
    21172262        self.assertEqual(dir(C), cstuff)
    2118         self.assert_('im_self' in dir(C.Cmethod))
     2263        self.assertIn('im_self', dir(C.Cmethod))
    21192264
    21202265        c = C()  # c.__doc__ is an odd thing to see here; ditto c.__module__.
     
    21242269        c.cmethod = lambda self: 0
    21252270        self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
    2126         self.assert_('im_self' in dir(c.Cmethod))
     2271        self.assertIn('im_self', dir(c.Cmethod))
    21272272
    21282273        class A(C):
     
    21322277        astuff = ['Adata', 'Amethod'] + cstuff
    21332278        self.assertEqual(dir(A), astuff)
    2134         self.assert_('im_self' in dir(A.Amethod))
     2279        self.assertIn('im_self', dir(A.Amethod))
    21352280        a = A()
    21362281        self.assertEqual(dir(a), astuff)
    2137         self.assert_('im_self' in dir(a.Amethod))
     2282        self.assertIn('im_self', dir(a.Amethod))
    21382283        a.adata = 42
    21392284        a.amethod = lambda self: 3
     
    21542299        c = C()
    21552300        self.assertEqual(interesting(dir(c)), cstuff)
    2156         self.assert_('im_self' in dir(C.Cmethod))
     2301        self.assertIn('im_self', dir(C.Cmethod))
    21572302
    21582303        c.cdata = 2
    21592304        c.cmethod = lambda self: 0
    21602305        self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
    2161         self.assert_('im_self' in dir(c.Cmethod))
     2306        self.assertIn('im_self', dir(c.Cmethod))
    21622307
    21632308        class A(C):
     
    21672312        astuff = ['Adata', 'Amethod'] + cstuff
    21682313        self.assertEqual(interesting(dir(A)), astuff)
    2169         self.assert_('im_self' in dir(A.Amethod))
     2314        self.assertIn('im_self', dir(A.Amethod))
    21702315        a = A()
    21712316        self.assertEqual(interesting(dir(a)), astuff)
     
    21732318        a.amethod = lambda self: 3
    21742319        self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
    2175         self.assert_('im_self' in dir(a.Amethod))
     2320        self.assertIn('im_self', dir(a.Amethod))
    21762321
    21772322        # Try a module subclass.
    2178         import sys
    21792323        class M(type(sys)):
    21802324            pass
     
    22012345        # Two essentially featureless objects, just inheriting stuff from
    22022346        # 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))
    22042351
    22052352        # Nasty test case for proxied objects
     
    23542501        self.assertEqual(a, 12345)
    23552502        self.assertEqual(int(a), 12345)
    2356         self.assert_(int(a).__class__ is int)
     2503        self.assertTrue(int(a).__class__ is int)
    23572504        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)
    23632510
    23642511        class octlong(long):
     
    23802527        self.assertEqual(long(a), 12345L)
    23812528        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)
    23992546
    24002547        # Because octlong overrides __add__, we can't check the absence of +0
     
    24032550            pass
    24042551        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)
    24072554
    24082555        # Check that negative clones don't segfault
    24092556        a = longclone(-1)
    24102557        self.assertEqual(a.__dict__, {})
    2411         self.assertEqual(long(a), -1)  # self.assert_ PyNumber_Long() copies the sign bit
     2558        self.assertEqual(long(a), -1)  # self.assertTrue PyNumber_Long() copies the sign bit
    24122559
    24132560        class precfloat(float):
     
    24212568        self.assertEqual(a, 12345.0)
    24222569        self.assertEqual(float(a), 12345.0)
    2423         self.assert_(float(a).__class__ is float)
     2570        self.assertTrue(float(a).__class__ is float)
    24242571        self.assertEqual(hash(a), hash(12345.0))
    2425         self.assert_((+a).__class__ is float)
     2572        self.assertTrue((+a).__class__ is float)
    24262573
    24272574        class madcomplex(complex):
     
    24712618        a = madtuple((1,2,3,4,5))
    24722619        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)
    24742621        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)
    24792626        a = madtuple(())
    24802627        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)
    24872634
    24882635        class madstring(str):
     
    25062653        s = madstring("12345")
    25072654        self.assertEqual(str(s), "12345")
    2508         self.assert_(str(s).__class__ is str)
     2655        self.assertTrue(str(s).__class__ is str)
    25092656
    25102657        base = "\x00" * 5
     
    25122659        self.assertEqual(s, base)
    25132660        self.assertEqual(str(s), base)
    2514         self.assert_(str(s).__class__ is str)
     2661        self.assertTrue(str(s).__class__ is str)
    25152662        self.assertEqual(hash(s), hash(base))
    25162663        self.assertEqual({s: 1}[base], 1)
    25172664        self.assertEqual({base: 1}[s], 1)
    2518         self.assert_((s + "").__class__ is str)
     2665        self.assertTrue((s + "").__class__ is str)
    25192666        self.assertEqual(s + "", base)
    2520         self.assert_(("" + s).__class__ is str)
     2667        self.assertTrue(("" + s).__class__ is str)
    25212668        self.assertEqual("" + s, base)
    2522         self.assert_((s * 0).__class__ is str)
     2669        self.assertTrue((s * 0).__class__ is str)
    25232670        self.assertEqual(s * 0, "")
    2524         self.assert_((s * 1).__class__ is str)
     2671        self.assertTrue((s * 1).__class__ is str)
    25252672        self.assertEqual(s * 1, base)
    2526         self.assert_((s * 2).__class__ is str)
     2673        self.assertTrue((s * 2).__class__ is str)
    25272674        self.assertEqual(s * 2, base + base)
    2528         self.assert_(s[:].__class__ is str)
     2675        self.assertTrue(s[:].__class__ is str)
    25292676        self.assertEqual(s[:], base)
    2530         self.assert_(s[0:0].__class__ is str)
     2677        self.assertTrue(s[0:0].__class__ is str)
    25312678        self.assertEqual(s[0:0], "")
    2532         self.assert_(s.strip().__class__ is str)
     2679        self.assertTrue(s.strip().__class__ is str)
    25332680        self.assertEqual(s.strip(), base)
    2534         self.assert_(s.lstrip().__class__ is str)
     2681        self.assertTrue(s.lstrip().__class__ is str)
    25352682        self.assertEqual(s.lstrip(), base)
    2536         self.assert_(s.rstrip().__class__ is str)
     2683        self.assertTrue(s.rstrip().__class__ is str)
    25372684        self.assertEqual(s.rstrip(), base)
    25382685        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)
    25402687        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)
    25422689        self.assertEqual(s.translate(identitytab, "x"), base)
    25432690        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)
    25452692        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)
    25472694        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)
    25492696        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)
    25512698        self.assertEqual(s.center(len(s)), base)
    2552         self.assert_(s.lower().__class__ is str)
     2699        self.assertTrue(s.lower().__class__ is str)
    25532700        self.assertEqual(s.lower(), base)
    25542701
     
    25692716        u = madunicode(base)
    25702717        self.assertEqual(unicode(u), base)
    2571         self.assert_(unicode(u).__class__ is unicode)
     2718        self.assertTrue(unicode(u).__class__ is unicode)
    25722719        self.assertEqual(hash(u), hash(base))
    25732720        self.assertEqual({u: 1}[base], 1)
    25742721        self.assertEqual({base: 1}[u], 1)
    2575         self.assert_(u.strip().__class__ is unicode)
     2722        self.assertTrue(u.strip().__class__ is unicode)
    25762723        self.assertEqual(u.strip(), base)
    2577         self.assert_(u.lstrip().__class__ is unicode)
     2724        self.assertTrue(u.lstrip().__class__ is unicode)
    25782725        self.assertEqual(u.lstrip(), base)
    2579         self.assert_(u.rstrip().__class__ is unicode)
     2726        self.assertTrue(u.rstrip().__class__ is unicode)
    25802727        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)
    25822729        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)
    25842731        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)
    25862733        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)
    25882735        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)
    25902737        self.assertEqual(u.rjust(len(u)), base)
    2591         self.assert_(u.lower().__class__ is unicode)
     2738        self.assertTrue(u.lower().__class__ is unicode)
    25922739        self.assertEqual(u.lower(), base)
    2593         self.assert_(u.upper().__class__ is unicode)
     2740        self.assertTrue(u.upper().__class__ is unicode)
    25942741        self.assertEqual(u.upper(), base)
    2595         self.assert_(u.capitalize().__class__ is unicode)
     2742        self.assertTrue(u.capitalize().__class__ is unicode)
    25962743        self.assertEqual(u.capitalize(), base)
    2597         self.assert_(u.title().__class__ is unicode)
     2744        self.assertTrue(u.title().__class__ is unicode)
    25982745        self.assertEqual(u.title(), base)
    2599         self.assert_((u + u"").__class__ is unicode)
     2746        self.assertTrue((u + u"").__class__ is unicode)
    26002747        self.assertEqual(u + u"", base)
    2601         self.assert_((u"" + u).__class__ is unicode)
     2748        self.assertTrue((u"" + u).__class__ is unicode)
    26022749        self.assertEqual(u"" + u, base)
    2603         self.assert_((u * 0).__class__ is unicode)
     2750        self.assertTrue((u * 0).__class__ is unicode)
    26042751        self.assertEqual(u * 0, u"")
    2605         self.assert_((u * 1).__class__ is unicode)
     2752        self.assertTrue((u * 1).__class__ is unicode)
    26062753        self.assertEqual(u * 1, base)
    2607         self.assert_((u * 2).__class__ is unicode)
     2754        self.assertTrue((u * 2).__class__ is unicode)
    26082755        self.assertEqual(u * 2, base + base)
    2609         self.assert_(u[:].__class__ is unicode)
     2756        self.assertTrue(u[:].__class__ is unicode)
    26102757        self.assertEqual(u[:], base)
    2611         self.assert_(u[0:0].__class__ is unicode)
     2758        self.assertTrue(u[0:0].__class__ is unicode)
    26122759        self.assertEqual(u[0:0], u"")
    26132760
     
    27282875        self.assertEqual(d[cistr('tWo')], 2)
    27292876        self.assertEqual(d[cistr('THrEE')], 3)
    2730         self.assert_(cistr('ONe') in d)
     2877        self.assertIn(cistr('ONe'), d)
    27312878        self.assertEqual(d.get(cistr('thrEE')), 3)
    27322879
     
    27552902            for x in 1, 2, 3:
    27562903                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))
    27582905                    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),
    27602907                               "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))
    27632910
    27642911    def test_rich_comparisons(self):
     
    28332980                for y in 1, 2, 3:
    28342981                    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),
    28362983                               "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),
    28382985                               "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),
    28402987                               "x=%d, y=%d" % (x, y))
    28412988
     
    29033050                x = cls()
    29043051                x.__class__ = cls2
    2905                 self.assert_(x.__class__ is cls2)
     3052                self.assertTrue(x.__class__ is cls2)
    29063053                x.__class__ = cls
    2907                 self.assert_(x.__class__ is cls)
     3054                self.assertTrue(x.__class__ is cls)
    29083055        def cant(x, C):
    29093056            try:
     
    29153062            try:
    29163063                delattr(x, "__class__")
    2917             except TypeError:
     3064            except (TypeError, AttributeError):
    29183065                pass
    29193066            else:
     
    29673114            x.a = 1
    29683115            x.__class__ = cls2
    2969             self.assert_(x.__class__ is cls2,
     3116            self.assertTrue(x.__class__ is cls2,
    29703117                   "assigning %r as __class__ for %r silently failed" % (cls2, x))
    29713118            self.assertEqual(x.a, 1)
    29723119            x.__class__ = cls
    2973             self.assert_(x.__class__ is cls,
     3120            self.assertTrue(x.__class__ is cls,
    29743121                   "assigning %r as __class__ for %r silently failed" % (cls, x))
    29753122            self.assertEqual(x.a, 1)
     
    30593206
    30603207        # 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
    30613218        class Exception1(Exception, Base):
    30623219            pass
     
    30673224            e.__dict__ = {"a": 1}
    30683225            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()))
    30753227
    30763228    def test_pickles(self):
     
    31363288                    s = p.dumps(cls, bin)
    31373289                    cls2 = p.loads(s)
    3138                     self.assert_(cls2 is cls)
     3290                    self.assertTrue(cls2 is cls)
    31393291
    31403292                a = C1(1, 2); a.append(42); a.append(24)
     
    31663318        for cls in C, C1, C2:
    31673319            cls2 = copy.deepcopy(cls)
    3168             self.assert_(cls2 is cls)
     3320            self.assertTrue(cls2 is cls)
    31693321
    31703322        a = C1(1, 2); a.append(42); a.append(24)
     
    33653517
    33663518        # Test a nasty bug in recurse_down_subclasses()
    3367         import gc
    33683519        class A(object):
    33693520            pass
     
    33713522            pass
    33723523        del B
    3373         gc.collect()
     3524        test_support.gc_collect()
    33743525        A.__setitem__ = lambda *a: None # crash
    33753526
     
    34633614        self.assertEqual(log, [])
    34643615        del c
     3616        test_support.gc_collect()
    34653617        self.assertEqual(log, [1])
    34663618
     
    35583710        self.assertEqual(hasattr(m, "__file__"), 0)
    35593711        self.assertEqual(hasattr(m, "foo"), 0)
    3560         self.assertEqual(m.__dict__, None)
     3712        self.assertFalse(m.__dict__)   # None or {} are both reasonable answers
    35613713        m.foo = 1
    35623714        self.assertEqual(m.__dict__, {"foo": 1})
     
    36933845        c.attr = 42
    36943846
    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).
    36973850        del c
    36983851
    36993852        # 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)
    37033859        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)
    37063864
    37073865        # Make c mortal again, so that the test framework with -l doesn't report
     
    37293887        class C(A,B) :
    37303888            __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__'))
    37343893        C().x = 2
    37353894
     
    37853944        self.assertEqual(C2.__subclasses__(), [D])
    37863945
    3787         # stuff that shouldn't:
    3788         class L(list):
    3789             pass
    3790 
    3791         try:
    3792             L.__bases__ = (dict,)
    3793         except TypeError:
    3794             pass
    3795         else:
    3796             self.fail("shouldn't turn list subclass into dict subclass")
    3797 
    3798         try:
    3799             list.__bases__ = (dict,)
    3800         except TypeError:
    3801             pass
    3802         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             pass
    3809         else:
    3810             assert 0, "best_base calculation found wanting"
    3811 
    38123946        try:
    38133947            del D.__bases__
    3814         except TypeError:
     3948        except (TypeError, AttributeError):
    38153949            pass
    38163950        else:
     
    38794013            if tp is not object:
    38804014                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"
    38814045
    38824046
     
    39734137        self.assertEqual((C.__module__, C.__name__), (mod, 'D.E'))
    39744138
     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
    39754153    def test_subclass_right_op(self):
    39764154        # Testing correct dispatch of subclass overloading __r<op>__...
     
    40244202        self.assertEqual(C() // E(), "C.__floordiv__") # This one would fail
    40254203
     4204    @test_support.impl_detail("testing an internal kind of method object")
    40264205    def test_meth_class_get(self):
    40274206        # Testing __get__ method of METH_CLASS C methods...
     
    40824261        a = C()
    40834262        pa = Proxy(a)
    4084         self.assert_(isinstance(a, C))  # Baseline
    4085         self.assert_(isinstance(pa, C)) # Test
     4263        self.assertIsInstance(a, C)  # Baseline
     4264        self.assertIsInstance(pa, C) # Test
    40864265        # Test with a classic subclass
    40874266        class D(C):
     
    40894268        a = D()
    40904269        pa = Proxy(a)
    4091         self.assert_(isinstance(a, C))  # Baseline
    4092         self.assert_(isinstance(pa, C)) # Test
     4270        self.assertIsInstance(a, C)  # Baseline
     4271        self.assertIsInstance(pa, C) # Test
    40934272        # Test with a new-style class
    40944273        class C(object):
     
    40964275        a = C()
    40974276        pa = Proxy(a)
    4098         self.assert_(isinstance(a, C))  # Baseline
    4099         self.assert_(isinstance(pa, C)) # Test
     4277        self.assertIsInstance(a, C)  # Baseline
     4278        self.assertIsInstance(pa, C) # Test
    41004279        # Test with a new-style subclass
    41014280        class D(C):
     
    41034282        a = D()
    41044283        pa = Proxy(a)
    4105         self.assert_(isinstance(a, C))  # Baseline
    4106         self.assert_(isinstance(pa, C)) # Test
     4284        self.assertIsInstance(a, C)  # Baseline
     4285        self.assertIsInstance(pa, C) # Test
    41074286
    41084287    def test_proxy_super(self):
     
    41364315            pass
    41374316        else:
    4138             self.fail("Carlo Verre __setattr__ suceeded!")
     4317            self.fail("Carlo Verre __setattr__ succeeded!")
    41394318        try:
    41404319            object.__delattr__(str, "lower")
     
    41724351    def test_file_fault(self):
    41734352        # Testing sys.stdout is changed in getattr...
    4174         import sys
     4353        test_stdout = sys.stdout
    41754354        class StdoutGuard:
    41764355            def __getattr__(self, attr):
     
    41824361        except RuntimeError:
    41834362            pass
     4363        finally:
     4364            sys.stdout = test_stdout
    41844365
    41854366    def test_vicious_descriptor_nonsense(self):
     
    42094390        self.assertEqual(c.attr, 1)
    42104391        # this makes a crash more likely:
    4211         import gc; gc.collect()
     4392        test_support.gc_collect()
    42124393        self.assertEqual(hasattr(c, 'attr'), False)
    42134394
     
    42314412        self.assertEqual(l.__add__, l.__add__)
    42324413        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)
    42384425        self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
    42394426        try:
     
    42524439        # Testing NotImplemented...
    42534440        # all binary methods should be able to return a NotImplemented
    4254         import sys
    4255         import types
    42564441        import operator
    42574442
     
    43324517        self.assertEqual(c.value, 3)
    43334518
     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
    43344548    def test_getattr_hooks(self):
    43354549        # issue 4230
     
    43534567
    43544568        self.assertRaises(AttributeError, getattr, A(), "attr")
    4355         self.assertEquals(descr.counter, 1)
     4569        self.assertEqual(descr.counter, 1)
    43564570        self.assertRaises(AttributeError, getattr, B(), "attr")
    4357         self.assertEquals(descr.counter, 2)
     4571        self.assertEqual(descr.counter, 2)
    43584572        self.assertRaises(AttributeError, getattr, C(), "attr")
    4359         self.assertEquals(descr.counter, 4)
    4360 
    4361         import gc
     4573        self.assertEqual(descr.counter, 4)
     4574
    43624575        class EvilGetattribute(object):
    43634576            # This used to segfault
     
    43724585        self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
    43734586
     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)
    43744648
    43754649class DictProxyTests(unittest.TestCase):
     
    43804654        self.C = C
    43814655
     4656    def test_repr(self):
     4657        self.assertIn('dict_proxy({', repr(vars(self.C)))
     4658        self.assertIn("'meth':", repr(vars(self.C)))
     4659
    43824660    def test_iter_keys(self):
    43834661        # Testing dict-proxy iterkeys...
    43844662        keys = [ key for key in self.C.__dict__.iterkeys() ]
    43854663        keys.sort()
    4386         self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
     4664        self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
    43874665            '__weakref__', 'meth'])
    43884666
     
    44344712
    44354713def 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)
    44394725
    44404726if __name__ == "__main__":
Note: See TracChangeset for help on using the changeset viewer.