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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
|
import copy
import os
import pathlib
import sys
from unittest import mock
import pytest
import procrunner
@mock.patch("procrunner._NonBlockingStreamReader")
@mock.patch("procrunner.time")
@mock.patch("procrunner.subprocess")
@mock.patch("procrunner.Pipe")
def test_run_command_aborts_after_timeout_legacy(
mock_pipe, mock_subprocess, mock_time, mock_streamreader
):
mock_pipe.return_value = mock.Mock(), mock.Mock()
mock_process = mock.Mock()
mock_process.returncode = None
mock_subprocess.Popen.return_value = mock_process
task = ["___"]
with pytest.raises(RuntimeError):
with pytest.warns(DeprecationWarning, match="timeout"):
procrunner.run(task, timeout=-1, debug=False)
assert mock_subprocess.Popen.called
assert mock_process.terminate.called
assert mock_process.kill.called
@mock.patch("procrunner._NonBlockingStreamReader")
@mock.patch("procrunner.time")
@mock.patch("procrunner.subprocess")
@mock.patch("procrunner.Pipe")
def test_run_command_aborts_after_timeout(
mock_pipe, mock_subprocess, mock_time, mock_streamreader
):
mock_pipe.return_value = mock.Mock(), mock.Mock()
mock_process = mock.Mock()
mock_process.returncode = None
mock_subprocess.Popen.return_value = mock_process
task = ["___"]
with pytest.raises(RuntimeError):
procrunner.run(task, timeout=-1, raise_timeout_exception=True)
assert mock_subprocess.Popen.called
assert mock_process.terminate.called
assert mock_process.kill.called
@mock.patch("procrunner._NonBlockingStreamReader")
@mock.patch("procrunner.subprocess")
def test_run_command_runs_command_and_directs_pipelines(
mock_subprocess, mock_streamreader
):
(mock_stdout, mock_stderr) = (mock.Mock(), mock.Mock())
mock_stdout.get_output.return_value = mock.sentinel.proc_stdout
mock_stderr.get_output.return_value = mock.sentinel.proc_stderr
(stream_stdout, stream_stderr) = (mock.sentinel.stdout, mock.sentinel.stderr)
mock_process = mock.Mock()
mock_process.stdout = stream_stdout
mock_process.stderr = stream_stderr
mock_process.returncode = 99
command = ["___"]
def streamreader_processing(*args, **kwargs):
return {(stream_stdout,): mock_stdout, (stream_stderr,): mock_stderr}[args]
mock_streamreader.side_effect = streamreader_processing
mock_subprocess.Popen.return_value = mock_process
expected = {
"stderr": mock.sentinel.proc_stderr,
"stdout": mock.sentinel.proc_stdout,
"exitcode": mock_process.returncode,
"command": tuple(command),
"runtime": mock.ANY,
"timeout": False,
"time_start": mock.ANY,
"time_end": mock.ANY,
}
actual = procrunner.run(
command,
timeout=0.5,
callback_stdout=mock.sentinel.callback_stdout,
callback_stderr=mock.sentinel.callback_stderr,
working_directory=pathlib.Path("somecwd"),
raise_timeout_exception=True,
)
assert mock_subprocess.Popen.called
assert mock_subprocess.Popen.call_args[1]["env"] == os.environ
assert mock_subprocess.Popen.call_args[1]["cwd"] in (
pathlib.Path("somecwd"),
"somecwd",
)
mock_streamreader.assert_has_calls(
[
mock.call(
stream_stdout,
output=mock.ANY,
debug=None,
notify=mock.ANY,
callback=mock.sentinel.callback_stdout,
),
mock.call(
stream_stderr,
output=mock.ANY,
debug=None,
notify=mock.ANY,
callback=mock.sentinel.callback_stderr,
),
],
any_order=True,
)
assert not mock_process.terminate.called
assert not mock_process.kill.called
for key in expected:
with pytest.warns(DeprecationWarning):
assert actual[key] == expected[key]
assert actual.args == tuple(command)
assert actual.returncode == mock_process.returncode
assert actual.stdout == mock.sentinel.proc_stdout
assert actual.stderr == mock.sentinel.proc_stderr
@mock.patch("procrunner.subprocess")
def test_default_process_environment_is_parent_environment(mock_subprocess):
mock_subprocess.Popen.side_effect = NotImplementedError() # cut calls short
with pytest.raises(NotImplementedError):
procrunner.run([mock.Mock()], timeout=-1, raise_timeout_exception=True)
assert mock_subprocess.Popen.call_args[1]["env"] == os.environ
@mock.patch("procrunner.subprocess")
def test_using_debug_parameter_raises_warning(mock_subprocess):
mock_subprocess.Popen.side_effect = NotImplementedError() # cut calls short
with pytest.warns(DeprecationWarning, match="debug"):
with pytest.raises(NotImplementedError):
procrunner.run([mock.Mock()], debug=True)
with pytest.warns(DeprecationWarning, match="debug"):
with pytest.raises(NotImplementedError):
procrunner.run([mock.Mock()], debug=False)
@mock.patch("procrunner.subprocess")
def test_pass_custom_environment_to_process(mock_subprocess):
mock_subprocess.Popen.side_effect = NotImplementedError() # cut calls short
mock_env = {"key": mock.sentinel.key}
# Pass an environment dictionary
with pytest.raises(NotImplementedError):
procrunner.run(
[mock.Mock()],
timeout=-1,
environment=copy.copy(mock_env),
raise_timeout_exception=True,
)
assert mock_subprocess.Popen.call_args[1]["env"] == mock_env
@mock.patch("procrunner.subprocess")
def test_pass_custom_environment_to_process_and_add_another_value(mock_subprocess):
mock_subprocess.Popen.side_effect = NotImplementedError() # cut calls short
mock_env1 = {"keyA": mock.sentinel.keyA}
mock_env2 = {"keyB": mock.sentinel.keyB, "number": 5}
# Pass an environment dictionary
with pytest.raises(NotImplementedError):
procrunner.run(
[mock.Mock()],
timeout=-1,
environment=copy.copy(mock_env1),
environment_override=copy.copy(mock_env2),
raise_timeout_exception=True,
)
mock_env_sum = copy.copy(mock_env1)
mock_env_sum.update({key: str(mock_env2[key]) for key in mock_env2})
assert mock_subprocess.Popen.call_args[1]["env"] == mock_env_sum
@mock.patch("procrunner.subprocess")
def test_use_default_process_environment_and_add_another_value(mock_subprocess):
mock_subprocess.Popen.side_effect = NotImplementedError() # cut calls short
mock_env2 = {"keyB": str(mock.sentinel.keyB)}
with pytest.raises(NotImplementedError):
procrunner.run(
[mock.Mock()],
timeout=-1,
environment_override=copy.copy(mock_env2),
raise_timeout_exception=True,
)
random_environment_variable = list(os.environ)[0]
if random_environment_variable == list(mock_env2)[0]:
random_environment_variable = list(os.environ)[1]
assert (
random_environment_variable
and random_environment_variable != list(mock_env2)[0]
)
assert (
mock_subprocess.Popen.call_args[1]["env"][list(mock_env2)[0]]
== mock_env2[list(mock_env2)[0]]
)
assert mock_subprocess.Popen.call_args[1]["env"][
random_environment_variable
] == os.getenv(random_environment_variable)
@mock.patch("procrunner.subprocess")
def test_use_default_process_environment_and_override_a_value(mock_subprocess):
mock_subprocess.Popen.side_effect = NotImplementedError() # cut calls short
random_environment_variable = list(os.environ)[0]
random_environment_value = os.getenv(random_environment_variable)
with pytest.raises(NotImplementedError):
procrunner.run(
[mock.Mock()],
timeout=-1,
environment_override={
random_environment_variable: "X" + random_environment_value
},
raise_timeout_exception=True,
)
assert (
mock_subprocess.Popen.call_args[1]["env"][random_environment_variable]
== "X" + random_environment_value
)
@mock.patch("procrunner.select")
@pytest.mark.skipif(
sys.platform == "win32",
reason="test only relevant on platforms supporting select()",
)
def test_nonblockingstreamreader_can_read(mock_select):
import time
class _stream:
def __init__(self):
self.data = b""
self.closed = False
def write(self, string):
self.data = self.data + string
def read(self, n):
if self.closed:
return b""
if self.data == b"":
time.sleep(0.01)
return b""
if len(self.data) < n:
data = self.data
self.data = b""
else:
data = self.data[:n]
self.data = self.data[n:]
return data
def close(self):
self.closed = True
teststream = _stream()
def select_replacement(rlist, wlist, xlist, timeout):
assert teststream in rlist
if teststream.closed:
return ([teststream], [], [])
if teststream.data == b"":
return ([], [], [])
return ([teststream], [], [])
mock_select.select = select_replacement
streamreader = procrunner._NonBlockingStreamReader(teststream, output=False)
assert not streamreader.has_finished()
time.sleep(0.1)
testdata = b"abc\n" * 1024
teststream.write(testdata)
time.sleep(0.2)
teststream.close()
time.sleep(0.1)
assert streamreader.has_finished()
output = streamreader.get_output()
assert len(output) == len(testdata)
assert output == testdata
def test_lineaggregator_aggregates_data():
callback = mock.Mock()
aggregator = procrunner._LineAggregator(callback=callback)
aggregator.add(b"some")
aggregator.add(b"string")
callback.assert_not_called()
aggregator.add(b"\n")
callback.assert_called_once_with("somestring")
callback.reset_mock()
aggregator.add(b"more")
aggregator.add(b"stuff")
callback.assert_not_called()
aggregator.flush()
callback.assert_called_once_with("morestuff")
def test_return_object_semantics():
ro = procrunner.ReturnObject(
command=mock.sentinel.command,
exitcode=0,
stdout=mock.sentinel.stdout,
stderr=mock.sentinel.stderr,
)
with pytest.warns(DeprecationWarning):
assert ro["command"] == mock.sentinel.command
assert ro.args == mock.sentinel.command
with pytest.warns(DeprecationWarning):
assert ro["exitcode"] == 0
assert ro.returncode == 0
with pytest.warns(DeprecationWarning):
assert ro["stdout"] == mock.sentinel.stdout
assert ro.stdout == mock.sentinel.stdout
with pytest.warns(DeprecationWarning):
assert ro["stderr"] == mock.sentinel.stderr
assert ro.stderr == mock.sentinel.stderr
with pytest.raises(KeyError):
with pytest.warns(DeprecationWarning):
ro["unknownkey"]
ro.update({"unknownkey": mock.sentinel.key})
with pytest.warns(DeprecationWarning):
assert ro["unknownkey"] == mock.sentinel.key
def test_return_object_check_function_passes_on_success():
ro = procrunner.ReturnObject(
command=mock.sentinel.command,
exitcode=0,
stdout=mock.sentinel.stdout,
stderr=mock.sentinel.stderr,
)
ro.check_returncode()
def test_return_object_check_function_raises_on_error():
ro = procrunner.ReturnObject(
command=mock.sentinel.command,
exitcode=1,
stdout=mock.sentinel.stdout,
stderr=mock.sentinel.stderr,
)
with pytest.raises(Exception) as e:
ro.check_returncode()
assert repr(mock.sentinel.command) in str(e.value)
assert "1" in str(e.value)
|