File: test_apython.py

package info (click to toggle)
aioconsole 0.8.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 332 kB
  • sloc: python: 2,022; makefile: 6
file content (235 lines) | stat: -rw-r--r-- 7,399 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import io
import sys
from contextlib import contextmanager

from unittest.mock import Mock, patch, call

import pytest

from aioconsole import InteractiveEventLoop, apython, rlwrap, compat


startupfile = """
def hehe():
    return 42

foo = 1

# Imports work
import math
r = math.cos(0)

# Exec works and is visible from the interpreter
s = 'from pprint import pprint'
exec(s)

"""


@contextmanager
def mock_module(name):
    try:
        module = sys.modules.get(name)
        sys.modules[name] = Mock()
        yield sys.modules[name]
    finally:
        if module is None:
            del sys.modules[name]
        else:
            sys.modules[name] = module


@pytest.fixture(params=["linux", "darwin", "win32"])
def platform(request):
    with patch("aioconsole.compat.platform", new=request.param):
        yield request.param


@pytest.fixture
def mock_readline(platform):
    with mock_module("readline"):
        with patch("aioconsole.rlwrap.ctypes") as m_ctypes:
            if platform == "darwin":
                stdin = "__stdinp"
                stderr = "__stderrp"
            else:
                stdin = "stdin"
                stderr = "stderr"

            def readline(fin, ferr, prompt):
                sys.stderr.write(prompt.decode())
                return sys.stdin.readline().encode()

            api = m_ctypes.pythonapi
            call_readline = api.PyOS_Readline
            call_readline.side_effect = readline

            if platform == "darwin":
                with patch("aioconsole.rlwrap.fcntl", create=True):
                    yield call_readline
            else:
                yield call_readline

            if call_readline.called:
                m_ctypes.c_void_p.in_dll.assert_has_calls(
                    [call(api, stdin), call(api, stderr)]
                )


@pytest.fixture(params=["readline", "no-readline"])
def use_readline(request, mock_readline, platform):
    if request.param == "readline":
        # Readline tests hang on windows for some reason
        if sys.platform == "win32":
            pytest.xfail()
        return []
    return ["--no-readline"]


def test_input_with_stderr_prompt(mock_readline):
    with patch("sys.stdin", new=io.StringIO("test\n")):
        assert rlwrap.input(use_stderr=True) == "test"


def test_basic_apython_usage(capfd, use_readline):
    with patch("sys.stdin", new=io.StringIO("1+1\n")):
        with pytest.raises(SystemExit):
            apython.run_apython(["--banner=test"] + use_readline)
    out, err = capfd.readouterr()
    assert out == ""
    assert err == "test\n>>> 2\n>>> \n"


def test_missing_readline(capfd, use_readline):
    sys.modules["readline"] = None
    with patch("sys.stdin", new=io.StringIO("1+1\n")):
        with pytest.raises(SystemExit):
            apython.run_apython(["--banner=test"] + use_readline)
    out, err = capfd.readouterr()
    assert out == ""
    assert err == "test\n>>> 2\n>>> \n"


def test_interactive_hook_error(capfd, use_readline, platform):
    sys.modules["readline"].parse_and_bind.side_effect = ZeroDivisionError()
    with patch("sys.stdin", new=io.StringIO("1+1\n")):
        with pytest.raises(SystemExit):
            with pytest.warns(UserWarning):
                apython.run_apython(["--banner=test"] + use_readline)
    out, err = capfd.readouterr()
    assert out == ""
    assert err == "test\n>>> 2\n>>> \n"


def test_basic_apython_usage_with_sys_argv(capfd, use_readline):
    with patch("sys.argv", new=["path.py", "--banner=test"] + use_readline):
        with patch("sys.stdin", new=io.StringIO("1+1\n")):
            with pytest.raises(SystemExit):
                apython.run_apython()
    out, err = capfd.readouterr()
    assert out == ""
    assert err == "test\n>>> 2\n>>> \n"


def test_apython_with_prompt_control(capfd):
    with patch("sys.stdin", new=io.StringIO("1+1\n")):
        with pytest.raises(SystemExit):
            apython.run_apython(
                ["--banner=test", "--prompt-control=▲", "--no-readline"]
            )
    out, err = capfd.readouterr()
    assert out == ""
    assert err == "test\n▲>>> ▲2\n▲>>> ▲\n"


def test_apython_with_prompt_control_and_ainput(capfd):
    input_string = "await ainput()\nhello\n"
    with patch("sys.stdin", new=io.StringIO(input_string)):
        with pytest.raises(SystemExit):
            apython.run_apython(
                ["--no-readline", "--banner=test", "--prompt-control=▲"]
            )
    out, err = capfd.readouterr()
    assert out == ""
    assert err == "test\n▲>>> ▲▲▲'hello'\n▲>>> ▲\n"


def test_apython_with_ainput(capfd, use_readline):
    input_string = "await ainput()\nhello\n"
    with patch("sys.stdin", new=io.StringIO(input_string)):
        with pytest.raises(SystemExit):
            apython.run_apython(["--banner=test"] + use_readline)
    out, err = capfd.readouterr()
    assert out == ""
    assert err == "test\n>>> 'hello'\n>>> \n"


def test_apython_with_stdout_logs(capfd, use_readline):
    with patch(
        "sys.stdin", new=io.StringIO('import sys; sys.stdout.write("logging") or 7\n')
    ):
        with pytest.raises(SystemExit):
            apython.run_apython(["--banner=test"] + use_readline)
    out, err = capfd.readouterr()
    assert out == "logging"
    assert err == "test\n>>> 7\n>>> \n"


def test_apython_server(capfd):
    def run_forever(self, orig=InteractiveEventLoop.run_forever):
        if self.console_server is not None:
            self.call_later(0, self.stop)
        return orig(self)

    with patch("aioconsole.InteractiveEventLoop.run_forever", run_forever):
        with pytest.raises(SystemExit):
            apython.run_apython(["--serve=:0"])
    out, err = capfd.readouterr()
    assert out.startswith("The console is being served on")
    assert err == ""


@pytest.mark.skipif(
    compat.platform == "win32", reason="apython does not run in a subprocess on windows"
)
def test_apython_non_existing_file(capfd):
    with pytest.raises(SystemExit):
        apython.run_apython(["idontexist.py"])
    out, err = capfd.readouterr()
    assert out == ""
    assert "No such file or directory" in err
    assert "idontexist.py" in err


@pytest.mark.skipif(
    compat.platform == "win32", reason="apython does not run in a subprocess on windows"
)
def test_apython_non_existing_module(capfd):
    with pytest.raises(SystemExit):
        apython.run_apython(["-m", "idontexist"])
    out, err = capfd.readouterr()
    assert out == ""
    assert "No module named idontexist" in err


def test_apython_pythonstartup(capfd, use_readline, monkeypatch, tmpdir):
    python_startup = tmpdir / "python_startup.py"
    monkeypatch.setenv("PYTHONSTARTUP", str(python_startup))
    python_startup.write(startupfile)

    test_vectors = (
        ("print(foo)\n", "", ">>> 1\n"),
        ("print(hehe())\n", "", ">>> 42\n"),
        ("print(r)\n", "", ">>> 1.0\n"),
        ("pprint({1:2})\n", "{1: 2}\n", ">>> >>> \n"),
    )
    inputstr = "".join([tv[0] for tv in test_vectors])
    outstr = "".join([tv[1] for tv in test_vectors])
    errstr = "test\n" + "".join([tv[2] for tv in test_vectors])

    with patch("sys.stdin", new=io.StringIO(inputstr)):
        with pytest.raises(SystemExit):
            apython.run_apython(["--banner=test"] + use_readline)
    out, err = capfd.readouterr()
    assert out == outstr
    assert err == errstr