Debian Codegraph @

tests/test_run_pyscript.py

raw symbols SCIP
1 """Unit/functional testing for run_pytest in cmd2"""
2
3 import os
4 import pathlib
5 from unittest import (
6 mock,
7 )
8
9 import pytest
10
11 from cmd2 import rich_utils as ru
12 from cmd2.string_utils import quote
13
14 from .conftest import (
15 odd_file_names,
16 run_cmd,
17 with_ansi_style,
18 )
19
20
21 def test_run_pyscript(base_app, request) -> None:
22 test_dir = os.path.dirname(request.module.__file__)
23 python_script = os.path.join(test_dir, "script.py")
24 expected = "This is a python script running ..."
25
26 out, _err = run_cmd(base_app, f"run_pyscript {python_script}")
27 assert expected in out
28 assert base_app.last_result is True
29
30
31 def test_run_pyscript_recursive_not_allowed(base_app, request) -> None:
32 test_dir = os.path.dirname(request.module.__file__)
33 python_script = os.path.join(test_dir, "pyscript", "recursive.py")
34 expected = "Recursively entering interactive Python shells is not allowed"
35
36 _out, err = run_cmd(base_app, f"run_pyscript {python_script}")
37 assert err[0] == expected
38 assert base_app.last_result is False
39
40
41 def test_run_pyscript_with_nonexist_file(base_app) -> None:
42 python_script = "does_not_exist.py"
43 _out, err = run_cmd(base_app, f"run_pyscript {python_script}")
44 assert "Error reading script file" in err[0]
45 assert base_app.last_result is False
46
47
48 def test_run_pyscript_with_non_python_file(base_app, request, monkeypatch) -> None:
49 # Mock out the read_input call so we don't actually wait for a user's response on stdin
50 read_input_mock = mock.MagicMock(name="read_input", return_value="2")
51 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
52
53 test_dir = os.path.dirname(request.module.__file__)
54 filename = os.path.join(test_dir, "scripts", "help.txt")
55 _out, err = run_cmd(base_app, f"run_pyscript {filename}")
56 assert "does not have a .py extension" in err[0]
57 assert base_app.last_result is False
58
59
60 @pytest.mark.parametrize("python_script", odd_file_names)
61 def test_run_pyscript_with_odd_file_names(base_app, python_script, monkeypatch) -> None:
62 """Pass in file names with various patterns. Since these files don't exist, we will rely
63 on the error text to make sure the file names were processed correctly.
64 """
65 # Mock read_input to get us passed the warning about not ending in .py
66 read_input_mock = mock.MagicMock(name="read_input", return_value="1")
67 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
68
69 _out, err = run_cmd(base_app, f"run_pyscript {quote(python_script)}")
70 err = "".join(err)
71 assert f"Error reading script file '{python_script}'" in err
72 assert base_app.last_result is False
73
74
75 def test_run_pyscript_with_exception(base_app, request) -> None:
76 test_dir = os.path.dirname(request.module.__file__)
77 python_script = os.path.join(test_dir, "pyscript", "raises_exception.py")
78 _out, err = run_cmd(base_app, f"run_pyscript {python_script}")
79 assert err[0].startswith("Traceback")
80 assert "TypeError: unsupported operand type(s) for +: 'int' and 'str'" in err[-1]
81 assert base_app.last_result is True
82
83
84 def test_run_pyscript_requires_an_argument(base_app) -> None:
85 _out, err = run_cmd(base_app, "run_pyscript")
86 assert "the following arguments are required: script_path" in err[1]
87 assert base_app.last_result is None
88
89
90 def test_run_pyscript_help(base_app, request) -> None:
91 test_dir = os.path.dirname(request.module.__file__)
92 python_script = os.path.join(test_dir, "pyscript", "help.py")
93 out1, _err1 = run_cmd(base_app, "help")
94 out2, _err2 = run_cmd(base_app, f"run_pyscript {python_script}")
95 assert out1
96 assert out1 == out2
97
98
99 def test_scripts_add_to_history(base_app, request) -> None:
100 test_dir = os.path.dirname(request.module.__file__)
101 python_script = os.path.join(test_dir, "pyscript", "help.py")
102 command = f"run_pyscript {python_script}"
103
104 # Add to history
105 base_app.scripts_add_to_history = True
106 base_app.history.clear()
107 run_cmd(base_app, command)
108 assert len(base_app.history) == 2
109 assert base_app.history.get(1).raw == command
110 assert base_app.history.get(2).raw == "help"
111
112 # Do not add to history
113 base_app.scripts_add_to_history = False
114 base_app.history.clear()
115 run_cmd(base_app, command)
116 assert len(base_app.history) == 1
117 assert base_app.history.get(1).raw == command
118
119
120 def test_run_pyscript_dir(base_app, request) -> None:
121 test_dir = os.path.dirname(request.module.__file__)
122 python_script = os.path.join(test_dir, "pyscript", "pyscript_dir.py")
123
124 out, _err = run_cmd(base_app, f"run_pyscript {python_script}")
125 assert out[0] == "['cmd_echo']"
126
127
128 def test_py_bridge_capture_isolation() -> None:
129 """Verify that PyBridge captures poutput but not raw print from within a command."""
130 import cmd2
131 from cmd2.py_bridge import PyBridge
132
133 class App(cmd2.Cmd):
134 def do_test_capture(self, _):
135 print("process_stdout")
136 self.poutput("app_stdout")
137
138 app = App()
139 bridge = PyBridge(app)
140 result = bridge("test_capture")
141
142 # Verify isolation: only the application stream should be in the result
143 assert result.stdout == "app_stdout\n"
144 assert "process_stdout" not in result.stdout
145
146
147 def test_run_pyscript_stop(base_app, request) -> None:
148 # Verify onecmd_plus_hooks() returns True if any commands in a pyscript return True for stop
149 test_dir = os.path.dirname(request.module.__file__)
150
151 # help.py doesn't run any commands that return True for stop
152 python_script = os.path.join(test_dir, "pyscript", "help.py")
153 stop = base_app.onecmd_plus_hooks(f"run_pyscript {python_script}")
154 assert not stop
155
156 # stop.py runs the quit command which does return True for stop
157 python_script = os.path.join(test_dir, "pyscript", "stop.py")
158 stop = base_app.onecmd_plus_hooks(f"run_pyscript {python_script}")
159 assert stop
160
161
162 def test_run_pyscript_environment(base_app, request) -> None:
163 test_dir = os.path.dirname(request.module.__file__)
164 python_script = os.path.join(test_dir, "pyscript", "environment.py")
165 out, _err = run_cmd(base_app, f"run_pyscript {python_script}")
166
167 assert out[0] == "PASSED"
168
169
170 def test_run_pyscript_self_in_py(base_app, request) -> None:
171 test_dir = os.path.dirname(request.module.__file__)
172 python_script = os.path.join(test_dir, "pyscript", "self_in_py.py")
173
174 # Set self_in_py to True and make sure we see self
175 base_app.self_in_py = True
176 out, _err = run_cmd(base_app, f"run_pyscript {python_script}")
177 assert "I see self" in out[0]
178
179 # Set self_in_py to False and make sure we can't see self
180 base_app.self_in_py = False
181 out, _err = run_cmd(base_app, f"run_pyscript {python_script}")
182 assert "I do not see self" in out[0]
183
184
185 def test_run_pyscript_py_locals(base_app, request) -> None:
186 test_dir = os.path.dirname(request.module.__file__)
187 python_script = os.path.join(test_dir, "pyscript", "py_locals.py")
188
189 # Make sure pyscripts can't edit Cmd.py_locals. It used to be that cmd2 was passing its py_locals
190 # dictionary to the py environment instead of a shallow copy.
191 base_app.py_locals["test_var"] = 5
192
193 # Place an editable object in py_locals. Since we make a shallow copy of py_locals,
194 # this object should be editable from the py environment.
195 base_app.py_locals["my_list"] = []
196
197 run_cmd(base_app, f"run_pyscript {python_script}")
198
199 # test_var should still exist
200 assert base_app.py_locals["test_var"] == 5
201
202 # my_list should be edited
203 assert base_app.py_locals["my_list"][0] == 2
204
205
206 def test_run_pyscript_app_echo(base_app, request) -> None:
207 test_dir = os.path.dirname(request.module.__file__)
208 python_script = os.path.join(test_dir, "pyscript", "echo.py")
209 out, _err = run_cmd(base_app, f"run_pyscript {python_script}")
210
211 # Only the edit help text should have been echoed to pytest's stdout
212 assert out[0] == "Usage: edit [-h] [file_path]"
213
214
215 @with_ansi_style(ru.AllowStyle.ALWAYS)
216 def test_run_pyscript_print(base_app, request, capsys) -> None:
217 """Verify that py_print() (the print() replacement in pyscripts) works correctly."""
218 test_dir = os.path.dirname(request.module.__file__)
219 python_script = os.path.join(test_dir, "pyscript", "test_print.py")
220 out, err = run_cmd(base_app, f"run_pyscript {python_script}")
221
222 # Verify contents of self.stdout
223 assert len(out) == 4
224 assert out[0] == "hello-world"
225 assert out[1] == "no newline here"
226 assert out[2] == "1:2:3."
227 assert out[3] == "\x1b[34mI am Rich Text\x1b[0m"
228
229 # Verify contents of sys.stderr
230 assert len(err) == 1
231 assert err[0] == "this goes to sys.stderr"
232
233 # Verify contents of sys.stdout
234 stdout, _ = capsys.readouterr()
235 assert "this goes to sys.stdout" in stdout
236
237
238 def test_run_pyscript_print_redirection(base_app, request, tmp_path, capsys) -> None:
239 """Verify that py_print() (the print() replacement in pyscripts) respects cmd2 redirection."""
240 test_dir = os.path.dirname(request.module.__file__)
241 python_script = os.path.join(test_dir, "pyscript", "test_print.py")
242 out_file = tmp_path / "out.txt"
243
244 # Run the pyscript with redirection
245 base_app.onecmd_plus_hooks(f"run_pyscript {python_script} > {out_file}")
246 out, err = capsys.readouterr()
247
248 # Verify the output file contains what we expect from print()
249 content = pathlib.Path(out_file).read_text()
250
251 # Look for everything written to self.stdout
252 assert len(content.splitlines()) == 4
253 assert "hello-world\n" in content
254 assert "no newline here\n" in content
255 assert "1:2:3.\n" in content
256 assert "I am Rich Text\n" in content
257
258 # Nothing else should have been redirected
259 assert "this goes to sys.stdout" not in content
260 assert "this goes to sys.stderr" not in content
261
262 # Verify the remaining output when to the correct stream
263 assert "this goes to sys.stdout" in out
264 assert "this goes to sys.stderr" in err