-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathtest_action.py
More file actions
240 lines (191 loc) · 8.16 KB
/
test_action.py
File metadata and controls
240 lines (191 loc) · 8.16 KB
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
236
237
238
239
240
from pathlib import Path
from subprocess import TimeoutExpired
import pytest
from unittest.mock import Mock, patch, call, ANY
from tests.installer import CommandFailed, AbortAction, InstallerError
@pytest.mark.unit
def test_exec_with_log(action, args_mock, analytics_mock, execute_mock):
action.execute_with_log(args_mock)
execute_mock.assert_called_once_with(args_mock)
@pytest.mark.unit
@pytest.mark.parametrize(
"exec_exc,expected_exc,print_msg",
(
(AbortAction(), AbortAction, False),
(InstallerError(), InstallerError, True),
(RuntimeError(), InstallerError, True),
(KeyboardInterrupt(), InstallerError, False),
),
)
def test_exec_with_log_raises(exec_exc, expected_exc, print_msg, action, args_mock, analytics_mock, execute_mock):
execute_mock.side_effect = exec_exc
with patch.object(action, "_msg_unexpected_error") as uncauhgt_msg_mock:
with pytest.raises(expected_exc) as exc_info:
action.execute_with_log(args_mock)
execute_mock.assert_called_once_with(args_mock)
assert exec_exc in (exc_info.value, exc_info.value.__cause__)
assert uncauhgt_msg_mock.call_args_list == ([call(exec_exc)] if print_msg else [])
@pytest.mark.unit
@pytest.mark.parametrize(
"exc_levels, glob_side_effect, expected_calls, expected_return",
(
(0, ([], [Path("stdout.txt")]), ("stderr", "stdout"), (ANY, Path("stdout.txt"))),
(
1,
([Path("stderr.txt"), Path("stderr_2.txt")], [Path("stdout.txt")]),
("stderr", "stdout"),
(ANY, Path("stdout.txt")),
),
(5, ([Path("stderr.txt")], [Path("stdout.txt")]), ("stderr",), (ANY, Path("stderr.txt"))),
(3, ([], [Path("stdout.txt"), Path("stdout.txt")]), ("stderr", "stdout"), (None, None)),
(1, ([], []), ("stderr", "stdout"), (None, None)),
),
ids=(
"direct exception, stdout only",
"one layer deep, two stderr files",
"five layers deep, stderr is picked",
"three layers deep, two stdout",
"one layers deep, no files",
),
)
def test_get_failed_cmd_log(action, exc_levels, glob_side_effect, expected_calls, expected_return):
cmd_failed_exc = CommandFailed(42, "cmd 42", 2)
exc = cmd_failed_exc
for n in range(exc_levels):
outer_exc = RuntimeError(str(n + 1))
outer_exc.__cause__ = exc
exc = outer_exc
action.session_folder.glob.side_effect = glob_side_effect
ret = action._get_failed_cmd_log_file_path(exc)
assert ret == expected_return
assert ret[0] in (None, cmd_failed_exc)
action.session_folder.glob.assert_has_calls([call(f"0042-{stream}-*.txt") for stream in expected_calls])
@pytest.mark.unit
def test_run_cmd_text(action, start_cmd_mock, stdout_mock, console_msg_mock):
stdout_mock.return_value = ["hi there"]
result = action.run_cmd("cmd", capture_text=True)
assert result == "hi there"
console_msg_mock.assert_not_called()
start_cmd_mock.assert_called_once()
@pytest.mark.unit
def test_run_cmd_json(action, start_cmd_mock, stdout_mock):
stdout_mock.return_value = ['{"foo": 123}']
result = action.run_cmd("cmd", capture_json=True)
assert result == {"foo": 123}
start_cmd_mock.assert_called_once()
@pytest.mark.unit
def test_run_cmd_invalid_json(action, start_cmd_mock, stdout_mock):
stdout_mock.return_value = ["no JSON here"]
result = action.run_cmd("cmd", capture_json=True)
assert result == {}
start_cmd_mock.assert_called_once()
@pytest.mark.unit
def test_run_cmd_json_lines(action, start_cmd_mock, stdout_mock):
stdout_mock.return_value = ['{"foo": 123}', "something else", '{"foo": 321}']
result = action.run_cmd("cmd", capture_json_lines=True)
assert result == [{"foo": 123}, {"foo": 321}]
start_cmd_mock.assert_called_once()
@pytest.mark.unit
def test_run_cmd_echo(action, start_cmd_mock, stdout_mock, console_msg_mock):
stdout_mock.return_value = ["some output", "will be echoed"]
result = action.run_cmd("cmd", echo=True)
assert result is None
assert console_msg_mock.call_count == 2
assert console_msg_mock.call_args_list[0].args[0] == "some output"
assert console_msg_mock.call_args_list[1].args[0] == "will be echoed"
start_cmd_mock.assert_called_once()
@pytest.mark.unit
def test_run_cmd_retries(action, start_cmd_mock, proc_mock):
start_cmd_mock.__exit__.side_effect = [CommandFailed, None, CommandFailed, None, None]
proc_mock.wait.side_effect = [None, TimeoutExpired(Mock(), 5), None, None, None]
action.run_cmd_retries("cmd", timeout=5, retries=5)
assert start_cmd_mock.call_count == 4
assert proc_mock.wait.call_count == 4
start_cmd_mock.assert_called_with("cmd", env=None, raise_on_non_zero=True)
proc_mock.kill.assert_called_once_with()
proc_mock.wait.assert_called_with(timeout=5)
@pytest.mark.unit
def test_run_cmd_retries_raises(action, start_cmd_mock, proc_mock):
start_cmd_mock.__exit__.side_effect = CommandFailed
with pytest.raises(CommandFailed):
action.run_cmd_retries("cmd", timeout=5, retries=10)
assert start_cmd_mock.call_count == 10
proc_mock.kill.assert_not_called()
proc_mock.wait.assert_called_with(timeout=5)
@pytest.mark.unit
def test_start_cmd(action, popen_mock, stream_iter_mock):
with action.start_cmd("cmd", "arg", env={"var": "val"}, popen_extra=True, raise_on_non_zero=False) as (
proc_mock,
stdout_mock,
stderr_mock,
):
proc_mock.returncode = 55
stream_iter_mock.assert_has_calls(
[
call(popen_mock(), "stdout", action.session_folder.joinpath()),
call(popen_mock(), "stderr", action.session_folder.joinpath()),
call().__enter__(),
call().__enter__(),
call().__exit__(None, None, None),
call().__exit__(None, None, None),
],
any_order=True,
)
assert proc_mock.wait.call_count == 1
assert popen_mock.call_args_list[0].kwargs["env"]["var"] == "val"
assert popen_mock.call_args_list[0].kwargs["popen_extra"] is True
@pytest.mark.unit
def test_start_cmd_raises_non_zero(action, popen_mock, proc_mock, stream_iter_mock):
proc_mock.returncode = 143
with pytest.raises(CommandFailed) as exc_info:
with action.start_cmd("cmd", "arg"):
pass
assert exc_info.value.idx == 1
assert exc_info.value.cmd == "cmd arg"
assert exc_info.value.ret_code == 143
@pytest.mark.unit
def test_start_cmd_file_not_found(action, popen_mock, stream_iter_mock):
popen_mock.side_effect = FileNotFoundError
with pytest.raises(CommandFailed) as exc_info:
with action.start_cmd("cmd", "arg"):
assert False, "this should not be reachable"
assert exc_info.value.idx == 1
assert exc_info.value.cmd == "cmd arg"
assert exc_info.value.ret_code is None
@pytest.mark.unit
def test_start_cmd_enhance_command_failed(action, popen_mock, proc_mock, stream_iter_mock):
with pytest.raises(CommandFailed) as exc_info:
with action.start_cmd("cmd", "arg"):
raise CommandFailed
assert proc_mock.wait.call_count == 1
assert exc_info.value.idx == 1
assert exc_info.value.cmd == "cmd arg"
assert exc_info.value.ret_code == 0
@pytest.mark.unit
def test_start_cmd_wait_on_exception(action, popen_mock, stream_iter_mock):
with pytest.raises(RuntimeError) as exc_info:
with action.start_cmd("cmd", "arg") as (proc_mock, _, _):
proc_mock.returncode = 0
raise RuntimeError("something went wrong")
assert proc_mock.wait.call_count == 1
assert exc_info.value.args == ("something went wrong",)
@pytest.mark.unit
@pytest.mark.parametrize("raise_", (True, False))
def test_start_cmd_calls_wait_after_streams_consumed(raise_, action, popen_mock):
try:
with action.start_cmd("cmd", "arg") as (proc_mock, _, _):
proc_mock.returncode = 0
if raise_:
raise RuntimeError()
except RuntimeError:
did_raise = True
else:
did_raise = False
assert did_raise == raise_
proc_mock.assert_has_calls(
[
call.communicate(timeout=1.0),
call.communicate(timeout=1.0),
call.wait(),
]
)