Nick Coghlan | 8bd24fe | 2012-08-20 23:02:28 +1000 | [diff] [blame] | 1 | "Test InteractiveConsole and InteractiveInterpreter from code module" |
| 2 | import sys |
| 3 | import unittest |
| 4 | from contextlib import ExitStack |
| 5 | from unittest import mock |
| 6 | from test import support |
| 7 | |
| 8 | code = support.import_module('code') |
| 9 | |
| 10 | |
| 11 | class 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 | |
| 68 | def test_main(): |
| 69 | support.run_unittest(TestInteractiveConsole) |
| 70 | |
| 71 | if __name__ == "__main__": |
| 72 | unittest.main() |