Back to index

python3.2  3.2.2
_test_warnings.py
Go to the documentation of this file.
00001 # helper module for test_runner.Test_TextTestRunner.test_warnings
00002 
00003 """
00004 This module has a number of tests that raise different kinds of warnings.
00005 When the tests are run, the warnings are caught and their messages are printed
00006 to stdout.  This module also accepts an arg that is then passed to
00007 unittest.main to affect the behavior of warnings.
00008 Test_TextTestRunner.test_warnings executes this script with different
00009 combinations of warnings args and -W flags and check that the output is correct.
00010 See #10535.
00011 """
00012 
00013 import io
00014 import sys
00015 import unittest
00016 import warnings
00017 
00018 def warnfun():
00019     warnings.warn('rw', RuntimeWarning)
00020 
00021 class TestWarnings(unittest.TestCase):
00022     # unittest warnings will be printed at most once per type (max one message
00023     # for the fail* methods, and one for the assert* methods)
00024     def test_assert(self):
00025         self.assertEquals(2+2, 4)
00026         self.assertEquals(2*2, 4)
00027         self.assertEquals(2**2, 4)
00028 
00029     def test_fail(self):
00030         self.failUnless(1)
00031         self.failUnless(True)
00032 
00033     def test_other_unittest(self):
00034         self.assertAlmostEqual(2+2, 4)
00035         self.assertNotAlmostEqual(4+4, 2)
00036 
00037     # these warnings are normally silenced, but they are printed in unittest
00038     def test_deprecation(self):
00039         warnings.warn('dw', DeprecationWarning)
00040         warnings.warn('dw', DeprecationWarning)
00041         warnings.warn('dw', DeprecationWarning)
00042 
00043     def test_import(self):
00044         warnings.warn('iw', ImportWarning)
00045         warnings.warn('iw', ImportWarning)
00046         warnings.warn('iw', ImportWarning)
00047 
00048     # user warnings should always be printed
00049     def test_warning(self):
00050         warnings.warn('uw')
00051         warnings.warn('uw')
00052         warnings.warn('uw')
00053 
00054     # these warnings come from the same place; they will be printed
00055     # only once by default or three times if the 'always' filter is used
00056     def test_function(self):
00057 
00058         warnfun()
00059         warnfun()
00060         warnfun()
00061 
00062 
00063 
00064 if __name__ == '__main__':
00065     with warnings.catch_warnings(record=True) as ws:
00066         # if an arg is provided pass it to unittest.main as 'warnings'
00067         if len(sys.argv) == 2:
00068             unittest.main(exit=False, warnings=sys.argv.pop())
00069         else:
00070             unittest.main(exit=False)
00071 
00072     # print all the warning messages collected
00073     for w in ws:
00074         print(w.message)