Debian Codegraph @

tests/test_apython.py

raw symbols SCIP
1 import io
2 import sys
3 from contextlib import contextmanager
4
5 from unittest.mock import Mock, patch, call
6
7 import pytest
8
9 from aioconsole import InteractiveEventLoop, apython, rlwrap, compat
10
11
12 startupfile = """
13 def hehe():
14 return 42
15
16 foo = 1
17
18 # Imports work
19 import math
20 r = math.cos(0)
21
22 # Exec works and is visible from the interpreter
23 s = 'from pprint import pprint'
24 exec(s)
25
26 """
27
28
29 @contextmanager
30 def mock_module(name):
31 try:
32 module = sys.modules.get(name)
33 sys.modules[name] = Mock()
34 yield sys.modules[name]
35 finally:
36 if module is None:
37 del sys.modules[name]
38 else:
39 sys.modules[name] = module
40
41
42 @pytest.fixture(params=["linux", "darwin", "win32"])
43 def platform(request):
44 with patch("aioconsole.compat.platform", new=request.param):
45 yield request.param
46
47
48 @pytest.fixture
49 def mock_readline(platform):
50 with mock_module("readline"):
51 with patch("aioconsole.rlwrap.ctypes") as m_ctypes:
52 if platform == "darwin":
53 stdin = "__stdinp"
54 stderr = "__stderrp"
55 else:
56 stdin = "stdin"
57 stderr = "stderr"
58
59 def readline(fin, ferr, prompt):
60 sys.stderr.write(prompt.decode())
61 return sys.stdin.readline().encode()
62
63 api = m_ctypes.pythonapi
64 call_readline = api.PyOS_Readline
65 call_readline.side_effect = readline
66
67 if platform == "darwin":
68 with patch("aioconsole.rlwrap.fcntl", create=True):
69 yield call_readline
70 else:
71 yield call_readline
72
73 if call_readline.called:
74 m_ctypes.c_void_p.in_dll.assert_has_calls(
75 [call(api, stdin), call(api, stderr)]
76 )
77
78
79 @pytest.fixture(params=["readline", "no-readline"])
80 def use_readline(request, mock_readline, platform):
81 if request.param == "readline":
82 # Readline tests hang on windows for some reason
83 if sys.platform == "win32":
84 pytest.xfail()
85 return []
86 return ["--no-readline"]
87
88
89 def test_input_with_stderr_prompt(mock_readline):
90 with patch("sys.stdin", new=io.StringIO("test\n")):
91 assert rlwrap.input(use_stderr=True) == "test"
92
93
94 def test_basic_apython_usage(capfd, use_readline):
95 with patch("sys.stdin", new=io.StringIO("1+1\n")):
96 with pytest.raises(SystemExit):
97 apython.run_apython(["--banner=test"] + use_readline)
98 out, err = capfd.readouterr()
99 assert out == ""
100 assert err == "test\n>>> 2\n>>> \n"
101
102
103 def test_missing_readline(capfd, use_readline):
104 sys.modules["readline"] = None
105 with patch("sys.stdin", new=io.StringIO("1+1\n")):
106 with pytest.raises(SystemExit):
107 apython.run_apython(["--banner=test"] + use_readline)
108 out, err = capfd.readouterr()
109 assert out == ""
110 assert err == "test\n>>> 2\n>>> \n"
111
112
113 def test_interactive_hook_error(capfd, use_readline, platform):
114 sys.modules["readline"].parse_and_bind.side_effect = ZeroDivisionError()
115 with patch("sys.stdin", new=io.StringIO("1+1\n")):
116 with pytest.raises(SystemExit):
117 with pytest.warns(UserWarning):
118 apython.run_apython(["--banner=test"] + use_readline)
119 out, err = capfd.readouterr()
120 assert out == ""
121 assert err == "test\n>>> 2\n>>> \n"
122
123
124 def test_basic_apython_usage_with_sys_argv(capfd, use_readline):
125 with patch("sys.argv", new=["path.py", "--banner=test"] + use_readline):
126 with patch("sys.stdin", new=io.StringIO("1+1\n")):
127 with pytest.raises(SystemExit):
128 apython.run_apython()
129 out, err = capfd.readouterr()
130 assert out == ""
131 assert err == "test\n>>> 2\n>>> \n"
132
133
134 def test_apython_with_prompt_control(capfd):
135 with patch("sys.stdin", new=io.StringIO("1+1\n")):
136 with pytest.raises(SystemExit):
137 apython.run_apython(
138 ["--banner=test", "--prompt-control=▲", "--no-readline"]
139 )
140 out, err = capfd.readouterr()
141 assert out == ""
142 assert err == "test\n▲>>> ▲2\n▲>>> ▲\n"
143
144
145 def test_apython_with_prompt_control_and_ainput(capfd):
146 input_string = "await ainput()\nhello\n"
147 with patch("sys.stdin", new=io.StringIO(input_string)):
148 with pytest.raises(SystemExit):
149 apython.run_apython(
150 ["--no-readline", "--banner=test", "--prompt-control=▲"]
151 )
152 out, err = capfd.readouterr()
153 assert out == ""
154 assert err == "test\n▲>>> ▲▲▲'hello'\n▲>>> ▲\n"
155
156
157 def test_apython_with_ainput(capfd, use_readline):
158 input_string = "await ainput()\nhello\n"
159 with patch("sys.stdin", new=io.StringIO(input_string)):
160 with pytest.raises(SystemExit):
161 apython.run_apython(["--banner=test"] + use_readline)
162 out, err = capfd.readouterr()
163 assert out == ""
164 assert err == "test\n>>> 'hello'\n>>> \n"
165
166
167 def test_apython_with_stdout_logs(capfd, use_readline):
168 with patch(
169 "sys.stdin", new=io.StringIO('import sys; sys.stdout.write("logging") or 7\n')
170 ):
171 with pytest.raises(SystemExit):
172 apython.run_apython(["--banner=test"] + use_readline)
173 out, err = capfd.readouterr()
174 assert out == "logging"
175 assert err == "test\n>>> 7\n>>> \n"
176
177
178 def test_apython_server(capfd):
179 def run_forever(self, orig=InteractiveEventLoop.run_forever):
180 if self.console_server is not None:
181 self.call_later(0, self.stop)
182 return orig(self)
183
184 with patch("aioconsole.InteractiveEventLoop.run_forever", run_forever):
185 with pytest.raises(SystemExit):
186 apython.run_apython(["--serve=:0"])
187 out, err = capfd.readouterr()
188 assert out.startswith("The console is being served on")
189 assert err == ""
190
191
192 @pytest.mark.skipif(
193 compat.platform == "win32", reason="apython does not run in a subprocess on windows"
194 )
195 def test_apython_non_existing_file(capfd):
196 with pytest.raises(SystemExit):
197 apython.run_apython(["idontexist.py"])
198 out, err = capfd.readouterr()
199 assert out == ""
200 assert "No such file or directory" in err
201 assert "idontexist.py" in err
202
203
204 @pytest.mark.skipif(
205 compat.platform == "win32", reason="apython does not run in a subprocess on windows"
206 )
207 def test_apython_non_existing_module(capfd):
208 with pytest.raises(SystemExit):
209 apython.run_apython(["-m", "idontexist"])
210 out, err = capfd.readouterr()
211 assert out == ""
212 assert "No module named idontexist" in err
213
214
215 def test_apython_pythonstartup(capfd, use_readline, monkeypatch, tmpdir):
216 python_startup = tmpdir / "python_startup.py"
217 monkeypatch.setenv("PYTHONSTARTUP", str(python_startup))
218 python_startup.write(startupfile)
219
220 test_vectors = (
221 ("print(foo)\n", "", ">>> 1\n"),
222 ("print(hehe())\n", "", ">>> 42\n"),
223 ("print(r)\n", "", ">>> 1.0\n"),
224 ("pprint({1:2})\n", "{1: 2}\n", ">>> >>> \n"),
225 )
226 inputstr = "".join([tv[0] for tv in test_vectors])
227 outstr = "".join([tv[1] for tv in test_vectors])
228 errstr = "test\n" + "".join([tv[2] for tv in test_vectors])
229
230 with patch("sys.stdin", new=io.StringIO(inputstr)):
231 with pytest.raises(SystemExit):
232 apython.run_apython(["--banner=test"] + use_readline)
233 out, err = capfd.readouterr()
234 assert out == outstr
235 assert err == errstr