test_warning.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. '''Test warnings replacement in pyshell.py and run.py.
  2. This file could be expanded to include traceback overrides
  3. (in same two modules). If so, change name.
  4. Revise if output destination changes (http://bugs.python.org/issue18318).
  5. Make sure warnings module is left unaltered (http://bugs.python.org/issue18081).
  6. '''
  7. from idlelib import run
  8. from idlelib import pyshell as shell
  9. import unittest
  10. from test.support import captured_stderr
  11. import warnings
  12. # Try to capture default showwarning before Idle modules are imported.
  13. showwarning = warnings.showwarning
  14. # But if we run this file within idle, we are in the middle of the run.main loop
  15. # and default showwarnings has already been replaced.
  16. running_in_idle = 'idle' in showwarning.__name__
  17. # The following was generated from pyshell.idle_formatwarning
  18. # and checked as matching expectation.
  19. idlemsg = '''
  20. Warning (from warnings module):
  21. File "test_warning.py", line 99
  22. Line of code
  23. UserWarning: Test
  24. '''
  25. shellmsg = idlemsg + ">>> "
  26. class RunWarnTest(unittest.TestCase):
  27. @unittest.skipIf(running_in_idle, "Does not work when run within Idle.")
  28. def test_showwarnings(self):
  29. self.assertIs(warnings.showwarning, showwarning)
  30. run.capture_warnings(True)
  31. self.assertIs(warnings.showwarning, run.idle_showwarning_subproc)
  32. run.capture_warnings(False)
  33. self.assertIs(warnings.showwarning, showwarning)
  34. def test_run_show(self):
  35. with captured_stderr() as f:
  36. run.idle_showwarning_subproc(
  37. 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code')
  38. # The following uses .splitlines to erase line-ending differences
  39. self.assertEqual(idlemsg.splitlines(), f.getvalue().splitlines())
  40. class ShellWarnTest(unittest.TestCase):
  41. @unittest.skipIf(running_in_idle, "Does not work when run within Idle.")
  42. def test_showwarnings(self):
  43. self.assertIs(warnings.showwarning, showwarning)
  44. shell.capture_warnings(True)
  45. self.assertIs(warnings.showwarning, shell.idle_showwarning)
  46. shell.capture_warnings(False)
  47. self.assertIs(warnings.showwarning, showwarning)
  48. def test_idle_formatter(self):
  49. # Will fail if format changed without regenerating idlemsg
  50. s = shell.idle_formatwarning(
  51. 'Test', UserWarning, 'test_warning.py', 99, 'Line of code')
  52. self.assertEqual(idlemsg, s)
  53. def test_shell_show(self):
  54. with captured_stderr() as f:
  55. shell.idle_showwarning(
  56. 'Test', UserWarning, 'test_warning.py', 99, f, 'Line of code')
  57. self.assertEqual(shellmsg.splitlines(), f.getvalue().splitlines())
  58. if __name__ == '__main__':
  59. unittest.main(verbosity=2)