1import sys
2import unittest
3
4from unittest import mock
5from bpython.curtsiesfrontend.coderunner import CodeRunner, FakeOutput
6
7
8class TestCodeRunner(unittest.TestCase):
9    def setUp(self):
10        self.orig_stdout = sys.stdout
11        self.orig_stderr = sys.stderr
12
13    def tearDown(self):
14        sys.stdout = self.orig_stdout
15        sys.stderr = self.orig_stderr
16
17    def test_simple(self):
18        c = CodeRunner(
19            request_refresh=lambda: self.orig_stdout.flush()
20            or self.orig_stderr.flush()
21        )
22        stdout = FakeOutput(c, lambda *args, **kwargs: None, None)
23        stderr = FakeOutput(c, lambda *args, **kwargs: None, None)
24        sys.stdout = stdout
25        sys.stdout = stderr
26        c.load_code("1 + 1")
27        c.run_code()
28        c.run_code()
29        c.run_code()
30
31    def test_exception(self):
32        c = CodeRunner(
33            request_refresh=lambda: self.orig_stdout.flush()
34            or self.orig_stderr.flush()
35        )
36
37        def ctrlc():
38            raise KeyboardInterrupt()
39
40        stdout = FakeOutput(c, lambda x: ctrlc(), None)
41        stderr = FakeOutput(c, lambda *args, **kwargs: None, None)
42        sys.stdout = stdout
43        sys.stderr = stderr
44        c.load_code("1 + 1")
45        c.run_code()
46
47
48class TestFakeOutput(unittest.TestCase):
49    def assert_unicode(self, s):
50        self.assertIsInstance(s, str)
51
52    def test_bytes(self):
53        out = FakeOutput(mock.Mock(), self.assert_unicode, None)
54        out.write("native string type")
55