Issue #12643: Respect sys.excepthook in code.InteractiveConsole · python/cpython@8bd24fe

GitHub

@@ -0,0 +1,72 @@

1+"Test InteractiveConsole and InteractiveInterpreter from code module"

2+importsys

3+importunittest

4+fromcontextlibimportExitStack

5+fromunittestimportmock

6+fromtestimportsupport

7+8+code=support.import_module('code')

9+10+11+classTestInteractiveConsole(unittest.TestCase):

12+13+defsetUp(self):

14+self.console=code.InteractiveConsole()

15+self.mock_sys()

16+17+defmock_sys(self):

18+"Mock system environment for InteractiveConsole"

19+# use exit stack to match patch context managers to addCleanup

20+stack=ExitStack()

21+self.addCleanup(stack.close)

22+self.infunc=stack.enter_context(mock.patch('code.input',

23+create=True))

24+self.stdout=stack.enter_context(mock.patch('code.sys.stdout'))

25+self.stderr=stack.enter_context(mock.patch('code.sys.stderr'))

26+prepatch=mock.patch('code.sys', wraps=code.sys, spec=code.sys)

27+self.sysmod=stack.enter_context(prepatch)

28+ifsys.excepthookissys.__excepthook__:

29+self.sysmod.excepthook=self.sysmod.__excepthook__

30+31+deftest_ps1(self):

32+self.infunc.side_effect=EOFError('Finished')

33+self.console.interact()

34+self.assertEqual(self.sysmod.ps1, '>>> ')

35+36+deftest_ps2(self):

37+self.infunc.side_effect=EOFError('Finished')

38+self.console.interact()

39+self.assertEqual(self.sysmod.ps2, '... ')

40+41+deftest_console_stderr(self):

42+self.infunc.side_effect= ["'antioch'", "", EOFError('Finished')]

43+self.console.interact()

44+forcallinlist(self.stdout.method_calls):

45+if'antioch'in''.join(call[1]):

46+break

47+else:

48+raiseAssertionError("no console stdout")

49+50+deftest_syntax_error(self):

51+self.infunc.side_effect= ["undefined", EOFError('Finished')]

52+self.console.interact()

53+forcallinself.stderr.method_calls:

54+if'NameError:'in''.join(call[1]):

55+break

56+else:

57+raiseAssertionError("No syntax error from console")

58+59+deftest_sysexcepthook(self):

60+self.infunc.side_effect= ["raise ValueError('')",

61+EOFError('Finished')]

62+hook=mock.Mock()

63+self.sysmod.excepthook=hook

64+self.console.interact()

65+self.assertTrue(hook.called)

66+67+68+deftest_main():

69+support.run_unittest(TestInteractiveConsole)

70+71+if__name__=="__main__":

72+unittest.main()