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