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

    r2 r391  
    55import sys
    66import unittest
     7import subprocess
    78from test import test_support
     9from test.script_helper import assert_python_ok
    810
    911import warning_tests
     
    1113import warnings as original_warnings
    1214
    13 sys.modules['_warnings'] = 0
    14 del sys.modules['warnings']
    15 
    16 import warnings as py_warnings
    17 
    18 del sys.modules['_warnings']
    19 del sys.modules['warnings']
    20 
    21 import warnings as c_warnings
    22 
    23 sys.modules['warnings'] = original_warnings
    24 
     15py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])
     16c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])
    2517
    2618@contextmanager
     
    3830        pass
    3931    original_warnings = warning_tests.warnings
     32    original_filters = module.filters
    4033    try:
     34        module.filters = original_filters[:]
     35        module.simplefilter("once")
    4136        warning_tests.warnings = module
    4237        yield
    4338    finally:
    4439        warning_tests.warnings = original_warnings
     40        module.filters = original_filters
    4541
    4642
     
    8581            self.module.filterwarnings("ignore", category=UserWarning)
    8682            self.module.warn("FilterTests.test_ignore", UserWarning)
    87             self.assertEquals(len(w), 0)
     83            self.assertEqual(len(w), 0)
    8884
    8985    def test_always(self):
     
    9490            message = "FilterTests.test_always"
    9591            self.module.warn(message, UserWarning)
    96             self.assert_(message, w[-1].message)
     92            self.assertTrue(message, w[-1].message)
    9793            self.module.warn(message, UserWarning)
    98             self.assert_(w[-1].message, message)
     94            self.assertTrue(w[-1].message, message)
    9995
    10096    def test_default(self):
     
    107103                self.module.warn(message, UserWarning)
    108104                if x == 0:
    109                     self.assertEquals(w[-1].message, message)
     105                    self.assertEqual(w[-1].message, message)
    110106                    del w[:]
    111107                elif x == 1:
    112                     self.assertEquals(len(w), 0)
     108                    self.assertEqual(len(w), 0)
    113109                else:
    114110                    raise ValueError("loop variant unhandled")
     
    121117            message = UserWarning("FilterTests.test_module")
    122118            self.module.warn(message, UserWarning)
    123             self.assertEquals(w[-1].message, message)
     119            self.assertEqual(w[-1].message, message)
    124120            del w[:]
    125121            self.module.warn(message, UserWarning)
    126             self.assertEquals(len(w), 0)
     122            self.assertEqual(len(w), 0)
    127123
    128124    def test_once(self):
     
    134130            self.module.warn_explicit(message, UserWarning, "test_warnings.py",
    135131                                    42)
    136             self.assertEquals(w[-1].message, message)
     132            self.assertEqual(w[-1].message, message)
    137133            del w[:]
    138134            self.module.warn_explicit(message, UserWarning, "test_warnings.py",
    139135                                    13)
    140             self.assertEquals(len(w), 0)
     136            self.assertEqual(len(w), 0)
    141137            self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
    142138                                    42)
    143             self.assertEquals(len(w), 0)
     139            self.assertEqual(len(w), 0)
    144140
    145141    def test_inheritance(self):
     
    162158            except UserWarning:
    163159                self.fail("order handling for actions failed")
    164             self.assertEquals(len(w), 0)
     160            self.assertEqual(len(w), 0)
    165161
    166162    def test_filterwarnings(self):
     
    176172            self.module.warn(text)
    177173            self.assertEqual(str(w[-1].message), text)
    178             self.assert_(w[-1].category is UserWarning)
     174            self.assertTrue(w[-1].category is UserWarning)
    179175
    180176            self.module.filterwarnings("ignore", "", Warning, "", 0)
     
    189185            self.module.warn(text)
    190186            self.assertEqual(str(w[-1].message), text)
    191             self.assert_(w[-1].category is UserWarning)
     187            self.assertTrue(w[-1].category is UserWarning)
    192188
    193189class CFilterTests(BaseTest, FilterTests):
     
    205201        with original_warnings.catch_warnings(record=True,
    206202                module=self.module) as w:
     203            self.module.simplefilter("once")
    207204            for i in range(4):
    208205                text = 'multi %d' %i  # Different text on each call.
    209206                self.module.warn(text)
    210207                self.assertEqual(str(w[-1].message), text)
    211                 self.assert_(w[-1].category is UserWarning)
     208                self.assertTrue(w[-1].category is UserWarning)
    212209
    213210    def test_filename(self):
     
    324321
    325322    def test_warn_explicit_type_errors(self):
    326         # warn_explicit() shoud error out gracefully if it is given objects
     323        # warn_explicit() should error out gracefully if it is given objects
    327324        # of the wrong types.
    328325        # lineno is expected to be an integer.
     
    348345                        {"err" : "there is no %(err)s"})
    349346
    350         self.assertRaises(ValueError, self.module.warn, BadStrWarning())
     347        with self.assertRaises(ValueError):
     348            self.module.warn(BadStrWarning())
    351349
    352350
     
    354352    module = c_warnings
    355353
     354    # As an early adopter, we sanity check the
     355    # test_support.import_fresh_module utility function
     356    def test_accelerated(self):
     357        self.assertFalse(original_warnings is self.module)
     358        self.assertFalse(hasattr(self.module.warn, 'func_code'))
     359
    356360class PyWarnTests(BaseTest, WarnTests):
    357361    module = py_warnings
     362
     363    # As an early adopter, we sanity check the
     364    # test_support.import_fresh_module utility function
     365    def test_pure_python(self):
     366        self.assertFalse(original_warnings is self.module)
     367        self.assertTrue(hasattr(self.module.warn, 'func_code'))
    358368
    359369
     
    373383            self.assertRaises(UserWarning, self.module.warn, 'convert to error')
    374384
     385    def test_improper_option(self):
     386        # Same as above, but check that the message is printed out when
     387        # the interpreter is executed. This also checks that options are
     388        # actually parsed at all.
     389        rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
     390        self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
     391
     392    def test_warnings_bootstrap(self):
     393        # Check that the warnings module does get loaded when -W<some option>
     394        # is used (see issue #10372 for an example of silent bootstrap failure).
     395        rc, out, err = assert_python_ok("-Wi", "-c",
     396            "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
     397        # '-Wi' was observed
     398        self.assertFalse(out.strip())
     399        self.assertNotIn(b'RuntimeWarning', err)
     400
    375401class CWCmdLineTests(BaseTest, WCmdLineTests):
    376402    module = c_warnings
     
    408434                self.module.filterwarnings("once", category=UserWarning)
    409435                self.module.warn_explicit(message, UserWarning, "file", 42)
    410                 self.failUnlessEqual(w[-1].message, message)
     436                self.assertEqual(w[-1].message, message)
    411437                del w[:]
    412438                self.module.warn_explicit(message, UserWarning, "file", 42)
    413                 self.assertEquals(len(w), 0)
     439                self.assertEqual(len(w), 0)
    414440                # Test the resetting of onceregistry.
    415441                self.module.onceregistry = {}
    416442                __warningregistry__ = {}
    417443                self.module.warn('onceregistry test')
    418                 self.failUnlessEqual(w[-1].message.args, message.args)
     444                self.assertEqual(w[-1].message.args, message.args)
    419445                # Removal of onceregistry is okay.
    420446                del w[:]
     
    422448                __warningregistry__ = {}
    423449                self.module.warn_explicit(message, UserWarning, "file", 42)
    424                 self.assertEquals(len(w), 0)
     450                self.assertEqual(len(w), 0)
    425451        finally:
    426452            self.module.onceregistry = original_registry
     453
     454    def test_default_action(self):
     455        # Replacing or removing defaultaction should be okay.
     456        message = UserWarning("defaultaction test")
     457        original = self.module.defaultaction
     458        try:
     459            with original_warnings.catch_warnings(record=True,
     460                    module=self.module) as w:
     461                self.module.resetwarnings()
     462                registry = {}
     463                self.module.warn_explicit(message, UserWarning, "<test>", 42,
     464                                            registry=registry)
     465                self.assertEqual(w[-1].message, message)
     466                self.assertEqual(len(w), 1)
     467                self.assertEqual(len(registry), 1)
     468                del w[:]
     469                # Test removal.
     470                del self.module.defaultaction
     471                __warningregistry__ = {}
     472                registry = {}
     473                self.module.warn_explicit(message, UserWarning, "<test>", 43,
     474                                            registry=registry)
     475                self.assertEqual(w[-1].message, message)
     476                self.assertEqual(len(w), 1)
     477                self.assertEqual(len(registry), 1)
     478                del w[:]
     479                # Test setting.
     480                self.module.defaultaction = "ignore"
     481                __warningregistry__ = {}
     482                registry = {}
     483                self.module.warn_explicit(message, UserWarning, "<test>", 44,
     484                                            registry=registry)
     485                self.assertEqual(len(w), 0)
     486        finally:
     487            self.module.defaultaction = original
    427488
    428489    def test_showwarning_missing(self):
     
    435496                self.module.warn(text)
    436497                result = stream.getvalue()
    437         self.failUnless(text in result)
     498        self.assertIn(text, result)
    438499
    439500    def test_showwarning_not_callable(self):
    440         self.module.filterwarnings("always", category=UserWarning)
    441         old_showwarning = self.module.showwarning
    442         self.module.showwarning = 23
    443         try:
    444             self.assertRaises(TypeError, self.module.warn, "Warning!")
    445         finally:
    446             self.module.showwarning = old_showwarning
    447             self.module.resetwarnings()
     501        with original_warnings.catch_warnings(module=self.module):
     502            self.module.filterwarnings("always", category=UserWarning)
     503            old_showwarning = self.module.showwarning
     504            self.module.showwarning = 23
     505            try:
     506                self.assertRaises(TypeError, self.module.warn, "Warning!")
     507            finally:
     508                self.module.showwarning = old_showwarning
    448509
    449510    def test_show_warning_output(self):
     
    456517                warning_tests.inner(text)
    457518                result = stream.getvalue()
    458         self.failUnlessEqual(result.count('\n'), 2,
     519        self.assertEqual(result.count('\n'), 2,
    459520                             "Too many newlines in %r" % result)
    460521        first_line, second_line = result.split('\n', 1)
     
    463524        path, line, warning_class, message = first_line_parts
    464525        line = int(line)
    465         self.failUnlessEqual(expected_file, path)
    466         self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
    467         self.failUnlessEqual(message, ' ' + text)
     526        self.assertEqual(expected_file, path)
     527        self.assertEqual(warning_class, ' ' + UserWarning.__name__)
     528        self.assertEqual(message, ' ' + text)
    468529        expected_line = '  ' + linecache.getline(path, line).strip() + '\n'
    469530        assert expected_line
    470         self.failUnlessEqual(second_line, expected_line)
     531        self.assertEqual(second_line, expected_line)
     532
     533    def test_filename_none(self):
     534        # issue #12467: race condition if a warning is emitted at shutdown
     535        globals_dict = globals()
     536        oldfile = globals_dict['__file__']
     537        try:
     538            with original_warnings.catch_warnings(module=self.module) as w:
     539                self.module.filterwarnings("always", category=UserWarning)
     540                globals_dict['__file__'] = None
     541                self.module.warn('test', UserWarning)
     542        finally:
     543            globals_dict['__file__'] = oldfile
    471544
    472545
     
    485558        expect = format % (file_name, line_num, category.__name__, message,
    486559                            file_line)
    487         self.failUnlessEqual(expect, self.module.formatwarning(message,
     560        self.assertEqual(expect, self.module.formatwarning(message,
    488561                                                category, file_name, line_num))
    489562        # Test the 'line' argument.
     
    491564        expect = format % (file_name, line_num, category.__name__, message,
    492565                            file_line)
    493         self.failUnlessEqual(expect, self.module.formatwarning(message,
     566        self.assertEqual(expect, self.module.formatwarning(message,
    494567                                    category, file_name, line_num, file_line))
    495568
     
    505578        self.module.showwarning(message, category, file_name, line_num,
    506579                                file_object)
    507         self.failUnlessEqual(file_object.getvalue(), expect)
     580        self.assertEqual(file_object.getvalue(), expect)
    508581        # Test 'line' argument.
    509582        expected_file_line += "for the win!"
     
    513586        self.module.showwarning(message, category, file_name, line_num,
    514587                                file_object, expected_file_line)
    515         self.failUnlessEqual(expect, file_object.getvalue())
     588        self.assertEqual(expect, file_object.getvalue())
    516589
    517590class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
     
    533606        with wmod.catch_warnings(module=wmod, record=True):
    534607            wmod.filters = wmod.showwarning = object()
    535         self.assert_(wmod.filters is orig_filters)
    536         self.assert_(wmod.showwarning is orig_showwarning)
     608        self.assertTrue(wmod.filters is orig_filters)
     609        self.assertTrue(wmod.showwarning is orig_showwarning)
    537610        # Same test, but with recording disabled
    538611        with wmod.catch_warnings(module=wmod, record=False):
    539612            wmod.filters = wmod.showwarning = object()
    540         self.assert_(wmod.filters is orig_filters)
    541         self.assert_(wmod.showwarning is orig_showwarning)
     613        self.assertTrue(wmod.filters is orig_filters)
     614        self.assertTrue(wmod.showwarning is orig_showwarning)
    542615
    543616    def test_catch_warnings_recording(self):
     
    546619        with wmod.catch_warnings(module=wmod, record=True) as w:
    547620            self.assertEqual(w, [])
    548             self.assert_(type(w) is list)
     621            self.assertTrue(type(w) is list)
    549622            wmod.simplefilter("always")
    550623            wmod.warn("foo")
     
    559632        orig_showwarning = wmod.showwarning
    560633        with wmod.catch_warnings(module=wmod, record=False) as w:
    561             self.assert_(w is None)
    562             self.assert_(wmod.showwarning is orig_showwarning)
     634            self.assertTrue(w is None)
     635            self.assertTrue(wmod.showwarning is orig_showwarning)
    563636
    564637    def test_catch_warnings_reentry_guard(self):
     
    581654        # Ensure default behaviour is not to record warnings
    582655        with wmod.catch_warnings(module=wmod) as w:
    583             self.assert_(w is None)
    584             self.assert_(wmod.showwarning is orig_showwarning)
    585             self.assert_(wmod.filters is not orig_filters)
    586         self.assert_(wmod.filters is orig_filters)
     656            self.assertTrue(w is None)
     657            self.assertTrue(wmod.showwarning is orig_showwarning)
     658            self.assertTrue(wmod.filters is not orig_filters)
     659        self.assertTrue(wmod.filters is orig_filters)
    587660        if wmod is sys.modules['warnings']:
    588661            # Ensure the default module is this one
    589662            with wmod.catch_warnings() as w:
    590                 self.assert_(w is None)
    591                 self.assert_(wmod.showwarning is orig_showwarning)
    592                 self.assert_(wmod.filters is not orig_filters)
    593             self.assert_(wmod.filters is orig_filters)
     663                self.assertTrue(w is None)
     664                self.assertTrue(wmod.showwarning is orig_showwarning)
     665                self.assertTrue(wmod.filters is not orig_filters)
     666            self.assertTrue(wmod.filters is orig_filters)
    594667
    595668    def test_check_warnings(self):
    596669        # Explicit tests for the test_support convenience wrapper
    597670        wmod = self.module
    598         if wmod is sys.modules['warnings']:
    599             with test_support.check_warnings() as w:
    600                 self.assertEqual(w.warnings, [])
    601                 wmod.simplefilter("always")
     671        if wmod is not sys.modules['warnings']:
     672            return
     673        with test_support.check_warnings(quiet=False) as w:
     674            self.assertEqual(w.warnings, [])
     675            wmod.simplefilter("always")
     676            wmod.warn("foo")
     677            self.assertEqual(str(w.message), "foo")
     678            wmod.warn("bar")
     679            self.assertEqual(str(w.message), "bar")
     680            self.assertEqual(str(w.warnings[0].message), "foo")
     681            self.assertEqual(str(w.warnings[1].message), "bar")
     682            w.reset()
     683            self.assertEqual(w.warnings, [])
     684
     685        with test_support.check_warnings():
     686            # defaults to quiet=True without argument
     687            pass
     688        with test_support.check_warnings(('foo', UserWarning)):
     689            wmod.warn("foo")
     690
     691        with self.assertRaises(AssertionError):
     692            with test_support.check_warnings(('', RuntimeWarning)):
     693                # defaults to quiet=False with argument
     694                pass
     695        with self.assertRaises(AssertionError):
     696            with test_support.check_warnings(('foo', RuntimeWarning)):
    602697                wmod.warn("foo")
    603                 self.assertEqual(str(w.message), "foo")
    604                 wmod.warn("bar")
    605                 self.assertEqual(str(w.message), "bar")
    606                 self.assertEqual(str(w.warnings[0].message), "foo")
    607                 self.assertEqual(str(w.warnings[1].message), "bar")
    608                 w.reset()
    609                 self.assertEqual(w.warnings, [])
    610 
    611698
    612699
     
    618705
    619706
    620 class ShowwarningDeprecationTests(BaseTest):
    621 
    622     """Test the deprecation of the old warnings.showwarning() API works."""
    623 
    624     @staticmethod
    625     def bad_showwarning(message, category, filename, lineno, file=None):
    626         pass
    627 
    628     @staticmethod
    629     def ok_showwarning(*args):
    630         pass
    631 
    632     def test_deprecation(self):
    633         # message, category, filename, lineno[, file[, line]]
    634         args = ("message", UserWarning, "file name", 42)
    635         with original_warnings.catch_warnings(module=self.module):
    636             self.module.filterwarnings("error", category=DeprecationWarning)
    637             self.module.showwarning = self.bad_showwarning
    638             self.assertRaises(DeprecationWarning, self.module.warn_explicit,
    639                                 *args)
    640             self.module.showwarning = self.ok_showwarning
    641             try:
    642                 self.module.warn_explicit(*args)
    643             except DeprecationWarning as exc:
    644                 self.fail('showwarning(*args) should not trigger a '
    645                             'DeprecationWarning')
    646 
    647 class CShowwarningDeprecationTests(ShowwarningDeprecationTests):
     707class EnvironmentVariableTests(BaseTest):
     708
     709    def test_single_warning(self):
     710        newenv = os.environ.copy()
     711        newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
     712        p = subprocess.Popen([sys.executable,
     713                "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
     714                stdout=subprocess.PIPE, env=newenv)
     715        self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
     716        self.assertEqual(p.wait(), 0)
     717
     718    def test_comma_separated_warnings(self):
     719        newenv = os.environ.copy()
     720        newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
     721                                    "ignore::UnicodeWarning")
     722        p = subprocess.Popen([sys.executable,
     723                "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
     724                stdout=subprocess.PIPE, env=newenv)
     725        self.assertEqual(p.communicate()[0],
     726                "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
     727        self.assertEqual(p.wait(), 0)
     728
     729    def test_envvar_and_command_line(self):
     730        newenv = os.environ.copy()
     731        newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
     732        p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
     733                "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
     734                stdout=subprocess.PIPE, env=newenv)
     735        self.assertEqual(p.communicate()[0],
     736                "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
     737        self.assertEqual(p.wait(), 0)
     738
     739class CEnvironmentVariableTests(EnvironmentVariableTests):
    648740    module = c_warnings
    649741
    650 
    651 class PyShowwarningDeprecationTests(ShowwarningDeprecationTests):
     742class PyEnvironmentVariableTests(EnvironmentVariableTests):
    652743    module = py_warnings
    653744
     
    662753                                CWarningsDisplayTests, PyWarningsDisplayTests,
    663754                                CCatchWarningTests, PyCatchWarningTests,
    664                                 CShowwarningDeprecationTests,
    665                                     PyShowwarningDeprecationTests,
     755                                CEnvironmentVariableTests,
     756                                PyEnvironmentVariableTests
    666757                             )
    667758
Note: See TracChangeset for help on using the changeset viewer.