Debian Codegraph @

tests/integrations/subprocess/test_Subprocess__run__controlled_console.py

raw
1 import os
2 import subprocess
3 from pathlib import Path
4 from unittest.mock import ANY
5
6 import pytest
7
8 from briefcase.console import LogLevel
9
10
11 def test_call(mock_sub, sub_stream_kw, sleep_zero, capsys):
12 """A simple call will be invoked."""
13
14 with mock_sub.tools.console.wait_bar():
15 mock_sub.run(["hello", "world"])
16
17 mock_sub._subprocess.Popen.assert_called_with(["hello", "world"], **sub_stream_kw)
18 # fmt: off
19 expected_output = (
20 "output line 1\n"
21 "\n"
22 "output line 3\n"
23 )
24 # fmt: on
25 assert capsys.readouterr().out == expected_output
26
27
28 def test_call_with_arg(mock_sub, sub_stream_kw, sleep_zero, capsys):
29 """Any extra keyword arguments are passed through as-is."""
30
31 with mock_sub.tools.console.wait_bar():
32 mock_sub.run(["hello", "world"], extra_kw="extra")
33
34 mock_sub._subprocess.Popen.assert_called_with(
35 ["hello", "world"],
36 extra_kw="extra",
37 **sub_stream_kw,
38 )
39 # fmt: off
40 expected_output = (
41 "output line 1\n"
42 "\n"
43 "output line 3\n"
44 )
45 # fmt: on
46 assert capsys.readouterr().out == expected_output
47
48
49 def test_debug_call(mock_sub, sub_stream_kw, sleep_zero, capsys):
50 """If verbosity is turned up, there is debug output."""
51 mock_sub.tools.console.verbosity = LogLevel.DEBUG
52
53 with mock_sub.tools.console.wait_bar():
54 mock_sub.run(["hello", "world"])
55
56 mock_sub._subprocess.Popen.assert_called_with(["hello", "world"], **sub_stream_kw)
57 expected_output = (
58 "\n"
59 ">>> Running Command:\n"
60 ">>> hello world\n"
61 ">>> Working Directory:\n"
62 f">>> {Path.cwd()}\n"
63 "output line 1\n"
64 "\n"
65 "output line 3\n"
66 ">>> Return code: -3\n"
67 "\n"
68 )
69 assert capsys.readouterr().out == expected_output
70
71
72 def test_debug_call_with_env(mock_sub, sub_stream_kw, sleep_zero, capsys, tmp_path):
73 """If verbosity is turned up, injected env vars are included in debug output."""
74 mock_sub.tools.console.verbosity = LogLevel.DEBUG
75
76 env = {"NewVar": "NewVarValue"}
77 with mock_sub.tools.console.wait_bar():
78 mock_sub.run(
79 ["hello", "world"],
80 env=env,
81 cwd=tmp_path / "cwd",
82 )
83
84 merged_env = mock_sub.tools.os.environ.copy()
85 merged_env.update(env)
86
87 mock_sub._subprocess.Popen.assert_called_with(
88 ["hello", "world"],
89 env=merged_env,
90 cwd=os.fsdecode(tmp_path / "cwd"),
91 **sub_stream_kw,
92 )
93 expected_output = (
94 "\n"
95 ">>> Running Command:\n"
96 ">>> hello world\n"
97 ">>> Working Directory:\n"
98 f">>> {tmp_path / 'cwd'}\n"
99 ">>> Environment Overrides:\n"
100 ">>> NewVar=NewVarValue\n"
101 "output line 1\n"
102 "\n"
103 "output line 3\n"
104 ">>> Return code: -3\n"
105 "\n"
106 )
107 assert capsys.readouterr().out == expected_output
108
109
110 @pytest.mark.parametrize(
111 ("in_kwargs", "kwargs"),
112 [
113 (
114 {},
115 {"text": True, "encoding": ANY, "bufsize": 1, "errors": "backslashreplace"},
116 ),
117 (
118 {"text": True},
119 {"text": True, "encoding": ANY, "bufsize": 1, "errors": "backslashreplace"},
120 ),
121 ({"text": False}, {"text": False, "bufsize": 1}),
122 ({"text": False, "bufsize": 42}, {"text": False, "bufsize": 42}),
123 ({"universal_newlines": False}, {"text": False, "bufsize": 1}),
124 (
125 {"universal_newlines": True},
126 {"text": True, "encoding": ANY, "bufsize": 1, "errors": "backslashreplace"},
127 ),
128 ],
129 )
130 def test_text_eq_true_default_overriding(mock_sub, in_kwargs, kwargs, sleep_zero):
131 """If text or universal_newlines is explicitly provided, those should override
132 text=true default and universal_newlines should be converted to text."""
133 with mock_sub.tools.console.wait_bar():
134 mock_sub.run(["hello", "world"], **in_kwargs)
135
136 mock_sub._subprocess.Popen.assert_called_with(
137 ["hello", "world"],
138 stdout=subprocess.PIPE,
139 stderr=subprocess.STDOUT,
140 **kwargs,
141 )
142
143
144 def test_stderr_is_redirected(
145 mock_sub,
146 streaming_process,
147 sub_stream_kw,
148 sleep_zero,
149 capsys,
150 ):
151 """When stderr is redirected, it should be included in the result."""
152 stderr_output = "stderr output\nline 2"
153 streaming_process.stderr.read.return_value = stderr_output
154
155 with mock_sub.tools.console.wait_bar():
156 run_result = mock_sub.run(
157 ["hello", "world"],
158 stderr=subprocess.PIPE,
159 )
160
161 sub_stream_kw.pop("stderr")
162 mock_sub._subprocess.Popen.assert_called_with(
163 ["hello", "world"],
164 stderr=subprocess.PIPE,
165 **sub_stream_kw,
166 )
167 # fmt: off
168 expected_output = (
169 "output line 1\n"
170 "\n"
171 "output line 3\n"
172 )
173 # fmt: on
174 assert capsys.readouterr().out == expected_output
175 assert run_result.stderr == stderr_output
176
177
178 def test_stderr_dev_null(
179 mock_sub,
180 streaming_process,
181 sub_stream_kw,
182 sleep_zero,
183 capsys,
184 ):
185 """When stderr is discarded, it should be None in the result."""
186 streaming_process.stderr = None
187
188 with mock_sub.tools.console.wait_bar():
189 run_result = mock_sub.run(
190 ["hello", "world"],
191 stderr=subprocess.DEVNULL,
192 )
193
194 sub_stream_kw.pop("stderr")
195 mock_sub._subprocess.Popen.assert_called_with(
196 ["hello", "world"],
197 stderr=subprocess.DEVNULL,
198 **sub_stream_kw,
199 )
200 # fmt: off
201 expected_output = (
202 "output line 1\n"
203 "\n"
204 "output line 3\n"
205 )
206 # fmt: on
207 assert capsys.readouterr().out == expected_output
208 assert run_result.stderr is None
209
210
211 def test_calledprocesserror(mock_sub, streaming_process, sleep_zero, capsys):
212 """CalledProcessError is raised with check=True and non-zero return value."""
213 stderr_output = "stderr output\nline 2"
214 streaming_process.stderr.read.return_value = stderr_output
215
216 with (
217 pytest.raises(subprocess.CalledProcessError) as exc,
218 mock_sub.tools.console.wait_bar(),
219 ):
220 mock_sub.run(
221 ["hello", "world"],
222 check=True,
223 stderr=subprocess.PIPE,
224 )
225
226 # fmt: off
227 expected_output = (
228 "output line 1\n"
229 "\n"
230 "output line 3\n"
231 )
232 # fmt: on
233 assert capsys.readouterr().out == expected_output
234 assert exc.value.returncode == -3
235 assert exc.value.cmd == ["hello", "world"]
236 assert exc.value.stderr == stderr_output
237
238
239 def test_invalid_invocations(mock_sub):
240 """Ensure run cannot be used in a Wait Bar with invalid arguments."""
241 with pytest.raises(AssertionError), mock_sub.tools.console.wait_bar():
242 mock_sub.run(
243 ["hello", "world"],
244 stdout=subprocess.PIPE,
245 )
246
247 for invalid_arg in ("timeout", "input"):
248 with pytest.raises(AssertionError), mock_sub.tools.console.wait_bar():
249 mock_sub.run(["hello", "world"], **{invalid_arg: "value"})