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_exceptions.py

    r2 r391  
    55import unittest
    66import pickle, cPickle
    7 import warnings
    8 
    9 from test.test_support import TESTFN, unlink, run_unittest, captured_output
    10 from test.test_pep352 import ignore_message_warning
     7
     8from test.test_support import (TESTFN, unlink, run_unittest, captured_output,
     9                               check_warnings, cpython_only)
     10from test.test_pep352 import ignore_deprecation_warnings
    1111
    1212# XXX This is not really enough, each *operation* should be tested!
     
    1818        # should act the same as reloading built-in sys.
    1919        try:
     20            from imp import reload
    2021            import exceptions
    2122            reload(exceptions)
     
    3233        except exc, err:
    3334            buf2 = str(err)
    34         self.assertEquals(buf1, buf2)
    35         self.assertEquals(exc.__name__, excname)
     35        self.assertEqual(buf1, buf2)
     36        self.assertEqual(exc.__name__, excname)
    3637
    3738    def testRaising(self):
     
    109110
    110111        self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
    111         try: x = 1/0
     112        try: x = 1 // 0
    112113        except ZeroDivisionError: pass
    113114
    114115        self.raise_catch(Exception, "Exception")
    115         try: x = 1/0
     116        try: x = 1 // 0
    116117        except Exception, e: pass
    117118
     
    147148        ckmsg("continue\n", "'continue' not properly in loop")
    148149
     150    @cpython_only
    149151    def testSettingException(self):
    150152        # test that setting an exception at the C level works even if the
     
    162164                exc, err, tb = sys.exc_info()
    163165                co = tb.tb_frame.f_code
    164                 self.assertEquals(co.co_name, "test_capi1")
    165                 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
     166                self.assertEqual(co.co_name, "test_capi1")
     167                self.assertTrue(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
    166168            else:
    167169                self.fail("Expected exception")
     
    174176                exc, err, tb = sys.exc_info()
    175177                co = tb.tb_frame.f_code
    176                 self.assertEquals(co.co_name, "__init__")
    177                 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
     178                self.assertEqual(co.co_name, "__init__")
     179                self.assertTrue(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
    178180                co2 = tb.tb_frame.f_back.f_code
    179                 self.assertEquals(co2.co_name, "test_capi2")
     181                self.assertEqual(co2.co_name, "test_capi2")
    180182            else:
    181183                self.fail("Expected exception")
     
    191193            pass
    192194        else:
    193             self.failUnlessEqual(str(WindowsError(1001)),
     195            self.assertEqual(str(WindowsError(1001)),
    194196                                 "1001")
    195             self.failUnlessEqual(str(WindowsError(1001, "message")),
     197            self.assertEqual(str(WindowsError(1001, "message")),
    196198                                 "[Error 1001] message")
    197             self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
    198             self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
    199 
     199            self.assertEqual(WindowsError(1001, "message").errno, 22)
     200            self.assertEqual(WindowsError(1001, "message").winerror, 1001)
     201
     202    @ignore_deprecation_warnings
    200203    def testAttributes(self):
    201204        # test that exception attributes are happy
     
    275278            pass
    276279
    277         with warnings.catch_warnings():
    278             ignore_message_warning()
    279             for exc, args, expected in exceptionList:
    280                 try:
    281                     raise exc(*args)
    282                 except BaseException, e:
    283                     if type(e) is not exc:
    284                         raise
    285                     # Verify module name
    286                     self.assertEquals(type(e).__module__, 'exceptions')
    287                     # Verify no ref leaks in Exc_str()
    288                     s = str(e)
    289                     for checkArgName in expected:
    290                         self.assertEquals(repr(getattr(e, checkArgName)),
    291                                           repr(expected[checkArgName]),
    292                                           'exception "%s", attribute "%s"' %
    293                                            (repr(e), checkArgName))
    294 
    295                     # test for pickling support
    296                     for p in pickle, cPickle:
    297                         for protocol in range(p.HIGHEST_PROTOCOL + 1):
    298                             new = p.loads(p.dumps(e, protocol))
    299                             for checkArgName in expected:
    300                                 got = repr(getattr(new, checkArgName))
    301                                 want = repr(expected[checkArgName])
    302                                 self.assertEquals(got, want,
    303                                                   'pickled "%r", attribute "%s"' %
    304                                                   (e, checkArgName))
     280        for exc, args, expected in exceptionList:
     281            try:
     282                raise exc(*args)
     283            except BaseException, e:
     284                if type(e) is not exc:
     285                    raise
     286                # Verify module name
     287                self.assertEqual(type(e).__module__, 'exceptions')
     288                # Verify no ref leaks in Exc_str()
     289                s = str(e)
     290                for checkArgName in expected:
     291                    self.assertEqual(repr(getattr(e, checkArgName)),
     292                                     repr(expected[checkArgName]),
     293                                     'exception "%s", attribute "%s"' %
     294                                      (repr(e), checkArgName))
     295
     296                # test for pickling support
     297                for p in pickle, cPickle:
     298                    for protocol in range(p.HIGHEST_PROTOCOL + 1):
     299                        new = p.loads(p.dumps(e, protocol))
     300                        for checkArgName in expected:
     301                            got = repr(getattr(new, checkArgName))
     302                            want = repr(expected[checkArgName])
     303                            self.assertEqual(got, want,
     304                                             'pickled "%r", attribute "%s"' %
     305                                             (e, checkArgName))
    305306
    306307
     
    309310        # BaseException.__init__ triggers a deprecation warning.
    310311        exc = BaseException("foo")
    311         with warnings.catch_warnings(record=True) as w:
    312             self.assertEquals(exc.message, "foo")
    313         self.assertEquals(len(w), 1)
    314         self.assertEquals(w[0].category, DeprecationWarning)
    315         self.assertEquals(
    316             str(w[0].message),
    317             "BaseException.message has been deprecated as of Python 2.6")
    318 
     312        with check_warnings(("BaseException.message has been deprecated "
     313                             "as of Python 2.6", DeprecationWarning)) as w:
     314            self.assertEqual(exc.message, "foo")
     315        self.assertEqual(len(w.warnings), 1)
    319316
    320317    def testRegularMessageAttribute(self):
     
    323320        exc = BaseException("foo")
    324321        exc.message = "bar"
    325         with warnings.catch_warnings(record=True) as w:
    326             self.assertEquals(exc.message, "bar")
    327         self.assertEquals(len(w), 0)
     322        with check_warnings(quiet=True) as w:
     323            self.assertEqual(exc.message, "bar")
     324        self.assertEqual(len(w.warnings), 0)
    328325        # Deleting the message is supported, too.
    329326        del exc.message
    330         self.assertRaises(AttributeError, getattr, exc, "message")
    331 
     327        with self.assertRaises(AttributeError):
     328            exc.message
     329
     330    @ignore_deprecation_warnings
    332331    def testPickleMessageAttribute(self):
    333332        # Pickling with message attribute must work, as well.
     
    337336        for p in pickle, cPickle:
    338337            ep = p.loads(p.dumps(e))
    339             with warnings.catch_warnings():
    340                 ignore_message_warning()
    341                 self.assertEqual(ep.message, "foo")
     338            self.assertEqual(ep.message, "foo")
    342339            fp = p.loads(p.dumps(f))
    343340            self.assertEqual(fp.message, "bar")
    344341
     342    @ignore_deprecation_warnings
    345343    def testSlicing(self):
    346344        # Test that you can slice an exception directly instead of requiring
     
    348346        args = (1, 2, 3)
    349347        exc = BaseException(*args)
    350         self.failUnlessEqual(exc[:], args)
     348        self.assertEqual(exc[:], args)
     349        self.assertEqual(exc.args[:], args)
    351350
    352351    def testKeywordArgs(self):
     
    361360
    362361        x = DerivedException(fancy_arg=42)
    363         self.assertEquals(x.fancy_arg, 42)
     362        self.assertEqual(x.fancy_arg, 42)
    364363
    365364    def testInfiniteRecursion(self):
     
    390389        # Make sure both instances and classes have a str and unicode
    391390        # representation.
    392         self.failUnless(str(Exception))
    393         self.failUnless(unicode(Exception))
    394         self.failUnless(str(Exception('a')))
    395         self.failUnless(unicode(Exception(u'a')))
    396         self.failUnless(unicode(Exception(u'\xe1')))
     391        self.assertTrue(str(Exception))
     392        self.assertTrue(unicode(Exception))
     393        self.assertTrue(str(Exception('a')))
     394        self.assertTrue(unicode(Exception(u'a')))
     395        self.assertTrue(unicode(Exception(u'\xe1')))
    397396
    398397    def testUnicodeChangeAttributes(self):
     
    463462                    return sys.exc_info()
    464463            e, v, tb = g()
    465             self.assert_(e is RuntimeError, e)
    466             self.assert_("maximum recursion depth exceeded" in str(v), v)
    467 
     464            self.assertTrue(e is RuntimeError, e)
     465            self.assertIn("maximum recursion depth exceeded", str(v))
     466
     467    def test_new_returns_invalid_instance(self):
     468        # See issue #11627.
     469        class MyException(Exception):
     470            def __new__(cls, *args):
     471                return object()
     472
     473        with self.assertRaises(TypeError):
     474            raise MyException
     475
     476    def test_assert_with_tuple_arg(self):
     477        try:
     478            assert False, (3,)
     479        except AssertionError as e:
     480            self.assertEqual(str(e), "(3,)")
     481
     482    def test_bad_exception_clearing(self):
     483        # See issue 16445: use of Py_XDECREF instead of Py_CLEAR in
     484        # BaseException_set_message gave a possible way to segfault the
     485        # interpreter.
     486        class Nasty(str):
     487            def __del__(message):
     488                del e.message
     489
     490        e = ValueError(Nasty("msg"))
     491        e.args = ()
     492        del e.message
    468493
    469494
     
    574599        self.assertEqual(unicode(e), u'f\xf6\xf6')
    575600
     601    @cpython_only
     602    def test_exception_with_doc(self):
     603        import _testcapi
     604        doc2 = "This is a test docstring."
     605        doc4 = "This is another test docstring."
     606
     607        self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
     608                          "error1")
     609
     610        # test basic usage of PyErr_NewException
     611        error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
     612        self.assertIs(type(error1), type)
     613        self.assertTrue(issubclass(error1, Exception))
     614        self.assertIsNone(error1.__doc__)
     615
     616        # test with given docstring
     617        error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
     618        self.assertEqual(error2.__doc__, doc2)
     619
     620        # test with explicit base (without docstring)
     621        error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
     622                                                   base=error2)
     623        self.assertTrue(issubclass(error3, error2))
     624
     625        # test with explicit base tuple
     626        class C(object):
     627            pass
     628        error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
     629                                                   (error3, C))
     630        self.assertTrue(issubclass(error4, error3))
     631        self.assertTrue(issubclass(error4, C))
     632        self.assertEqual(error4.__doc__, doc4)
     633
     634        # test with explicit dictionary
     635        error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
     636                                                   error4, {'a': 1})
     637        self.assertTrue(issubclass(error5, error4))
     638        self.assertEqual(error5.a, 1)
     639        self.assertEqual(error5.__doc__, "")
     640
    576641
    577642def test_main():
Note: See TracChangeset for help on using the changeset viewer.