blob: adef1701d46a469b41335a2579bf8ff753bbb3e4 [file] [log] [blame]
Nick Coghlan8bd24fe2012-08-20 23:02:28 +10001"Test InteractiveConsole and InteractiveInterpreter from code module"
2import sys
3import unittest
4from contextlib import ExitStack
5from unittest import mock
6from test import support
7
8code = support.import_module('code')
9
10
11class TestInteractiveConsole(unittest.TestCase):
12
13 def setUp(self):
14 self.console = code.InteractiveConsole()
15 self.mock_sys()
16
17 def mock_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 if sys.excepthook is sys.__excepthook__:
29 self.sysmod.excepthook = self.sysmod.__excepthook__
30
31 def test_ps1(self):
32 self.infunc.side_effect = EOFError('Finished')
33 self.console.interact()
34 self.assertEqual(self.sysmod.ps1, '>>> ')
35
36 def test_ps2(self):
37 self.infunc.side_effect = EOFError('Finished')
38 self.console.interact()
39 self.assertEqual(self.sysmod.ps2, '... ')
40
41 def test_console_stderr(self):
42 self.infunc.side_effect = ["'antioch'", "", EOFError('Finished')]
43 self.console.interact()
44 for call in list(self.stdout.method_calls):
45 if 'antioch' in ''.join(call[1]):
46 break
47 else:
48 raise AssertionError("no console stdout")
49
50 def test_syntax_error(self):
51 self.infunc.side_effect = ["undefined", EOFError('Finished')]
52 self.console.interact()
53 for call in self.stderr.method_calls:
54 if 'NameError:' in ''.join(call[1]):
55 break
56 else:
57 raise AssertionError("No syntax error from console")
58
59 def test_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
68def test_main():
69 support.run_unittest(TestInteractiveConsole)
70
71if __name__ == "__main__":
72 unittest.main()