home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 July / maximum-cd-2011-07.iso / DiscContents / LibO_3.3.2_Win_x86_install_multi.exe / libreoffice1.cab / test_warnings.py < prev    next >
Encoding:
Python Source  |  2011-03-15  |  26.5 KB  |  659 lines

  1. from contextlib import contextmanager
  2. import linecache
  3. import os
  4. import StringIO
  5. import sys
  6. import unittest
  7. from test import test_support
  8.  
  9. import warning_tests
  10.  
  11. import warnings as original_warnings
  12.  
  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.  
  25.  
  26. @contextmanager
  27. def warnings_state(module):
  28.     """Use a specific warnings implementation in warning_tests."""
  29.     global __warningregistry__
  30.     for to_clear in (sys, warning_tests):
  31.         try:
  32.             to_clear.__warningregistry__.clear()
  33.         except AttributeError:
  34.             pass
  35.     try:
  36.         __warningregistry__.clear()
  37.     except NameError:
  38.         pass
  39.     original_warnings = warning_tests.warnings
  40.     try:
  41.         warning_tests.warnings = module
  42.         yield
  43.     finally:
  44.         warning_tests.warnings = original_warnings
  45.  
  46.  
  47. class BaseTest(unittest.TestCase):
  48.  
  49.     """Basic bookkeeping required for testing."""
  50.  
  51.     def setUp(self):
  52.         # The __warningregistry__ needs to be in a pristine state for tests
  53.         # to work properly.
  54.         if '__warningregistry__' in globals():
  55.             del globals()['__warningregistry__']
  56.         if hasattr(warning_tests, '__warningregistry__'):
  57.             del warning_tests.__warningregistry__
  58.         if hasattr(sys, '__warningregistry__'):
  59.             del sys.__warningregistry__
  60.         # The 'warnings' module must be explicitly set so that the proper
  61.         # interaction between _warnings and 'warnings' can be controlled.
  62.         sys.modules['warnings'] = self.module
  63.         super(BaseTest, self).setUp()
  64.  
  65.     def tearDown(self):
  66.         sys.modules['warnings'] = original_warnings
  67.         super(BaseTest, self).tearDown()
  68.  
  69.  
  70. class FilterTests(object):
  71.  
  72.     """Testing the filtering functionality."""
  73.  
  74.     def test_error(self):
  75.         with original_warnings.catch_warnings(module=self.module) as w:
  76.             self.module.resetwarnings()
  77.             self.module.filterwarnings("error", category=UserWarning)
  78.             self.assertRaises(UserWarning, self.module.warn,
  79.                                 "FilterTests.test_error")
  80.  
  81.     def test_ignore(self):
  82.         with original_warnings.catch_warnings(record=True,
  83.                 module=self.module) as w:
  84.             self.module.resetwarnings()
  85.             self.module.filterwarnings("ignore", category=UserWarning)
  86.             self.module.warn("FilterTests.test_ignore", UserWarning)
  87.             self.assertEquals(len(w), 0)
  88.  
  89.     def test_always(self):
  90.         with original_warnings.catch_warnings(record=True,
  91.                 module=self.module) as w:
  92.             self.module.resetwarnings()
  93.             self.module.filterwarnings("always", category=UserWarning)
  94.             message = "FilterTests.test_always"
  95.             self.module.warn(message, UserWarning)
  96.             self.assert_(message, w[-1].message)
  97.             self.module.warn(message, UserWarning)
  98.             self.assert_(w[-1].message, message)
  99.  
  100.     def test_default(self):
  101.         with original_warnings.catch_warnings(record=True,
  102.                 module=self.module) as w:
  103.             self.module.resetwarnings()
  104.             self.module.filterwarnings("default", category=UserWarning)
  105.             message = UserWarning("FilterTests.test_default")
  106.             for x in xrange(2):
  107.                 self.module.warn(message, UserWarning)
  108.                 if x == 0:
  109.                     self.assertEquals(w[-1].message, message)
  110.                     del w[:]
  111.                 elif x == 1:
  112.                     self.assertEquals(len(w), 0)
  113.                 else:
  114.                     raise ValueError("loop variant unhandled")
  115.  
  116.     def test_module(self):
  117.         with original_warnings.catch_warnings(record=True,
  118.                 module=self.module) as w:
  119.             self.module.resetwarnings()
  120.             self.module.filterwarnings("module", category=UserWarning)
  121.             message = UserWarning("FilterTests.test_module")
  122.             self.module.warn(message, UserWarning)
  123.             self.assertEquals(w[-1].message, message)
  124.             del w[:]
  125.             self.module.warn(message, UserWarning)
  126.             self.assertEquals(len(w), 0)
  127.  
  128.     def test_once(self):
  129.         with original_warnings.catch_warnings(record=True,
  130.                 module=self.module) as w:
  131.             self.module.resetwarnings()
  132.             self.module.filterwarnings("once", category=UserWarning)
  133.             message = UserWarning("FilterTests.test_once")
  134.             self.module.warn_explicit(message, UserWarning, "test_warnings.py",
  135.                                     42)
  136.             self.assertEquals(w[-1].message, message)
  137.             del w[:]
  138.             self.module.warn_explicit(message, UserWarning, "test_warnings.py",
  139.                                     13)
  140.             self.assertEquals(len(w), 0)
  141.             self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
  142.                                     42)
  143.             self.assertEquals(len(w), 0)
  144.  
  145.     def test_inheritance(self):
  146.         with original_warnings.catch_warnings(module=self.module) as w:
  147.             self.module.resetwarnings()
  148.             self.module.filterwarnings("error", category=Warning)
  149.             self.assertRaises(UserWarning, self.module.warn,
  150.                                 "FilterTests.test_inheritance", UserWarning)
  151.  
  152.     def test_ordering(self):
  153.         with original_warnings.catch_warnings(record=True,
  154.                 module=self.module) as w:
  155.             self.module.resetwarnings()
  156.             self.module.filterwarnings("ignore", category=UserWarning)
  157.             self.module.filterwarnings("error", category=UserWarning,
  158.                                         append=True)
  159.             del w[:]
  160.             try:
  161.                 self.module.warn("FilterTests.test_ordering", UserWarning)
  162.             except UserWarning:
  163.                 self.fail("order handling for actions failed")
  164.             self.assertEquals(len(w), 0)
  165.  
  166.     def test_filterwarnings(self):
  167.         # Test filterwarnings().
  168.         # Implicitly also tests resetwarnings().
  169.         with original_warnings.catch_warnings(record=True,
  170.                 module=self.module) as w:
  171.             self.module.filterwarnings("error", "", Warning, "", 0)
  172.             self.assertRaises(UserWarning, self.module.warn, 'convert to error')
  173.  
  174.             self.module.resetwarnings()
  175.             text = 'handle normally'
  176.             self.module.warn(text)
  177.             self.assertEqual(str(w[-1].message), text)
  178.             self.assert_(w[-1].category is UserWarning)
  179.  
  180.             self.module.filterwarnings("ignore", "", Warning, "", 0)
  181.             text = 'filtered out'
  182.             self.module.warn(text)
  183.             self.assertNotEqual(str(w[-1].message), text)
  184.  
  185.             self.module.resetwarnings()
  186.             self.module.filterwarnings("error", "hex*", Warning, "", 0)
  187.             self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
  188.             text = 'nonmatching text'
  189.             self.module.warn(text)
  190.             self.assertEqual(str(w[-1].message), text)
  191.             self.assert_(w[-1].category is UserWarning)
  192.  
  193. class CFilterTests(BaseTest, FilterTests):
  194.     module = c_warnings
  195.  
  196. class PyFilterTests(BaseTest, FilterTests):
  197.     module = py_warnings
  198.  
  199.  
  200. class WarnTests(unittest.TestCase):
  201.  
  202.     """Test warnings.warn() and warnings.warn_explicit()."""
  203.  
  204.     def test_message(self):
  205.         with original_warnings.catch_warnings(record=True,
  206.                 module=self.module) as w:
  207.             for i in range(4):
  208.                 text = 'multi %d' %i  # Different text on each call.
  209.                 self.module.warn(text)
  210.                 self.assertEqual(str(w[-1].message), text)
  211.                 self.assert_(w[-1].category is UserWarning)
  212.  
  213.     def test_filename(self):
  214.         with warnings_state(self.module):
  215.             with original_warnings.catch_warnings(record=True,
  216.                     module=self.module) as w:
  217.                 warning_tests.inner("spam1")
  218.                 self.assertEqual(os.path.basename(w[-1].filename),
  219.                                     "warning_tests.py")
  220.                 warning_tests.outer("spam2")
  221.                 self.assertEqual(os.path.basename(w[-1].filename),
  222.                                     "warning_tests.py")
  223.  
  224.     def test_stacklevel(self):
  225.         # Test stacklevel argument
  226.         # make sure all messages are different, so the warning won't be skipped
  227.         with warnings_state(self.module):
  228.             with original_warnings.catch_warnings(record=True,
  229.                     module=self.module) as w:
  230.                 warning_tests.inner("spam3", stacklevel=1)
  231.                 self.assertEqual(os.path.basename(w[-1].filename),
  232.                                     "warning_tests.py")
  233.                 warning_tests.outer("spam4", stacklevel=1)
  234.                 self.assertEqual(os.path.basename(w[-1].filename),
  235.                                     "warning_tests.py")
  236.  
  237.                 warning_tests.inner("spam5", stacklevel=2)
  238.                 self.assertEqual(os.path.basename(w[-1].filename),
  239.                                     "test_warnings.py")
  240.                 warning_tests.outer("spam6", stacklevel=2)
  241.                 self.assertEqual(os.path.basename(w[-1].filename),
  242.                                     "warning_tests.py")
  243.                 warning_tests.outer("spam6.5", stacklevel=3)
  244.                 self.assertEqual(os.path.basename(w[-1].filename),
  245.                                     "test_warnings.py")
  246.  
  247.                 warning_tests.inner("spam7", stacklevel=9999)
  248.                 self.assertEqual(os.path.basename(w[-1].filename),
  249.                                     "sys")
  250.  
  251.     def test_missing_filename_not_main(self):
  252.         # If __file__ is not specified and __main__ is not the module name,
  253.         # then __file__ should be set to the module name.
  254.         filename = warning_tests.__file__
  255.         try:
  256.             del warning_tests.__file__
  257.             with warnings_state(self.module):
  258.                 with original_warnings.catch_warnings(record=True,
  259.                         module=self.module) as w:
  260.                     warning_tests.inner("spam8", stacklevel=1)
  261.                     self.assertEqual(w[-1].filename, warning_tests.__name__)
  262.         finally:
  263.             warning_tests.__file__ = filename
  264.  
  265.     def test_missing_filename_main_with_argv(self):
  266.         # If __file__ is not specified and the caller is __main__ and sys.argv
  267.         # exists, then use sys.argv[0] as the file.
  268.         if not hasattr(sys, 'argv'):
  269.             return
  270.         filename = warning_tests.__file__
  271.         module_name = warning_tests.__name__
  272.         try:
  273.             del warning_tests.__file__
  274.             warning_tests.__name__ = '__main__'
  275.             with warnings_state(self.module):
  276.                 with original_warnings.catch_warnings(record=True,
  277.                         module=self.module) as w:
  278.                     warning_tests.inner('spam9', stacklevel=1)
  279.                     self.assertEqual(w[-1].filename, sys.argv[0])
  280.         finally:
  281.             warning_tests.__file__ = filename
  282.             warning_tests.__name__ = module_name
  283.  
  284.     def test_missing_filename_main_without_argv(self):
  285.         # If __file__ is not specified, the caller is __main__, and sys.argv
  286.         # is not set, then '__main__' is the file name.
  287.         filename = warning_tests.__file__
  288.         module_name = warning_tests.__name__
  289.         argv = sys.argv
  290.         try:
  291.             del warning_tests.__file__
  292.             warning_tests.__name__ = '__main__'
  293.             del sys.argv
  294.             with warnings_state(self.module):
  295.                 with original_warnings.catch_warnings(record=True,
  296.                         module=self.module) as w:
  297.                     warning_tests.inner('spam10', stacklevel=1)
  298.                     self.assertEqual(w[-1].filename, '__main__')
  299.         finally:
  300.             warning_tests.__file__ = filename
  301.             warning_tests.__name__ = module_name
  302.             sys.argv = argv
  303.  
  304.     def test_missing_filename_main_with_argv_empty_string(self):
  305.         # If __file__ is not specified, the caller is __main__, and sys.argv[0]
  306.         # is the empty string, then '__main__ is the file name.
  307.         # Tests issue 2743.
  308.         file_name = warning_tests.__file__
  309.         module_name = warning_tests.__name__
  310.         argv = sys.argv
  311.         try:
  312.             del warning_tests.__file__
  313.             warning_tests.__name__ = '__main__'
  314.             sys.argv = ['']
  315.             with warnings_state(self.module):
  316.                 with original_warnings.catch_warnings(record=True,
  317.                         module=self.module) as w:
  318.                     warning_tests.inner('spam11', stacklevel=1)
  319.                     self.assertEqual(w[-1].filename, '__main__')
  320.         finally:
  321.             warning_tests.__file__ = file_name
  322.             warning_tests.__name__ = module_name
  323.             sys.argv = argv
  324.  
  325.     def test_warn_explicit_type_errors(self):
  326.         # warn_explicit() shoud error out gracefully if it is given objects
  327.         # of the wrong types.
  328.         # lineno is expected to be an integer.
  329.         self.assertRaises(TypeError, self.module.warn_explicit,
  330.                             None, UserWarning, None, None)
  331.         # Either 'message' needs to be an instance of Warning or 'category'
  332.         # needs to be a subclass.
  333.         self.assertRaises(TypeError, self.module.warn_explicit,
  334.                             None, None, None, 1)
  335.         # 'registry' must be a dict or None.
  336.         self.assertRaises((TypeError, AttributeError),
  337.                             self.module.warn_explicit,
  338.                             None, Warning, None, 1, registry=42)
  339.  
  340.  
  341. class CWarnTests(BaseTest, WarnTests):
  342.     module = c_warnings
  343.  
  344. class PyWarnTests(BaseTest, WarnTests):
  345.     module = py_warnings
  346.  
  347.  
  348. class WCmdLineTests(unittest.TestCase):
  349.  
  350.     def test_improper_input(self):
  351.         # Uses the private _setoption() function to test the parsing
  352.         # of command-line warning arguments
  353.         with original_warnings.catch_warnings(module=self.module):
  354.             self.assertRaises(self.module._OptionError,
  355.                               self.module._setoption, '1:2:3:4:5:6')
  356.             self.assertRaises(self.module._OptionError,
  357.                               self.module._setoption, 'bogus::Warning')
  358.             self.assertRaises(self.module._OptionError,
  359.                               self.module._setoption, 'ignore:2::4:-5')
  360.             self.module._setoption('error::Warning::0')
  361.             self.assertRaises(UserWarning, self.module.warn, 'convert to error')
  362.  
  363. class CWCmdLineTests(BaseTest, WCmdLineTests):
  364.     module = c_warnings
  365.  
  366. class PyWCmdLineTests(BaseTest, WCmdLineTests):
  367.     module = py_warnings
  368.  
  369.  
  370. class _WarningsTests(BaseTest):
  371.  
  372.     """Tests specific to the _warnings module."""
  373.  
  374.     module = c_warnings
  375.  
  376.     def test_filter(self):
  377.         # Everything should function even if 'filters' is not in warnings.
  378.         with original_warnings.catch_warnings(module=self.module) as w:
  379.             self.module.filterwarnings("error", "", Warning, "", 0)
  380.             self.assertRaises(UserWarning, self.module.warn,
  381.                                 'convert to error')
  382.             del self.module.filters
  383.             self.assertRaises(UserWarning, self.module.warn,
  384.                                 'convert to error')
  385.  
  386.     def test_onceregistry(self):
  387.         # Replacing or removing the onceregistry should be okay.
  388.         global __warningregistry__
  389.         message = UserWarning('onceregistry test')
  390.         try:
  391.             original_registry = self.module.onceregistry
  392.             __warningregistry__ = {}
  393.             with original_warnings.catch_warnings(record=True,
  394.                     module=self.module) as w:
  395.                 self.module.resetwarnings()
  396.                 self.module.filterwarnings("once", category=UserWarning)
  397.                 self.module.warn_explicit(message, UserWarning, "file", 42)
  398.                 self.failUnlessEqual(w[-1].message, message)
  399.                 del w[:]
  400.                 self.module.warn_explicit(message, UserWarning, "file", 42)
  401.                 self.assertEquals(len(w), 0)
  402.                 # Test the resetting of onceregistry.
  403.                 self.module.onceregistry = {}
  404.                 __warningregistry__ = {}
  405.                 self.module.warn('onceregistry test')
  406.                 self.failUnlessEqual(w[-1].message.args, message.args)
  407.                 # Removal of onceregistry is okay.
  408.                 del w[:]
  409.                 del self.module.onceregistry
  410.                 __warningregistry__ = {}
  411.                 self.module.warn_explicit(message, UserWarning, "file", 42)
  412.                 self.assertEquals(len(w), 0)
  413.         finally:
  414.             self.module.onceregistry = original_registry
  415.  
  416.     def test_showwarning_missing(self):
  417.         # Test that showwarning() missing is okay.
  418.         text = 'del showwarning test'
  419.         with original_warnings.catch_warnings(module=self.module):
  420.             self.module.filterwarnings("always", category=UserWarning)
  421.             del self.module.showwarning
  422.             with test_support.captured_output('stderr') as stream:
  423.                 self.module.warn(text)
  424.                 result = stream.getvalue()
  425.         self.failUnless(text in result)
  426.  
  427.     def test_showwarning_not_callable(self):
  428.         self.module.filterwarnings("always", category=UserWarning)
  429.         old_showwarning = self.module.showwarning
  430.         self.module.showwarning = 23
  431.         try:
  432.             self.assertRaises(TypeError, self.module.warn, "Warning!")
  433.         finally:
  434.             self.module.showwarning = old_showwarning
  435.             self.module.resetwarnings()
  436.  
  437.     def test_show_warning_output(self):
  438.         # With showarning() missing, make sure that output is okay.
  439.         text = 'test show_warning'
  440.         with original_warnings.catch_warnings(module=self.module):
  441.             self.module.filterwarnings("always", category=UserWarning)
  442.             del self.module.showwarning
  443.             with test_support.captured_output('stderr') as stream:
  444.                 warning_tests.inner(text)
  445.                 result = stream.getvalue()
  446.         self.failUnlessEqual(result.count('\n'), 2,
  447.                              "Too many newlines in %r" % result)
  448.         first_line, second_line = result.split('\n', 1)
  449.         expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
  450.         first_line_parts = first_line.rsplit(':', 3)
  451.         path, line, warning_class, message = first_line_parts
  452.         line = int(line)
  453.         self.failUnlessEqual(expected_file, path)
  454.         self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
  455.         self.failUnlessEqual(message, ' ' + text)
  456.         expected_line = '  ' + linecache.getline(path, line).strip() + '\n'
  457.         assert expected_line
  458.         self.failUnlessEqual(second_line, expected_line)
  459.  
  460.  
  461. class WarningsDisplayTests(unittest.TestCase):
  462.  
  463.     """Test the displaying of warnings and the ability to overload functions
  464.     related to displaying warnings."""
  465.  
  466.     def test_formatwarning(self):
  467.         message = "msg"
  468.         category = Warning
  469.         file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
  470.         line_num = 3
  471.         file_line = linecache.getline(file_name, line_num).strip()
  472.         format = "%s:%s: %s: %s\n  %s\n"
  473.         expect = format % (file_name, line_num, category.__name__, message,
  474.                             file_line)
  475.         self.failUnlessEqual(expect, self.module.formatwarning(message,
  476.                                                 category, file_name, line_num))
  477.         # Test the 'line' argument.
  478.         file_line += " for the win!"
  479.         expect = format % (file_name, line_num, category.__name__, message,
  480.                             file_line)
  481.         self.failUnlessEqual(expect, self.module.formatwarning(message,
  482.                                     category, file_name, line_num, file_line))
  483.  
  484.     def test_showwarning(self):
  485.         file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
  486.         line_num = 3
  487.         expected_file_line = linecache.getline(file_name, line_num).strip()
  488.         message = 'msg'
  489.         category = Warning
  490.         file_object = StringIO.StringIO()
  491.         expect = self.module.formatwarning(message, category, file_name,
  492.                                             line_num)
  493.         self.module.showwarning(message, category, file_name, line_num,
  494.                                 file_object)
  495.         self.failUnlessEqual(file_object.getvalue(), expect)
  496.         # Test 'line' argument.
  497.         expected_file_line += "for the win!"
  498.         expect = self.module.formatwarning(message, category, file_name,
  499.                                             line_num, expected_file_line)
  500.         file_object = StringIO.StringIO()
  501.         self.module.showwarning(message, category, file_name, line_num,
  502.                                 file_object, expected_file_line)
  503.         self.failUnlessEqual(expect, file_object.getvalue())
  504.  
  505. class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
  506.     module = c_warnings
  507.  
  508. class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
  509.     module = py_warnings
  510.  
  511.  
  512. class CatchWarningTests(BaseTest):
  513.  
  514.     """Test catch_warnings()."""
  515.  
  516.     def test_catch_warnings_restore(self):
  517.         wmod = self.module
  518.         orig_filters = wmod.filters
  519.         orig_showwarning = wmod.showwarning
  520.         # Ensure both showwarning and filters are restored when recording
  521.         with wmod.catch_warnings(module=wmod, record=True):
  522.             wmod.filters = wmod.showwarning = object()
  523.         self.assert_(wmod.filters is orig_filters)
  524.         self.assert_(wmod.showwarning is orig_showwarning)
  525.         # Same test, but with recording disabled
  526.         with wmod.catch_warnings(module=wmod, record=False):
  527.             wmod.filters = wmod.showwarning = object()
  528.         self.assert_(wmod.filters is orig_filters)
  529.         self.assert_(wmod.showwarning is orig_showwarning)
  530.  
  531.     def test_catch_warnings_recording(self):
  532.         wmod = self.module
  533.         # Ensure warnings are recorded when requested
  534.         with wmod.catch_warnings(module=wmod, record=True) as w:
  535.             self.assertEqual(w, [])
  536.             self.assert_(type(w) is list)
  537.             wmod.simplefilter("always")
  538.             wmod.warn("foo")
  539.             self.assertEqual(str(w[-1].message), "foo")
  540.             wmod.warn("bar")
  541.             self.assertEqual(str(w[-1].message), "bar")
  542.             self.assertEqual(str(w[0].message), "foo")
  543.             self.assertEqual(str(w[1].message), "bar")
  544.             del w[:]
  545.             self.assertEqual(w, [])
  546.         # Ensure warnings are not recorded when not requested
  547.         orig_showwarning = wmod.showwarning
  548.         with wmod.catch_warnings(module=wmod, record=False) as w:
  549.             self.assert_(w is None)
  550.             self.assert_(wmod.showwarning is orig_showwarning)
  551.  
  552.     def test_catch_warnings_reentry_guard(self):
  553.         wmod = self.module
  554.         # Ensure catch_warnings is protected against incorrect usage
  555.         x = wmod.catch_warnings(module=wmod, record=True)
  556.         self.assertRaises(RuntimeError, x.__exit__)
  557.         with x:
  558.             self.assertRaises(RuntimeError, x.__enter__)
  559.         # Same test, but with recording disabled
  560.         x = wmod.catch_warnings(module=wmod, record=False)
  561.         self.assertRaises(RuntimeError, x.__exit__)
  562.         with x:
  563.             self.assertRaises(RuntimeError, x.__enter__)
  564.  
  565.     def test_catch_warnings_defaults(self):
  566.         wmod = self.module
  567.         orig_filters = wmod.filters
  568.         orig_showwarning = wmod.showwarning
  569.         # Ensure default behaviour is not to record warnings
  570.         with wmod.catch_warnings(module=wmod) as w:
  571.             self.assert_(w is None)
  572.             self.assert_(wmod.showwarning is orig_showwarning)
  573.             self.assert_(wmod.filters is not orig_filters)
  574.         self.assert_(wmod.filters is orig_filters)
  575.         if wmod is sys.modules['warnings']:
  576.             # Ensure the default module is this one
  577.             with wmod.catch_warnings() as w:
  578.                 self.assert_(w is None)
  579.                 self.assert_(wmod.showwarning is orig_showwarning)
  580.                 self.assert_(wmod.filters is not orig_filters)
  581.             self.assert_(wmod.filters is orig_filters)
  582.  
  583.     def test_check_warnings(self):
  584.         # Explicit tests for the test_support convenience wrapper
  585.         wmod = self.module
  586.         if wmod is sys.modules['warnings']:
  587.             with test_support.check_warnings() as w:
  588.                 self.assertEqual(w.warnings, [])
  589.                 wmod.simplefilter("always")
  590.                 wmod.warn("foo")
  591.                 self.assertEqual(str(w.message), "foo")
  592.                 wmod.warn("bar")
  593.                 self.assertEqual(str(w.message), "bar")
  594.                 self.assertEqual(str(w.warnings[0].message), "foo")
  595.                 self.assertEqual(str(w.warnings[1].message), "bar")
  596.                 w.reset()
  597.                 self.assertEqual(w.warnings, [])
  598.  
  599.  
  600.  
  601. class CCatchWarningTests(CatchWarningTests):
  602.     module = c_warnings
  603.  
  604. class PyCatchWarningTests(CatchWarningTests):
  605.     module = py_warnings
  606.  
  607.  
  608. class ShowwarningDeprecationTests(BaseTest):
  609.  
  610.     """Test the deprecation of the old warnings.showwarning() API works."""
  611.  
  612.     @staticmethod
  613.     def bad_showwarning(message, category, filename, lineno, file=None):
  614.         pass
  615.  
  616.     @staticmethod
  617.     def ok_showwarning(*args):
  618.         pass
  619.  
  620.     def test_deprecation(self):
  621.         # message, category, filename, lineno[, file[, line]]
  622.         args = ("message", UserWarning, "file name", 42)
  623.         with original_warnings.catch_warnings(module=self.module):
  624.             self.module.filterwarnings("error", category=DeprecationWarning)
  625.             self.module.showwarning = self.bad_showwarning
  626.             self.assertRaises(DeprecationWarning, self.module.warn_explicit,
  627.                                 *args)
  628.             self.module.showwarning = self.ok_showwarning
  629.             try:
  630.                 self.module.warn_explicit(*args)
  631.             except DeprecationWarning as exc:
  632.                 self.fail('showwarning(*args) should not trigger a '
  633.                             'DeprecationWarning')
  634.  
  635. class CShowwarningDeprecationTests(ShowwarningDeprecationTests):
  636.     module = c_warnings
  637.  
  638.  
  639. class PyShowwarningDeprecationTests(ShowwarningDeprecationTests):
  640.     module = py_warnings
  641.  
  642.  
  643. def test_main():
  644.     py_warnings.onceregistry.clear()
  645.     c_warnings.onceregistry.clear()
  646.     test_support.run_unittest(CFilterTests, PyFilterTests,
  647.                                 CWarnTests, PyWarnTests,
  648.                                 CWCmdLineTests, PyWCmdLineTests,
  649.                                 _WarningsTests,
  650.                                 CWarningsDisplayTests, PyWarningsDisplayTests,
  651.                                 CCatchWarningTests, PyCatchWarningTests,
  652.                                 CShowwarningDeprecationTests,
  653.                                     PyShowwarningDeprecationTests,
  654.                              )
  655.  
  656.  
  657. if __name__ == "__main__":
  658.     test_main()
  659.