_test_warnings.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # helper module for test_runner.Test_TextTestRunner.test_warnings
  2. """
  3. This module has a number of tests that raise different kinds of warnings.
  4. When the tests are run, the warnings are caught and their messages are printed
  5. to stdout. This module also accepts an arg that is then passed to
  6. unittest.main to affect the behavior of warnings.
  7. Test_TextTestRunner.test_warnings executes this script with different
  8. combinations of warnings args and -W flags and check that the output is correct.
  9. See #10535.
  10. """
  11. import sys
  12. import unittest
  13. import warnings
  14. def warnfun():
  15. warnings.warn('rw', RuntimeWarning)
  16. class TestWarnings(unittest.TestCase):
  17. # unittest warnings will be printed at most once per type (max one message
  18. # for the fail* methods, and one for the assert* methods)
  19. def test_assert(self):
  20. self.assertEquals(2+2, 4)
  21. self.assertEquals(2*2, 4)
  22. self.assertEquals(2**2, 4)
  23. def test_fail(self):
  24. self.failUnless(1)
  25. self.failUnless(True)
  26. def test_other_unittest(self):
  27. self.assertAlmostEqual(2+2, 4)
  28. self.assertNotAlmostEqual(4+4, 2)
  29. # these warnings are normally silenced, but they are printed in unittest
  30. def test_deprecation(self):
  31. warnings.warn('dw', DeprecationWarning)
  32. warnings.warn('dw', DeprecationWarning)
  33. warnings.warn('dw', DeprecationWarning)
  34. def test_import(self):
  35. warnings.warn('iw', ImportWarning)
  36. warnings.warn('iw', ImportWarning)
  37. warnings.warn('iw', ImportWarning)
  38. # user warnings should always be printed
  39. def test_warning(self):
  40. warnings.warn('uw')
  41. warnings.warn('uw')
  42. warnings.warn('uw')
  43. # these warnings come from the same place; they will be printed
  44. # only once by default or three times if the 'always' filter is used
  45. def test_function(self):
  46. warnfun()
  47. warnfun()
  48. warnfun()
  49. if __name__ == '__main__':
  50. with warnings.catch_warnings(record=True) as ws:
  51. # if an arg is provided pass it to unittest.main as 'warnings'
  52. if len(sys.argv) == 2:
  53. unittest.main(exit=False, warnings=sys.argv.pop())
  54. else:
  55. unittest.main(exit=False)
  56. # print all the warning messages collected
  57. for w in ws:
  58. print(w.message)