| 1 |
import errno |
| 2 |
import os |
| 3 |
import signal |
| 4 |
import struct |
| 5 |
import sys |
| 6 |
import termios |
| 7 |
import threading |
| 8 |
import types |
| 9 |
from contextlib import AbstractContextManager |
| 10 |
from io import BytesIO, StringIO |
| 11 |
from itertools import chain, repeat |
| 12 |
from unittest.mock import Mock, call, patch |
| 13 |
|
| 14 |
from _util import ( |
| 15 |
OhNoz, |
| 16 |
_, |
| 17 |
_Dummy, |
| 18 |
_KeyboardInterruptingRunner, |
| 19 |
mock_pty, |
| 20 |
mock_subprocess, |
| 21 |
skip_if_windows, |
| 22 |
) |
| 23 |
from pytest import raises, skip |
| 24 |
from pytest_relaxed import trap |
| 25 |
|
| 26 |
from invoke import ( |
| 27 |
CommandTimedOut, |
| 28 |
Config, |
| 29 |
Context, |
| 30 |
Failure, |
| 31 |
Local, |
| 32 |
Promise, |
| 33 |
Responder, |
| 34 |
Result, |
| 35 |
Runner, |
| 36 |
StreamWatcher, |
| 37 |
SubprocessPipeError, |
| 38 |
ThreadException, |
| 39 |
UnexpectedExit, |
| 40 |
WatcherError, |
| 41 |
) |
| 42 |
from invoke.runners import default_encoding |
| 43 |
from invoke.terminals import WINDOWS |
| 44 |
|
| 45 |
|
| 46 |
class _RaisingWatcher(StreamWatcher): |
| 47 |
def submit(self, stream): |
| 48 |
raise WatcherError("meh") |
| 49 |
|
| 50 |
|
| 51 |
class _GenericException(Exception): |
| 52 |
pass |
| 53 |
|
| 54 |
|
| 55 |
class _GenericExceptingRunner(_Dummy): |
| 56 |
def wait(self): |
| 57 |
raise _GenericException |
| 58 |
|
| 59 |
|
| 60 |
def _run(*args, **kwargs): |
| 61 |
klass = kwargs.pop("klass", _Dummy) |
| 62 |
settings = kwargs.pop("settings", {}) |
| 63 |
context = Context(config=Config(overrides=settings)) |
| 64 |
return klass(context).run(*args, **kwargs) |
| 65 |
|
| 66 |
|
| 67 |
def _runner(out="", err="", **kwargs): |
| 68 |
klass = kwargs.pop("klass", _Dummy) |
| 69 |
runner = klass(Context(config=Config(overrides=kwargs))) |
| 70 |
if "exits" in kwargs: |
| 71 |
runner.returncode = Mock(return_value=kwargs.pop("exits")) |
| 72 |
out_file = BytesIO(out.encode()) |
| 73 |
err_file = BytesIO(err.encode()) |
| 74 |
runner.read_proc_stdout = out_file.read |
| 75 |
runner.read_proc_stderr = err_file.read |
| 76 |
return runner |
| 77 |
|
| 78 |
|
| 79 |
def _expect_platform_shell(shell): |
| 80 |
if WINDOWS: |
| 81 |
assert shell.endswith("cmd.exe") |
| 82 |
else: |
| 83 |
assert shell == "bash" |
| 84 |
|
| 85 |
|
| 86 |
def _make_tcattrs(cc_is_ints=True, echo=False): |
| 87 |
# Set up the control character sub-array; it's technically platform |
| 88 |
# dependent so we need to be dynamic. |
| 89 |
# NOTE: setting this up so we can test both potential values for |
| 90 |
# the 'cc' members...docs say ints, reality says one-byte |
| 91 |
# bytestrings... |
| 92 |
cc_base = [None] * (max(termios.VMIN, termios.VTIME) + 1) |
| 93 |
cc_ints, cc_bytes = cc_base.copy(), cc_base.copy() |
| 94 |
cc_ints[termios.VMIN], cc_ints[termios.VTIME] = 1, 0 |
| 95 |
cc_bytes[termios.VMIN], cc_bytes[termios.VTIME] = b"\x01", b"\x00" |
| 96 |
# Set tcgetattr to look like it's already cbroken... |
| 97 |
attrs = [ |
| 98 |
# iflag, oflag, cflag - don't care |
| 99 |
None, |
| 100 |
None, |
| 101 |
None, |
| 102 |
# lflag needs to have ECHO and ICANON unset |
| 103 |
~(termios.ECHO | termios.ICANON), |
| 104 |
# ispeed, ospeed - don't care |
| 105 |
None, |
| 106 |
None, |
| 107 |
# cc - care about its VMIN and VTIME members. |
| 108 |
cc_ints if cc_is_ints else cc_bytes, |
| 109 |
] |
| 110 |
# Undo the ECHO unset if caller wants this to look like a non-cbroken term |
| 111 |
if echo: |
| 112 |
attrs[3] = attrs[3] | termios.ECHO |
| 113 |
return attrs |
| 114 |
|
| 115 |
|
| 116 |
class _TimingOutRunner(_Dummy): |
| 117 |
@property |
| 118 |
def timed_out(self): |
| 119 |
return True |
| 120 |
|
| 121 |
|
| 122 |
_async_skipped_methods = ["generate_result", "stop"] |
| 123 |
_disown_skipped_methods = ["wait", "stop"] |
| 124 |
|
| 125 |
|
| 126 |
class Runner_: |
| 127 |
# NOTE: these copies of _run and _runner form the base case of "test Runner |
| 128 |
# subclasses via self._run/_runner helpers" functionality. See how e.g. |
| 129 |
# Local_ uses the same approach but bakes in the dummy class used. |
| 130 |
def _run(self, *args, **kwargs): |
| 131 |
return _run(*args, **kwargs) |
| 132 |
|
| 133 |
def _runner(self, *args, **kwargs): |
| 134 |
return _runner(*args, **kwargs) |
| 135 |
|
| 136 |
def _mock_stdin_writer(self): |
| 137 |
""" |
| 138 |
Return new _Dummy subclass whose write_proc_stdin() method is a mock. |
| 139 |
""" |
| 140 |
|
| 141 |
class MockedStdin(_Dummy): |
| 142 |
pass |
| 143 |
|
| 144 |
MockedStdin.write_proc_stdin = Mock() |
| 145 |
return MockedStdin |
| 146 |
|
| 147 |
class init: |
| 148 |
"__init__" |
| 149 |
|
| 150 |
def takes_a_context_instance(self): |
| 151 |
c = Context() |
| 152 |
assert Runner(c).context == c |
| 153 |
|
| 154 |
def context_instance_is_required(self): |
| 155 |
with raises(TypeError): |
| 156 |
Runner() |
| 157 |
|
| 158 |
class run: |
| 159 |
def handles_invalid_kwargs_like_any_other_function(self): |
| 160 |
try: |
| 161 |
self._run(_, nope_noway_nohow="as if") |
| 162 |
except TypeError as e: |
| 163 |
assert "got an unexpected keyword argument" in str(e) |
| 164 |
else: |
| 165 |
assert False, "Invalid run() kwarg didn't raise TypeError" |
| 166 |
|
| 167 |
class warn: |
| 168 |
def honors_config(self): |
| 169 |
runner = self._runner(run={"warn": True}, exits=1) |
| 170 |
# Doesn't raise Failure -> all good |
| 171 |
runner.run(_) |
| 172 |
|
| 173 |
def kwarg_beats_config(self): |
| 174 |
runner = self._runner(run={"warn": False}, exits=1) |
| 175 |
# Doesn't raise Failure -> all good |
| 176 |
runner.run(_, warn=True) |
| 177 |
|
| 178 |
def does_not_apply_to_watcher_errors(self): |
| 179 |
runner = self._runner(out="stuff") |
| 180 |
try: |
| 181 |
watcher = _RaisingWatcher() |
| 182 |
runner.run(_, watchers=[watcher], warn=True, hide=True) |
| 183 |
except Failure as e: |
| 184 |
assert isinstance(e.reason, WatcherError) |
| 185 |
else: |
| 186 |
assert False, "Did not raise Failure for WatcherError!" |
| 187 |
|
| 188 |
def does_not_apply_to_timeout_errors(self): |
| 189 |
with raises(CommandTimedOut): |
| 190 |
self._runner(klass=_TimingOutRunner).run( |
| 191 |
_, timeout=1, warn=True |
| 192 |
) |
| 193 |
|
| 194 |
class hide: |
| 195 |
@trap |
| 196 |
def honors_config(self): |
| 197 |
runner = self._runner(out="stuff", run={"hide": True}) |
| 198 |
r = runner.run(_) |
| 199 |
assert r.stdout == "stuff" |
| 200 |
assert sys.stdout.getvalue() == "" |
| 201 |
|
| 202 |
@trap |
| 203 |
def kwarg_beats_config(self): |
| 204 |
runner = self._runner(out="stuff") |
| 205 |
r = runner.run(_, hide=True) |
| 206 |
assert r.stdout == "stuff" |
| 207 |
assert sys.stdout.getvalue() == "" |
| 208 |
|
| 209 |
class pty: |
| 210 |
def pty_defaults_to_off(self): |
| 211 |
assert self._run(_).pty is False |
| 212 |
|
| 213 |
def honors_config(self): |
| 214 |
runner = self._runner(run={"pty": True}) |
| 215 |
assert runner.run(_).pty is True |
| 216 |
|
| 217 |
def kwarg_beats_config(self): |
| 218 |
runner = self._runner(run={"pty": False}) |
| 219 |
assert runner.run(_, pty=True).pty is True |
| 220 |
|
| 221 |
class shell: |
| 222 |
def defaults_to_bash_or_cmdexe_when_pty_True(self): |
| 223 |
_expect_platform_shell(self._run(_, pty=True).shell) |
| 224 |
|
| 225 |
def defaults_to_bash_or_cmdexe_when_pty_False(self): |
| 226 |
_expect_platform_shell(self._run(_, pty=False).shell) |
| 227 |
|
| 228 |
def may_be_overridden(self): |
| 229 |
assert self._run(_, shell="/bin/zsh").shell == "/bin/zsh" |
| 230 |
|
| 231 |
def may_be_configured(self): |
| 232 |
runner = self._runner(run={"shell": "/bin/tcsh"}) |
| 233 |
assert runner.run(_).shell == "/bin/tcsh" |
| 234 |
|
| 235 |
def kwarg_beats_config(self): |
| 236 |
runner = self._runner(run={"shell": "/bin/tcsh"}) |
| 237 |
assert runner.run(_, shell="/bin/zsh").shell == "/bin/zsh" |
| 238 |
|
| 239 |
class env: |
| 240 |
def defaults_to_os_environ(self): |
| 241 |
assert self._run(_).env == os.environ |
| 242 |
|
| 243 |
def updates_when_dict_given(self): |
| 244 |
expected = dict(os.environ, FOO="BAR") |
| 245 |
assert self._run(_, env={"FOO": "BAR"}).env == expected |
| 246 |
|
| 247 |
def replaces_when_replace_env_True(self): |
| 248 |
env = self._run(_, env={"JUST": "ME"}, replace_env=True).env |
| 249 |
assert env == {"JUST": "ME"} |
| 250 |
|
| 251 |
def config_can_be_used(self): |
| 252 |
env = self._run(_, settings={"run": {"env": {"FOO": "BAR"}}}).env |
| 253 |
assert env == dict(os.environ, FOO="BAR") |
| 254 |
|
| 255 |
def kwarg_wins_over_config(self): |
| 256 |
settings = {"run": {"env": {"FOO": "BAR"}}} |
| 257 |
kwarg = {"FOO": "NOTBAR"} |
| 258 |
foo = self._run(_, settings=settings, env=kwarg).env["FOO"] |
| 259 |
assert foo == "NOTBAR" |
| 260 |
|
| 261 |
class return_value: |
| 262 |
def return_code(self): |
| 263 |
""" |
| 264 |
Result has .return_code (and .exited) containing exit code int |
| 265 |
""" |
| 266 |
runner = self._runner(exits=17) |
| 267 |
r = runner.run(_, warn=True) |
| 268 |
assert r.return_code == 17 |
| 269 |
assert r.exited == 17 |
| 270 |
|
| 271 |
def ok_attr_indicates_success(self): |
| 272 |
runner = self._runner() |
| 273 |
assert runner.run(_).ok is True # default dummy retval is 0 |
| 274 |
|
| 275 |
def ok_attr_indicates_failure(self): |
| 276 |
runner = self._runner(exits=1) |
| 277 |
assert runner.run(_, warn=True).ok is False |
| 278 |
|
| 279 |
def failed_attr_indicates_success(self): |
| 280 |
runner = self._runner() |
| 281 |
assert runner.run(_).failed is False # default dummy retval is 0 |
| 282 |
|
| 283 |
def failed_attr_indicates_failure(self): |
| 284 |
runner = self._runner(exits=1) |
| 285 |
assert runner.run(_, warn=True).failed is True |
| 286 |
|
| 287 |
@trap |
| 288 |
def stdout_attribute_contains_stdout(self): |
| 289 |
runner = self._runner(out="foo") |
| 290 |
assert runner.run(_).stdout == "foo" |
| 291 |
assert sys.stdout.getvalue() == "foo" |
| 292 |
|
| 293 |
@trap |
| 294 |
def stderr_attribute_contains_stderr(self): |
| 295 |
runner = self._runner(err="foo") |
| 296 |
assert runner.run(_).stderr == "foo" |
| 297 |
assert sys.stderr.getvalue() == "foo" |
| 298 |
|
| 299 |
def whether_pty_was_used(self): |
| 300 |
assert self._run(_).pty is False |
| 301 |
assert self._run(_, pty=True).pty is True |
| 302 |
|
| 303 |
def command_executed(self): |
| 304 |
assert self._run(_).command == _ |
| 305 |
|
| 306 |
def shell_used(self): |
| 307 |
_expect_platform_shell(self._run(_).shell) |
| 308 |
|
| 309 |
def hide_param_exposed_and_normalized(self): |
| 310 |
assert self._run(_, hide=True).hide, "stdout" == "stderr" |
| 311 |
assert self._run(_, hide=False).hide == tuple() |
| 312 |
assert self._run(_, hide="stderr").hide == ("stderr",) |
| 313 |
|
| 314 |
class command_echoing: |
| 315 |
@trap |
| 316 |
def off_by_default(self): |
| 317 |
self._run("my command") |
| 318 |
assert sys.stdout.getvalue() == "" |
| 319 |
|
| 320 |
@trap |
| 321 |
def enabled_via_kwarg(self): |
| 322 |
self._run("my command", echo=True) |
| 323 |
assert "my command" in sys.stdout.getvalue() |
| 324 |
|
| 325 |
@trap |
| 326 |
def enabled_via_config(self): |
| 327 |
self._run("yup", settings={"run": {"echo": True}}) |
| 328 |
assert "yup" in sys.stdout.getvalue() |
| 329 |
|
| 330 |
@trap |
| 331 |
def kwarg_beats_config(self): |
| 332 |
self._run("yup", echo=True, settings={"run": {"echo": False}}) |
| 333 |
assert "yup" in sys.stdout.getvalue() |
| 334 |
|
| 335 |
@trap |
| 336 |
def uses_ansi_bold(self): |
| 337 |
self._run("my command", echo=True) |
| 338 |
# TODO: vendor & use a color module |
| 339 |
assert sys.stdout.getvalue() == "\x1b[1;37mmy command\x1b[0m\n" |
| 340 |
|
| 341 |
@trap |
| 342 |
def uses_custom_format(self): |
| 343 |
self._run( |
| 344 |
"my command", |
| 345 |
echo=True, |
| 346 |
settings={"run": {"echo_format": "AA{command}ZZ"}}, |
| 347 |
) |
| 348 |
assert sys.stdout.getvalue() == "AAmy commandZZ\n" |
| 349 |
|
| 350 |
class dry_running: |
| 351 |
@trap |
| 352 |
def sets_echo_to_True(self): |
| 353 |
self._run("what up", settings={"run": {"dry": True}}) |
| 354 |
assert "what up" in sys.stdout.getvalue() |
| 355 |
|
| 356 |
@trap |
| 357 |
def short_circuits_with_dummy_result(self): |
| 358 |
runner = self._runner(run={"dry": True}) |
| 359 |
# Using the call to self.start() in _run_body() as a sentinel for |
| 360 |
# all the work beyond it. |
| 361 |
runner.start = Mock() |
| 362 |
result = runner.run(_) |
| 363 |
assert not runner.start.called |
| 364 |
assert isinstance(result, Result) |
| 365 |
assert result.command == _ |
| 366 |
assert result.stdout == "" |
| 367 |
assert result.stderr == "" |
| 368 |
assert result.exited == 0 |
| 369 |
assert result.pty is False |
| 370 |
|
| 371 |
class encoding: |
| 372 |
# NOTE: these tests just check what Runner.encoding ends up as; it's |
| 373 |
# difficult/impossible to mock string objects themselves to see what |
| 374 |
# .decode() is being given :( |
| 375 |
# |
| 376 |
# TODO: consider using truly "nonstandard"-encoded byte sequences as |
| 377 |
# fixtures, encoded with something that isn't compatible with UTF-8 |
| 378 |
# (UTF-7 kinda is, so...) so we can assert that the decoded string is |
| 379 |
# equal to its Unicode equivalent. |
| 380 |
# |
| 381 |
# Use UTF-7 as a valid encoding unlikely to be a real default derived |
| 382 |
# from test-runner's locale.getpreferredencoding() |
| 383 |
def defaults_to_encoding_method_result(self): |
| 384 |
# Setup |
| 385 |
runner = self._runner() |
| 386 |
encoding = "UTF-7" |
| 387 |
runner.default_encoding = Mock(return_value=encoding) |
| 388 |
# Execution & assertion |
| 389 |
runner.run(_) |
| 390 |
runner.default_encoding.assert_called_with() |
| 391 |
assert runner.encoding == "UTF-7" |
| 392 |
|
| 393 |
def honors_config(self): |
| 394 |
c = Context(Config(overrides={"run": {"encoding": "UTF-7"}})) |
| 395 |
runner = _Dummy(c) |
| 396 |
runner.default_encoding = Mock(return_value="UTF-not-7") |
| 397 |
runner.run(_) |
| 398 |
assert runner.encoding == "UTF-7" |
| 399 |
|
| 400 |
def honors_kwarg(self): |
| 401 |
skip() |
| 402 |
|
| 403 |
def uses_locale_module_for_default_encoding(self): |
| 404 |
# Actually testing this highly OS/env specific stuff is very |
| 405 |
# error-prone; so we degrade to just testing expected function |
| 406 |
# calls for now :( |
| 407 |
with patch("invoke.runners.locale") as fake_locale: |
| 408 |
fake_locale.getdefaultlocale.return_value = ("meh", "UHF-8") |
| 409 |
fake_locale.getpreferredencoding.return_value = "FALLBACK" |
| 410 |
assert self._runner().default_encoding() == "FALLBACK" |
| 411 |
|
| 412 |
def falls_back_to_defaultlocale_when_preferredencoding_is_None(self): |
| 413 |
with patch("invoke.runners.locale") as fake_locale: |
| 414 |
fake_locale.getdefaultlocale.return_value = (None, None) |
| 415 |
fake_locale.getpreferredencoding.return_value = "FALLBACK" |
| 416 |
assert self._runner().default_encoding() == "FALLBACK" |
| 417 |
|
| 418 |
class output_hiding: |
| 419 |
@trap |
| 420 |
def _expect_hidden(self, hide, expect_out="", expect_err=""): |
| 421 |
self._runner(out="foo", err="bar").run(_, hide=hide) |
| 422 |
assert sys.stdout.getvalue() == expect_out |
| 423 |
assert sys.stderr.getvalue() == expect_err |
| 424 |
|
| 425 |
def both_hides_everything(self): |
| 426 |
self._expect_hidden("both") |
| 427 |
|
| 428 |
def True_hides_everything(self): |
| 429 |
self._expect_hidden(True) |
| 430 |
|
| 431 |
def out_only_hides_stdout(self): |
| 432 |
self._expect_hidden("out", expect_out="", expect_err="bar") |
| 433 |
|
| 434 |
def err_only_hides_stderr(self): |
| 435 |
self._expect_hidden("err", expect_out="foo", expect_err="") |
| 436 |
|
| 437 |
def accepts_stdout_alias_for_out(self): |
| 438 |
self._expect_hidden("stdout", expect_out="", expect_err="bar") |
| 439 |
|
| 440 |
def accepts_stderr_alias_for_err(self): |
| 441 |
self._expect_hidden("stderr", expect_out="foo", expect_err="") |
| 442 |
|
| 443 |
def None_hides_nothing(self): |
| 444 |
self._expect_hidden(None, expect_out="foo", expect_err="bar") |
| 445 |
|
| 446 |
def False_hides_nothing(self): |
| 447 |
self._expect_hidden(False, expect_out="foo", expect_err="bar") |
| 448 |
|
| 449 |
def unknown_vals_raises_ValueError(self): |
| 450 |
with raises(ValueError): |
| 451 |
self._run(_, hide="wat?") |
| 452 |
|
| 453 |
def unknown_vals_mention_value_given_in_error(self): |
| 454 |
value = "penguinmints" |
| 455 |
try: |
| 456 |
self._run(_, hide=value) |
| 457 |
except ValueError as e: |
| 458 |
msg = "Error from run(hide=xxx) did not tell user what the bad value was!" # noqa |
| 459 |
msg += "\nException msg: {}".format(e) |
| 460 |
assert value in str(e), msg |
| 461 |
else: |
| 462 |
assert ( |
| 463 |
False |
| 464 |
), "run() did not raise ValueError for bad hide= value" # noqa |
| 465 |
|
| 466 |
def does_not_affect_capturing(self): |
| 467 |
assert self._runner(out="foo").run(_, hide=True).stdout == "foo" |
| 468 |
|
| 469 |
@trap |
| 470 |
def overrides_echoing(self): |
| 471 |
self._runner().run("invisible", hide=True, echo=True) |
| 472 |
assert "invisible" not in sys.stdout.getvalue() |
| 473 |
|
| 474 |
class output_stream_overrides: |
| 475 |
@trap |
| 476 |
def out_defaults_to_sys_stdout(self): |
| 477 |
"out_stream defaults to sys.stdout" |
| 478 |
self._runner(out="sup").run(_) |
| 479 |
assert sys.stdout.getvalue() == "sup" |
| 480 |
|
| 481 |
@trap |
| 482 |
def err_defaults_to_sys_stderr(self): |
| 483 |
"err_stream defaults to sys.stderr" |
| 484 |
self._runner(err="sup").run(_) |
| 485 |
assert sys.stderr.getvalue() == "sup" |
| 486 |
|
| 487 |
@trap |
| 488 |
def out_can_be_overridden(self): |
| 489 |
"out_stream can be overridden" |
| 490 |
out = StringIO() |
| 491 |
self._runner(out="sup").run(_, out_stream=out) |
| 492 |
assert out.getvalue() == "sup" |
| 493 |
assert sys.stdout.getvalue() == "" |
| 494 |
|
| 495 |
@trap |
| 496 |
def overridden_out_is_never_hidden(self): |
| 497 |
out = StringIO() |
| 498 |
self._runner(out="sup").run(_, out_stream=out, hide=True) |
| 499 |
assert out.getvalue() == "sup" |
| 500 |
assert sys.stdout.getvalue() == "" |
| 501 |
|
| 502 |
@trap |
| 503 |
def err_can_be_overridden(self): |
| 504 |
"err_stream can be overridden" |
| 505 |
err = StringIO() |
| 506 |
self._runner(err="sup").run(_, err_stream=err) |
| 507 |
assert err.getvalue() == "sup" |
| 508 |
assert sys.stderr.getvalue() == "" |
| 509 |
|
| 510 |
@trap |
| 511 |
def overridden_err_is_never_hidden(self): |
| 512 |
err = StringIO() |
| 513 |
self._runner(err="sup").run(_, err_stream=err, hide=True) |
| 514 |
assert err.getvalue() == "sup" |
| 515 |
assert sys.stderr.getvalue() == "" |
| 516 |
|
| 517 |
@trap |
| 518 |
def pty_defaults_to_sys(self): |
| 519 |
self._runner(out="sup").run(_, pty=True) |
| 520 |
assert sys.stdout.getvalue() == "sup" |
| 521 |
|
| 522 |
@trap |
| 523 |
def pty_out_can_be_overridden(self): |
| 524 |
out = StringIO() |
| 525 |
self._runner(out="yo").run(_, pty=True, out_stream=out) |
| 526 |
assert out.getvalue() == "yo" |
| 527 |
assert sys.stdout.getvalue() == "" |
| 528 |
|
| 529 |
class output_stream_handling: |
| 530 |
# Mostly corner cases, generic behavior's covered above |
| 531 |
def writes_and_flushes_to_stdout(self): |
| 532 |
out = Mock(spec=StringIO) |
| 533 |
self._runner(out="meh").run(_, out_stream=out) |
| 534 |
out.write.assert_called_once_with("meh") |
| 535 |
out.flush.assert_called_once_with() |
| 536 |
|
| 537 |
def writes_and_flushes_to_stderr(self): |
| 538 |
err = Mock(spec=StringIO) |
| 539 |
self._runner(err="whatever").run(_, err_stream=err) |
| 540 |
err.write.assert_called_once_with("whatever") |
| 541 |
err.flush.assert_called_once_with() |
| 542 |
|
| 543 |
class input_stream_handling: |
| 544 |
# NOTE: actual autoresponder tests are elsewhere. These just test that |
| 545 |
# stdin works normally & can be overridden. |
| 546 |
@patch("invoke.runners.sys.stdin", StringIO("Text!")) |
| 547 |
def defaults_to_sys_stdin(self): |
| 548 |
# Execute w/ runner class that has a mocked stdin_writer |
| 549 |
klass = self._mock_stdin_writer() |
| 550 |
self._runner(klass=klass).run(_, out_stream=StringIO()) |
| 551 |
# Check that mocked writer was called w/ the data from our patched |
| 552 |
# sys.stdin. |
| 553 |
# NOTE: this also tests that non-fileno-bearing streams read/write |
| 554 |
# 1 byte at a time. See farther-down test for fileno-bearing stdin |
| 555 |
calls = list(map(lambda x: call(x), "Text!")) |
| 556 |
klass.write_proc_stdin.assert_has_calls(calls, any_order=False) |
| 557 |
|
| 558 |
def can_be_overridden(self): |
| 559 |
klass = self._mock_stdin_writer() |
| 560 |
in_stream = StringIO("Hey, listen!") |
| 561 |
self._runner(klass=klass).run( |
| 562 |
_, in_stream=in_stream, out_stream=StringIO() |
| 563 |
) |
| 564 |
# stdin mirroring occurs char-by-char |
| 565 |
calls = list(map(lambda x: call(x), "Hey, listen!")) |
| 566 |
klass.write_proc_stdin.assert_has_calls(calls, any_order=False) |
| 567 |
|
| 568 |
def can_be_disabled_entirely(self): |
| 569 |
# Mock handle_stdin so we can assert it's not even called |
| 570 |
class MockedHandleStdin(_Dummy): |
| 571 |
pass |
| 572 |
|
| 573 |
MockedHandleStdin.handle_stdin = Mock() |
| 574 |
self._runner(klass=MockedHandleStdin).run( |
| 575 |
_, |
| 576 |
in_stream=False, # vs None or a stream |
| 577 |
) |
| 578 |
assert not MockedHandleStdin.handle_stdin.called |
| 579 |
|
| 580 |
@patch("invoke.util.debug") |
| 581 |
def exceptions_get_logged(self, mock_debug): |
| 582 |
# Make write_proc_stdin asplode |
| 583 |
klass = self._mock_stdin_writer() |
| 584 |
klass.write_proc_stdin.side_effect = OhNoz("oh god why") |
| 585 |
# Execute with some stdin to trigger that asplode (but skip the |
| 586 |
# actual bubbled-up raising of it so we can check things out) |
| 587 |
try: |
| 588 |
stdin = StringIO("non-empty") |
| 589 |
self._runner(klass=klass).run(_, in_stream=stdin) |
| 590 |
except ThreadException: |
| 591 |
pass |
| 592 |
# Assert debug() was called w/ expected format |
| 593 |
# TODO: make the debug call a method on ExceptionHandlingThread, |
| 594 |
# then make thread class configurable somewhere in Runner, and pass |
| 595 |
# in a customized ExceptionHandlingThread that has a Mock for that |
| 596 |
# method? |
| 597 |
# NOTE: splitting into a few asserts to work around python 3.7 |
| 598 |
# change re: trailing comma, which kills ability to just statically |
| 599 |
# assert the entire string. Sigh. Also I'm too lazy to regex. |
| 600 |
msg = mock_debug.call_args[0][0] |
| 601 |
assert "Encountered exception OhNoz" in msg |
| 602 |
assert "'oh god why'" in msg |
| 603 |
assert "in thread for 'handle_stdin'" in msg |
| 604 |
|
| 605 |
def EOF_triggers_closing_of_proc_stdin(self): |
| 606 |
class Fake(_Dummy): |
| 607 |
pass |
| 608 |
|
| 609 |
Fake.close_proc_stdin = Mock() |
| 610 |
self._runner(klass=Fake).run(_, in_stream=StringIO("what?")) |
| 611 |
Fake.close_proc_stdin.assert_called_once_with() |
| 612 |
|
| 613 |
def EOF_does_not_close_proc_stdin_when_pty_True(self): |
| 614 |
class Fake(_Dummy): |
| 615 |
pass |
| 616 |
|
| 617 |
Fake.close_proc_stdin = Mock() |
| 618 |
self._runner(klass=Fake).run( |
| 619 |
_, in_stream=StringIO("what?"), pty=True |
| 620 |
) |
| 621 |
assert not Fake.close_proc_stdin.called |
| 622 |
|
| 623 |
@patch("invoke.runners.sys.stdin") |
| 624 |
def EBADF_on_stdin_read_ignored(self, fake_stdin): |
| 625 |
# Issue #659: nohup is a jerk |
| 626 |
fake_stdin.read.side_effect = OSError(errno.EBADF, "Ugh") |
| 627 |
# No boom == fixed |
| 628 |
self._runner().run(_) |
| 629 |
|
| 630 |
@patch("invoke.runners.sys.stdin") |
| 631 |
def non_EBADF_on_stdin_read_not_ignored(self, fake_stdin): |
| 632 |
# Issue #659: nohup is a jerk, inverse case |
| 633 |
eio = OSError(errno.EIO, "lol") |
| 634 |
fake_stdin.read.side_effect = eio |
| 635 |
with raises(ThreadException) as info: |
| 636 |
self._runner().run(_) |
| 637 |
assert info.value.exceptions[0].value is eio |
| 638 |
|
| 639 |
class failure_handling: |
| 640 |
def fast_failures(self): |
| 641 |
with raises(UnexpectedExit): |
| 642 |
self._runner(exits=1).run(_) |
| 643 |
|
| 644 |
def non_1_return_codes_still_act_as_failure(self): |
| 645 |
r = self._runner(exits=17).run(_, warn=True) |
| 646 |
assert r.failed is True |
| 647 |
|
| 648 |
class Failure_repr: |
| 649 |
def defaults_to_just_class_and_command(self): |
| 650 |
expected = "<Failure: cmd='oh hecc'>" |
| 651 |
assert repr(Failure(Result(command="oh hecc"))) == expected |
| 652 |
|
| 653 |
def subclasses_may_add_more_kv_pairs(self): |
| 654 |
class TotalFailure(Failure): |
| 655 |
def _repr(self, **kwargs): |
| 656 |
return super()._repr(mood="dejected") |
| 657 |
|
| 658 |
expected = "<TotalFailure: cmd='onoz' mood=dejected>" |
| 659 |
assert repr(TotalFailure(Result(command="onoz"))) == expected |
| 660 |
|
| 661 |
class UnexpectedExit_repr: |
| 662 |
def similar_to_just_the_result_repr(self): |
| 663 |
try: |
| 664 |
self._runner(exits=23).run(_) |
| 665 |
except UnexpectedExit as e: |
| 666 |
expected = "<UnexpectedExit: cmd='{}' exited=23>" |
| 667 |
assert repr(e) == expected.format(_) |
| 668 |
|
| 669 |
class UnexpectedExit_str: |
| 670 |
def setup_method(self): |
| 671 |
def lines(prefix): |
| 672 |
prefixed = "\n".join( |
| 673 |
"{} {}".format(prefix, x) for x in range(1, 26) |
| 674 |
) |
| 675 |
return prefixed + "\n" |
| 676 |
|
| 677 |
self._stdout = lines("stdout") |
| 678 |
self._stderr = lines("stderr") |
| 679 |
|
| 680 |
@trap |
| 681 |
def displays_command_and_exit_code_by_default(self): |
| 682 |
try: |
| 683 |
self._runner( |
| 684 |
exits=23, out=self._stdout, err=self._stderr |
| 685 |
).run(_) |
| 686 |
except UnexpectedExit as e: |
| 687 |
expected = """Encountered a bad command exit code! |
| 688 |
|
| 689 |
Command: '{}' |
| 690 |
|
| 691 |
Exit code: 23 |
| 692 |
|
| 693 |
Stdout: already printed |
| 694 |
|
| 695 |
Stderr: already printed |
| 696 |
|
| 697 |
""" |
| 698 |
assert str(e) == expected.format(_) |
| 699 |
else: |
| 700 |
assert False, "Failed to raise UnexpectedExit!" |
| 701 |
|
| 702 |
@trap |
| 703 |
def does_not_display_stderr_when_pty_True(self): |
| 704 |
try: |
| 705 |
self._runner( |
| 706 |
exits=13, out=self._stdout, err=self._stderr |
| 707 |
).run(_, pty=True) |
| 708 |
except UnexpectedExit as e: |
| 709 |
expected = """Encountered a bad command exit code! |
| 710 |
|
| 711 |
Command: '{}' |
| 712 |
|
| 713 |
Exit code: 13 |
| 714 |
|
| 715 |
Stdout: already printed |
| 716 |
|
| 717 |
Stderr: n/a (PTYs have no stderr) |
| 718 |
|
| 719 |
""" |
| 720 |
assert str(e) == expected.format(_) |
| 721 |
|
| 722 |
@trap |
| 723 |
def pty_stderr_message_wins_over_hidden_stderr(self): |
| 724 |
try: |
| 725 |
self._runner( |
| 726 |
exits=1, out=self._stdout, err=self._stderr |
| 727 |
).run(_, pty=True, hide=True) |
| 728 |
except UnexpectedExit as e: |
| 729 |
r = str(e) |
| 730 |
assert "Stderr: n/a (PTYs have no stderr)" in r |
| 731 |
assert "Stderr: already printed" not in r |
| 732 |
|
| 733 |
@trap |
| 734 |
def explicit_hidden_stream_tail_display(self): |
| 735 |
# All the permutations of what's displayed when, are in |
| 736 |
# subsequent test, which does 'x in y' assertions; this one |
| 737 |
# here ensures the actual format of the display (newlines, etc) |
| 738 |
# is as desired. |
| 739 |
try: |
| 740 |
self._runner( |
| 741 |
exits=77, out=self._stdout, err=self._stderr |
| 742 |
).run(_, hide=True) |
| 743 |
except UnexpectedExit as e: |
| 744 |
expected = """Encountered a bad command exit code! |
| 745 |
|
| 746 |
Command: '{}' |
| 747 |
|
| 748 |
Exit code: 77 |
| 749 |
|
| 750 |
Stdout: |
| 751 |
|
| 752 |
stdout 16 |
| 753 |
stdout 17 |
| 754 |
stdout 18 |
| 755 |
stdout 19 |
| 756 |
stdout 20 |
| 757 |
stdout 21 |
| 758 |
stdout 22 |
| 759 |
stdout 23 |
| 760 |
stdout 24 |
| 761 |
stdout 25 |
| 762 |
|
| 763 |
Stderr: |
| 764 |
|
| 765 |
stderr 16 |
| 766 |
stderr 17 |
| 767 |
stderr 18 |
| 768 |
stderr 19 |
| 769 |
stderr 20 |
| 770 |
stderr 21 |
| 771 |
stderr 22 |
| 772 |
stderr 23 |
| 773 |
stderr 24 |
| 774 |
stderr 25 |
| 775 |
|
| 776 |
""" |
| 777 |
assert str(e) == expected.format(_) |
| 778 |
|
| 779 |
@trap |
| 780 |
def displays_tails_of_streams_only_when_hidden(self): |
| 781 |
def oops(msg, r, hide): |
| 782 |
return "{}! hide={}; str output:\n\n{}".format( |
| 783 |
msg, hide, r |
| 784 |
) |
| 785 |
|
| 786 |
for hide, expect_out, expect_err in ( |
| 787 |
(False, False, False), |
| 788 |
(True, True, True), |
| 789 |
("stdout", True, False), |
| 790 |
("stderr", False, True), |
| 791 |
("both", True, True), |
| 792 |
): |
| 793 |
try: |
| 794 |
self._runner( |
| 795 |
exits=1, out=self._stdout, err=self._stderr |
| 796 |
).run(_, hide=hide) |
| 797 |
except UnexpectedExit as e: |
| 798 |
r = str(e) |
| 799 |
# Expect that the top of output is never displayed |
| 800 |
err = oops("Too much stdout found", r, hide) |
| 801 |
assert "stdout 15" not in r, err |
| 802 |
err = oops("Too much stderr found", r, hide) |
| 803 |
assert "stderr 15" not in r, err |
| 804 |
# Expect to see tail of stdout if we expected it |
| 805 |
if expect_out: |
| 806 |
err = oops("Didn't see stdout", r, hide) |
| 807 |
assert "stdout 16" in r, err |
| 808 |
# Expect to see tail of stderr if we expected it |
| 809 |
if expect_err: |
| 810 |
err = oops("Didn't see stderr", r, hide) |
| 811 |
assert "stderr 16" in r, err |
| 812 |
else: |
| 813 |
assert False, "Failed to raise UnexpectedExit!" |
| 814 |
|
| 815 |
def _regular_error(self): |
| 816 |
self._runner(exits=1).run(_) |
| 817 |
|
| 818 |
def _watcher_error(self): |
| 819 |
klass = self._mock_stdin_writer() |
| 820 |
# Exited=None because real procs will have no useful .returncode() |
| 821 |
# result if they're aborted partway via an exception. |
| 822 |
runner = self._runner(klass=klass, out="stuff", exits=None) |
| 823 |
runner.run(_, watchers=[_RaisingWatcher()], hide=True) |
| 824 |
|
| 825 |
# TODO: may eventually turn into having Runner raise distinct Failure |
| 826 |
# subclasses itself, at which point `reason` would probably go away. |
| 827 |
class reason: |
| 828 |
def is_None_for_regular_nonzero_exits(self): |
| 829 |
try: |
| 830 |
self._regular_error() |
| 831 |
except Failure as e: |
| 832 |
assert e.reason is None |
| 833 |
else: |
| 834 |
assert False, "Failed to raise Failure!" |
| 835 |
|
| 836 |
def is_None_for_custom_command_exits(self): |
| 837 |
# TODO: when we implement 'exitcodes 1 and 2 are actually OK' |
| 838 |
skip() |
| 839 |
|
| 840 |
def is_exception_when_WatcherError_raised_internally(self): |
| 841 |
try: |
| 842 |
self._watcher_error() |
| 843 |
except Failure as e: |
| 844 |
assert isinstance(e.reason, WatcherError) |
| 845 |
else: |
| 846 |
assert False, "Failed to raise Failure!" |
| 847 |
|
| 848 |
# TODO: should these move elsewhere, eg to Result specific test file? |
| 849 |
# TODO: *is* there a nice way to split into multiple Response and/or |
| 850 |
# Failure subclasses? Given the split between "returned as a value when |
| 851 |
# no problem" and "raised as/attached to an exception when problem", |
| 852 |
# possibly not - complicates how the APIs need to be adhered to. |
| 853 |
class wrapped_result: |
| 854 |
def most_attrs_are_always_present(self): |
| 855 |
attrs = ("command", "shell", "env", "stdout", "stderr", "pty") |
| 856 |
for method in (self._regular_error, self._watcher_error): |
| 857 |
try: |
| 858 |
method() |
| 859 |
except Failure as e: |
| 860 |
for attr in attrs: |
| 861 |
assert getattr(e.result, attr) is not None |
| 862 |
else: |
| 863 |
assert False, "Did not raise Failure!" |
| 864 |
|
| 865 |
class shell_exit_failure: |
| 866 |
def exited_is_integer(self): |
| 867 |
try: |
| 868 |
self._regular_error() |
| 869 |
except Failure as e: |
| 870 |
assert isinstance(e.result.exited, int) |
| 871 |
else: |
| 872 |
assert False, "Did not raise Failure!" |
| 873 |
|
| 874 |
def ok_bool_etc_are_falsey(self): |
| 875 |
try: |
| 876 |
self._regular_error() |
| 877 |
except Failure as e: |
| 878 |
assert e.result.ok is False |
| 879 |
assert e.result.failed is True |
| 880 |
assert not bool(e.result) |
| 881 |
assert not e.result |
| 882 |
else: |
| 883 |
assert False, "Did not raise Failure!" |
| 884 |
|
| 885 |
def stringrep_notes_exit_status(self): |
| 886 |
try: |
| 887 |
self._regular_error() |
| 888 |
except Failure as e: |
| 889 |
assert "exited with status 1" in str(e.result) |
| 890 |
else: |
| 891 |
assert False, "Did not raise Failure!" |
| 892 |
|
| 893 |
class watcher_failure: |
| 894 |
def exited_is_None(self): |
| 895 |
try: |
| 896 |
self._watcher_error() |
| 897 |
except Failure as e: |
| 898 |
exited = e.result.exited |
| 899 |
err = "Expected None, got {!r}".format(exited) |
| 900 |
assert exited is None, err |
| 901 |
|
| 902 |
def ok_and_bool_still_are_falsey(self): |
| 903 |
try: |
| 904 |
self._watcher_error() |
| 905 |
except Failure as e: |
| 906 |
assert e.result.ok is False |
| 907 |
assert e.result.failed is True |
| 908 |
assert not bool(e.result) |
| 909 |
assert not e.result |
| 910 |
else: |
| 911 |
assert False, "Did not raise Failure!" |
| 912 |
|
| 913 |
def stringrep_lacks_exit_status(self): |
| 914 |
try: |
| 915 |
self._watcher_error() |
| 916 |
except Failure as e: |
| 917 |
assert "exited with status" not in str(e.result) |
| 918 |
expected = "not fully executed due to watcher error" |
| 919 |
assert expected in str(e.result) |
| 920 |
else: |
| 921 |
assert False, "Did not raise Failure!" |
| 922 |
|
| 923 |
class threading: |
| 924 |
# NOTE: see also the more generic tests in concurrency.py |
| 925 |
def errors_within_io_thread_body_bubble_up(self): |
| 926 |
class Oops(_Dummy): |
| 927 |
def handle_stdout(self, **kwargs): |
| 928 |
raise OhNoz() |
| 929 |
|
| 930 |
def handle_stderr(self, **kwargs): |
| 931 |
raise OhNoz() |
| 932 |
|
| 933 |
runner = Oops(Context()) |
| 934 |
try: |
| 935 |
runner.run("nah") |
| 936 |
except ThreadException as e: |
| 937 |
# Expect two separate OhNoz objects on 'e' |
| 938 |
assert len(e.exceptions) == 2 |
| 939 |
for tup in e.exceptions: |
| 940 |
assert isinstance(tup.value, OhNoz) |
| 941 |
assert isinstance(tup.traceback, types.TracebackType) |
| 942 |
assert tup.type == OhNoz |
| 943 |
# TODO: test the arguments part of the tuple too. It's pretty |
| 944 |
# implementation-specific, though, so possibly not worthwhile. |
| 945 |
else: |
| 946 |
assert False, "Did not raise ThreadException as expected!" |
| 947 |
|
| 948 |
def io_thread_errors_str_has_details(self): |
| 949 |
class Oops(_Dummy): |
| 950 |
def handle_stdout(self, **kwargs): |
| 951 |
raise OhNoz() |
| 952 |
|
| 953 |
runner = Oops(Context()) |
| 954 |
try: |
| 955 |
runner.run("nah") |
| 956 |
except ThreadException as e: |
| 957 |
message = str(e) |
| 958 |
# Just make sure salient bits appear present, vs e.g. default |
| 959 |
# representation happening instead. |
| 960 |
assert "Saw 1 exceptions within threads" in message |
| 961 |
assert "{'kwargs': " in message |
| 962 |
assert "Traceback (most recent call last):\n\n" in message |
| 963 |
assert "OhNoz" in message |
| 964 |
else: |
| 965 |
assert False, "Did not raise ThreadException as expected!" |
| 966 |
|
| 967 |
class watchers: |
| 968 |
# NOTE: it's initially tempting to consider using mocks or stub |
| 969 |
# Responder instances for many of these, but it really doesn't save |
| 970 |
# appreciable runtime or code read/write time. |
| 971 |
# NOTE: these strictly test interactions between |
| 972 |
# StreamWatcher/Responder and their host Runner; Responder-only tests |
| 973 |
# are in tests/watchers.py. |
| 974 |
|
| 975 |
def nothing_is_written_to_stdin_by_default(self): |
| 976 |
# NOTE: technically if some goofus ran the tests by hand and mashed |
| 977 |
# keys while doing so...this would fail. LOL? |
| 978 |
# NOTE: this test seems not too useful but is a) a sanity test and |
| 979 |
# b) guards against e.g. breaking the autoresponder such that it |
| 980 |
# responds to "" or "\n" or etc. |
| 981 |
klass = self._mock_stdin_writer() |
| 982 |
self._runner(klass=klass).run(_) |
| 983 |
assert not klass.write_proc_stdin.called |
| 984 |
|
| 985 |
def _expect_response(self, **kwargs): |
| 986 |
""" |
| 987 |
Execute a run() w/ ``watchers`` set from ``responses``. |
| 988 |
|
| 989 |
Any other ``**kwargs`` given are passed direct to ``_runner()``. |
| 990 |
|
| 991 |
:returns: The mocked ``write_proc_stdin`` method of the runner. |
| 992 |
""" |
| 993 |
watchers = [ |
| 994 |
Responder(pattern=key, response=value) |
| 995 |
for key, value in kwargs.pop("responses").items() |
| 996 |
] |
| 997 |
kwargs["klass"] = klass = self._mock_stdin_writer() |
| 998 |
runner = self._runner(**kwargs) |
| 999 |
runner.run(_, watchers=watchers, hide=True) |
| 1000 |
return klass.write_proc_stdin |
| 1001 |
|
| 1002 |
def watchers_responses_get_written_to_proc_stdin(self): |
| 1003 |
self._expect_response( |
| 1004 |
out="the house was empty", responses={"empty": "handed"} |
| 1005 |
).assert_called_once_with("handed") |
| 1006 |
|
| 1007 |
def multiple_hits_yields_multiple_responses(self): |
| 1008 |
holla = call("how high?") |
| 1009 |
self._expect_response( |
| 1010 |
out="jump, wait, jump, wait", responses={"jump": "how high?"} |
| 1011 |
).assert_has_calls([holla, holla]) |
| 1012 |
|
| 1013 |
def chunk_sizes_smaller_than_patterns_still_work_ok(self): |
| 1014 |
klass = self._mock_stdin_writer() |
| 1015 |
klass.read_chunk_size = 1 # < len('jump') |
| 1016 |
responder = Responder("jump", "how high?") |
| 1017 |
runner = self._runner(klass=klass, out="jump, wait, jump, wait") |
| 1018 |
runner.run(_, watchers=[responder], hide=True) |
| 1019 |
holla = call("how high?") |
| 1020 |
# Responses happened, period. |
| 1021 |
klass.write_proc_stdin.assert_has_calls([holla, holla]) |
| 1022 |
# And there weren't duplicates! |
| 1023 |
assert len(klass.write_proc_stdin.call_args_list) == 2 |
| 1024 |
|
| 1025 |
def both_out_and_err_are_scanned(self): |
| 1026 |
bye = call("goodbye") |
| 1027 |
# Would only be one 'bye' if only scanning stdout |
| 1028 |
self._expect_response( |
| 1029 |
out="hello my name is inigo", |
| 1030 |
err="hello how are you", |
| 1031 |
responses={"hello": "goodbye"}, |
| 1032 |
).assert_has_calls([bye, bye]) |
| 1033 |
|
| 1034 |
def multiple_patterns_works_as_expected(self): |
| 1035 |
calls = [call("betty"), call("carnival")] |
| 1036 |
self._expect_response( |
| 1037 |
out="beep boop I am a robot", |
| 1038 |
responses={"boop": "betty", "robot": "carnival"}, |
| 1039 |
).assert_has_calls(calls, any_order=True) |
| 1040 |
|
| 1041 |
def multiple_patterns_across_both_streams(self): |
| 1042 |
responses = { |
| 1043 |
"boop": "betty", |
| 1044 |
"robot": "carnival", |
| 1045 |
"Destroy": "your ego", |
| 1046 |
"humans": "are awful", |
| 1047 |
} |
| 1048 |
calls = map(lambda x: call(x), responses.values()) |
| 1049 |
# CANNOT assume order due to simultaneous streams. |
| 1050 |
# If we didn't say any_order=True we could get race condition fails |
| 1051 |
self._expect_response( |
| 1052 |
out="beep boop, I am a robot", |
| 1053 |
err="Destroy all humans!", |
| 1054 |
responses=responses, |
| 1055 |
).assert_has_calls(calls, any_order=True) |
| 1056 |
|
| 1057 |
def honors_watchers_config_option(self): |
| 1058 |
klass = self._mock_stdin_writer() |
| 1059 |
responder = Responder("my stdout", "and my axe") |
| 1060 |
runner = self._runner( |
| 1061 |
out="this is my stdout", # yielded stdout |
| 1062 |
klass=klass, # mocked stdin writer |
| 1063 |
run={"watchers": [responder]}, # ends up as config override |
| 1064 |
) |
| 1065 |
runner.run(_, hide=True) |
| 1066 |
klass.write_proc_stdin.assert_called_once_with("and my axe") |
| 1067 |
|
| 1068 |
def kwarg_overrides_config(self): |
| 1069 |
# TODO: how to handle use cases where merging, not overriding, is |
| 1070 |
# the expected/unsurprising default? probably another config-only |
| 1071 |
# (not kwarg) setting, e.g. run.merge_responses? |
| 1072 |
# TODO: now that this stuff is list, not dict, based, it should be |
| 1073 |
# easier...BUT how to handle removal of defaults from config? Maybe |
| 1074 |
# just document to be careful using the config as it won't _be_ |
| 1075 |
# overridden? (Users can always explicitly set the config to be |
| 1076 |
# empty-list if they want kwargs to be the entire set of |
| 1077 |
# watchers...right?) |
| 1078 |
klass = self._mock_stdin_writer() |
| 1079 |
conf = Responder("my stdout", "and my axe") |
| 1080 |
kwarg = Responder("my stdout", "and my body spray") |
| 1081 |
runner = self._runner( |
| 1082 |
out="this is my stdout", # yielded stdout |
| 1083 |
klass=klass, # mocked stdin writer |
| 1084 |
run={"watchers": [conf]}, # ends up as config override |
| 1085 |
) |
| 1086 |
runner.run(_, hide=True, watchers=[kwarg]) |
| 1087 |
klass.write_proc_stdin.assert_called_once_with("and my body spray") |
| 1088 |
|
| 1089 |
class io_sleeping: |
| 1090 |
# NOTE: there's an explicit CPU-measuring test in the integration suite |
| 1091 |
# which ensures the *point* of the sleeping - avoiding CPU hogging - is |
| 1092 |
# actually functioning. These tests below just unit-test the mechanisms |
| 1093 |
# around the sleep functionality (ensuring they are visible and can be |
| 1094 |
# altered as needed). |
| 1095 |
def input_sleep_attribute_defaults_to_hundredth_of_second(self): |
| 1096 |
assert Runner(Context()).input_sleep == 0.01 |
| 1097 |
|
| 1098 |
@mock_subprocess() |
| 1099 |
def subclasses_can_override_input_sleep(self): |
| 1100 |
class MyRunner(_Dummy): |
| 1101 |
input_sleep = 0.007 |
| 1102 |
|
| 1103 |
with patch("invoke.runners.time") as mock_time: |
| 1104 |
MyRunner(Context()).run( |
| 1105 |
_, |
| 1106 |
in_stream=StringIO("foo"), |
| 1107 |
out_stream=StringIO(), # null output to not pollute tests |
| 1108 |
) |
| 1109 |
# Just make sure the first few sleeps all look good. Can't know |
| 1110 |
# exact length of list due to stdin worker hanging out til end of |
| 1111 |
# process. Still worth testing more than the first tho. |
| 1112 |
assert mock_time.sleep.call_args_list[:3] == [call(0.007)] * 3 |
| 1113 |
|
| 1114 |
class stdin_mirroring: |
| 1115 |
def _test_mirroring(self, expect_mirroring, **kwargs): |
| 1116 |
# Setup |
| 1117 |
fake_in = "I'm typing!" |
| 1118 |
output = Mock() |
| 1119 |
input_ = StringIO(fake_in) |
| 1120 |
input_is_pty = kwargs.pop("in_pty", None) |
| 1121 |
|
| 1122 |
class MyRunner(_Dummy): |
| 1123 |
def should_echo_stdin(self, input_, output): |
| 1124 |
# Fake result of isatty() test here and only here; if we do |
| 1125 |
# this farther up, it will affect stuff trying to run |
| 1126 |
# termios & such, which is harder to mock successfully. |
| 1127 |
if input_is_pty is not None: |
| 1128 |
input_.isatty = lambda: input_is_pty |
| 1129 |
return super().should_echo_stdin(input_, output) |
| 1130 |
|
| 1131 |
# Execute basic command with given parameters |
| 1132 |
self._run( |
| 1133 |
_, |
| 1134 |
klass=MyRunner, |
| 1135 |
in_stream=input_, |
| 1136 |
out_stream=output, |
| 1137 |
**kwargs, |
| 1138 |
) |
| 1139 |
# Examine mocked output stream to see if it was mirrored to |
| 1140 |
if expect_mirroring: |
| 1141 |
calls = output.write.call_args_list |
| 1142 |
assert calls == list(map(lambda x: call(x), fake_in)) |
| 1143 |
assert len(output.flush.call_args_list) == len(fake_in) |
| 1144 |
# Or not mirrored to |
| 1145 |
else: |
| 1146 |
assert output.write.call_args_list == [] |
| 1147 |
|
| 1148 |
def when_pty_is_True_no_mirroring_occurs(self): |
| 1149 |
self._test_mirroring(pty=True, expect_mirroring=False) |
| 1150 |
|
| 1151 |
def when_pty_is_False_we_write_in_stream_back_to_out_stream(self): |
| 1152 |
self._test_mirroring(pty=False, in_pty=True, expect_mirroring=True) |
| 1153 |
|
| 1154 |
def mirroring_is_skipped_when_our_input_is_not_a_tty(self): |
| 1155 |
self._test_mirroring(in_pty=False, expect_mirroring=False) |
| 1156 |
|
| 1157 |
def mirroring_can_be_forced_on(self): |
| 1158 |
self._test_mirroring( |
| 1159 |
# Subprocess pty normally disables echoing |
| 1160 |
pty=True, |
| 1161 |
# But then we forcibly enable it |
| 1162 |
echo_stdin=True, |
| 1163 |
# And expect it to happen |
| 1164 |
expect_mirroring=True, |
| 1165 |
) |
| 1166 |
|
| 1167 |
def mirroring_can_be_forced_off(self): |
| 1168 |
# Make subprocess pty False, stdin tty True, echo_stdin False, |
| 1169 |
# prove no mirroring |
| 1170 |
self._test_mirroring( |
| 1171 |
# Subprocess lack of pty normally enables echoing |
| 1172 |
pty=False, |
| 1173 |
# Provided the controlling terminal _is_ a tty |
| 1174 |
in_pty=True, |
| 1175 |
# But then we forcibly disable it |
| 1176 |
echo_stdin=False, |
| 1177 |
# And expect it to not happen |
| 1178 |
expect_mirroring=False, |
| 1179 |
) |
| 1180 |
|
| 1181 |
def mirroring_honors_configuration(self): |
| 1182 |
self._test_mirroring( |
| 1183 |
pty=False, |
| 1184 |
in_pty=True, |
| 1185 |
settings={"run": {"echo_stdin": False}}, |
| 1186 |
expect_mirroring=False, |
| 1187 |
) |
| 1188 |
|
| 1189 |
@trap |
| 1190 |
@skip_if_windows |
| 1191 |
@patch("invoke.runners.sys.stdin") |
| 1192 |
@patch("invoke.terminals.fcntl.ioctl") |
| 1193 |
@patch("invoke.terminals.os") |
| 1194 |
@patch("invoke.terminals.termios") |
| 1195 |
@patch("invoke.terminals.tty") |
| 1196 |
@patch("invoke.terminals.select") |
| 1197 |
# NOTE: the no-fileno edition is handled at top of this local test |
| 1198 |
# class, in the base case test. |
| 1199 |
def reads_FIONREAD_bytes_from_stdin_when_fileno( |
| 1200 |
self, select, tty, termios, mock_os, ioctl, stdin |
| 1201 |
): |
| 1202 |
# Set stdin up as a file-like buffer which passes has_fileno |
| 1203 |
stdin.fileno.return_value = 17 # arbitrary |
| 1204 |
stdin_data = list("boo!") |
| 1205 |
|
| 1206 |
def fakeread(n): |
| 1207 |
# Why is there no slice version of pop()? |
| 1208 |
data = stdin_data[:n] |
| 1209 |
del stdin_data[:n] |
| 1210 |
return "".join(data) |
| 1211 |
|
| 1212 |
stdin.read.side_effect = fakeread |
| 1213 |
# Without mocking this, we'll always get errors checking the above |
| 1214 |
# bogus fileno() |
| 1215 |
mock_os.tcgetpgrp.return_value = None |
| 1216 |
# Ensure select() only spits back stdin one time, despite there |
| 1217 |
# being multiple bytes to read (this at least partly fakes behavior |
| 1218 |
# from issue #58) |
| 1219 |
select.select.side_effect = chain( |
| 1220 |
[([stdin], [], [])], repeat(([], [], [])) |
| 1221 |
) |
| 1222 |
|
| 1223 |
# Have ioctl yield our multiple number of bytes when called with |
| 1224 |
# FIONREAD |
| 1225 |
def fake_ioctl(fd, cmd, buf): |
| 1226 |
# This works since each mocked attr will still be its own mock |
| 1227 |
# object with a distinct 'is' identity. |
| 1228 |
if cmd is termios.FIONREAD: |
| 1229 |
return struct.pack("h", len(stdin_data)) |
| 1230 |
|
| 1231 |
ioctl.side_effect = fake_ioctl |
| 1232 |
# Set up our runner as one w/ mocked stdin writing (simplest way to |
| 1233 |
# assert how the reads & writes are happening) |
| 1234 |
klass = self._mock_stdin_writer() |
| 1235 |
self._runner(klass=klass).run(_) |
| 1236 |
klass.write_proc_stdin.assert_called_once_with("boo!") |
| 1237 |
|
| 1238 |
class character_buffered_stdin: |
| 1239 |
@skip_if_windows |
| 1240 |
@patch("invoke.terminals.tty") |
| 1241 |
def setcbreak_called_on_tty_stdins(self, mock_tty, mock_termios): |
| 1242 |
mock_termios.tcgetattr.return_value = _make_tcattrs(echo=True) |
| 1243 |
self._run(_) |
| 1244 |
mock_tty.setcbreak.assert_called_with(sys.stdin) |
| 1245 |
|
| 1246 |
@skip_if_windows |
| 1247 |
@patch("invoke.terminals.tty") |
| 1248 |
def setcbreak_not_called_on_non_tty_stdins(self, mock_tty): |
| 1249 |
self._run(_, in_stream=StringIO()) |
| 1250 |
assert not mock_tty.setcbreak.called |
| 1251 |
|
| 1252 |
@skip_if_windows |
| 1253 |
@patch("invoke.terminals.tty") |
| 1254 |
@patch("invoke.terminals.os") |
| 1255 |
def setcbreak_not_called_if_process_not_foregrounded( |
| 1256 |
self, mock_os, mock_tty |
| 1257 |
): |
| 1258 |
# Re issue #439. |
| 1259 |
mock_os.getpgrp.return_value = 1337 |
| 1260 |
mock_os.tcgetpgrp.return_value = 1338 |
| 1261 |
self._run(_) |
| 1262 |
assert not mock_tty.setcbreak.called |
| 1263 |
# Sanity |
| 1264 |
mock_os.tcgetpgrp.assert_called_once_with(sys.stdin.fileno()) |
| 1265 |
|
| 1266 |
@skip_if_windows |
| 1267 |
@patch("invoke.terminals.tty") |
| 1268 |
def tty_stdins_have_settings_restored_by_default( |
| 1269 |
self, mock_tty, mock_termios |
| 1270 |
): |
| 1271 |
# Get already-cbroken attrs since that's an easy way to get the |
| 1272 |
# right format/layout |
| 1273 |
attrs = _make_tcattrs(echo=True) |
| 1274 |
mock_termios.tcgetattr.return_value = attrs |
| 1275 |
self._run(_) |
| 1276 |
# Ensure those old settings are being restored |
| 1277 |
mock_termios.tcsetattr.assert_called_once_with( |
| 1278 |
sys.stdin, mock_termios.TCSADRAIN, attrs |
| 1279 |
) |
| 1280 |
|
| 1281 |
@skip_if_windows |
| 1282 |
@patch("invoke.terminals.tty") # stub |
| 1283 |
def tty_stdins_have_settings_restored_on_KeyboardInterrupt( |
| 1284 |
self, mock_tty, mock_termios |
| 1285 |
): |
| 1286 |
# This test is re: GH issue #303 |
| 1287 |
sentinel = _make_tcattrs(echo=True) |
| 1288 |
mock_termios.tcgetattr.return_value = sentinel |
| 1289 |
# Don't actually bubble up the KeyboardInterrupt... |
| 1290 |
try: |
| 1291 |
self._run(_, klass=_KeyboardInterruptingRunner) |
| 1292 |
except KeyboardInterrupt: |
| 1293 |
pass |
| 1294 |
# Did we restore settings?! |
| 1295 |
mock_termios.tcsetattr.assert_called_once_with( |
| 1296 |
sys.stdin, mock_termios.TCSADRAIN, sentinel |
| 1297 |
) |
| 1298 |
|
| 1299 |
@skip_if_windows |
| 1300 |
@patch("invoke.terminals.tty") |
| 1301 |
def setcbreak_not_called_if_terminal_seems_already_cbroken( |
| 1302 |
self, mock_tty, mock_termios |
| 1303 |
): |
| 1304 |
# Proves #559, sorta, insofar as it only passes when the fixed |
| 1305 |
# behavior is in place. (Proving the old bug is hard as it is race |
| 1306 |
# condition reliant; the new behavior sidesteps that entirely.) |
| 1307 |
|
| 1308 |
# Test both bytes and ints versions of CC values, since docs |
| 1309 |
# disagree with at least some platforms' realities on that. |
| 1310 |
for is_ints in (True, False): |
| 1311 |
mock_termios.tcgetattr.return_value = _make_tcattrs( |
| 1312 |
cc_is_ints=is_ints |
| 1313 |
) |
| 1314 |
self._run(_) |
| 1315 |
# Ensure tcsetattr and setcbreak were never called |
| 1316 |
assert not mock_tty.setcbreak.called |
| 1317 |
assert not mock_termios.tcsetattr.called |
| 1318 |
|
| 1319 |
class send_interrupt: |
| 1320 |
def _run_with_mocked_interrupt(self, klass): |
| 1321 |
runner = klass(Context()) |
| 1322 |
runner.send_interrupt = Mock() |
| 1323 |
try: |
| 1324 |
runner.run(_) |
| 1325 |
except _GenericException: |
| 1326 |
pass |
| 1327 |
return runner |
| 1328 |
|
| 1329 |
def called_on_KeyboardInterrupt(self): |
| 1330 |
runner = self._run_with_mocked_interrupt( |
| 1331 |
_KeyboardInterruptingRunner |
| 1332 |
) |
| 1333 |
assert runner.send_interrupt.called |
| 1334 |
|
| 1335 |
def not_called_for_other_exceptions(self): |
| 1336 |
runner = self._run_with_mocked_interrupt(_GenericExceptingRunner) |
| 1337 |
assert not runner.send_interrupt.called |
| 1338 |
|
| 1339 |
def sends_escape_byte_sequence(self): |
| 1340 |
for pty in (True, False): |
| 1341 |
runner = _KeyboardInterruptingRunner(Context()) |
| 1342 |
mock_stdin = Mock() |
| 1343 |
runner.write_proc_stdin = mock_stdin |
| 1344 |
runner.run(_, pty=pty) |
| 1345 |
mock_stdin.assert_called_once_with("\x03") |
| 1346 |
|
| 1347 |
class timeout: |
| 1348 |
def start_timer_called_with_config_value(self): |
| 1349 |
runner = self._runner(timeouts={"command": 7}) |
| 1350 |
runner.start_timer = Mock() |
| 1351 |
assert runner.context.config.timeouts.command == 7 |
| 1352 |
runner.run(_) |
| 1353 |
runner.start_timer.assert_called_once_with(7) |
| 1354 |
|
| 1355 |
def run_kwarg_honored(self): |
| 1356 |
runner = self._runner() |
| 1357 |
runner.start_timer = Mock() |
| 1358 |
assert runner.context.config.timeouts.command is None |
| 1359 |
runner.run(_, timeout=3) |
| 1360 |
runner.start_timer.assert_called_once_with(3) |
| 1361 |
|
| 1362 |
def kwarg_wins_over_config(self): |
| 1363 |
runner = self._runner(timeouts={"command": 7}) |
| 1364 |
runner.start_timer = Mock() |
| 1365 |
assert runner.context.config.timeouts.command == 7 |
| 1366 |
runner.run(_, timeout=3) |
| 1367 |
runner.start_timer.assert_called_once_with(3) |
| 1368 |
|
| 1369 |
def raises_CommandTimedOut_with_timeout_info(self): |
| 1370 |
runner = self._runner( |
| 1371 |
klass=_TimingOutRunner, timeouts={"command": 7} |
| 1372 |
) |
| 1373 |
with raises(CommandTimedOut) as info: |
| 1374 |
runner.run(_) |
| 1375 |
assert info.value.timeout == 7 |
| 1376 |
_repr = "<CommandTimedOut: cmd='nope' timeout=7>" |
| 1377 |
assert repr(info.value) == _repr |
| 1378 |
expected = """ |
| 1379 |
Command did not complete within 7 seconds! |
| 1380 |
|
| 1381 |
Command: 'nope' |
| 1382 |
|
| 1383 |
Stdout: already printed |
| 1384 |
|
| 1385 |
Stderr: already printed |
| 1386 |
|
| 1387 |
""".lstrip() |
| 1388 |
assert str(info.value) == expected |
| 1389 |
|
| 1390 |
@patch("invoke.runners.threading.Timer") |
| 1391 |
def start_timer_gives_its_timer_the_kill_method(self, Timer): |
| 1392 |
runner = self._runner() |
| 1393 |
runner.start_timer(30) |
| 1394 |
Timer.assert_called_once_with(30, runner.kill) |
| 1395 |
|
| 1396 |
def _mocked_timer(self): |
| 1397 |
runner = self._runner() |
| 1398 |
runner._timer = Mock() |
| 1399 |
return runner |
| 1400 |
|
| 1401 |
def run_always_stops_timer(self): |
| 1402 |
runner = _GenericExceptingRunner(Context()) |
| 1403 |
runner._timer = Mock() |
| 1404 |
with raises(_GenericException): |
| 1405 |
runner.run(_) |
| 1406 |
runner._timer.cancel.assert_called_once_with() |
| 1407 |
|
| 1408 |
def timer_aliveness_is_test_of_timing_out(self): |
| 1409 |
# Might be redundant, but easy enough to unit test |
| 1410 |
runner = Runner(Context()) |
| 1411 |
runner._timer = Mock() |
| 1412 |
runner._timer.is_alive.return_value = False |
| 1413 |
assert runner.timed_out |
| 1414 |
runner._timer.is_alive.return_value = True |
| 1415 |
assert not runner.timed_out |
| 1416 |
|
| 1417 |
def timeout_specified_but_no_timer_means_no_exception(self): |
| 1418 |
# Weird corner case but worth testing |
| 1419 |
runner = Runner(Context()) |
| 1420 |
runner._timer = None |
| 1421 |
assert not runner.timed_out |
| 1422 |
|
| 1423 |
class stop: |
| 1424 |
def always_runs_no_matter_what(self): |
| 1425 |
runner = _GenericExceptingRunner(context=Context()) |
| 1426 |
runner.stop = Mock() |
| 1427 |
with raises(_GenericException): |
| 1428 |
runner.run(_) |
| 1429 |
runner.stop.assert_called_once_with() |
| 1430 |
|
| 1431 |
def cancels_timer(self): |
| 1432 |
runner = self._runner() |
| 1433 |
runner._timer = Mock() |
| 1434 |
runner.stop() |
| 1435 |
runner._timer.cancel.assert_called_once_with() |
| 1436 |
|
| 1437 |
class asynchronous: |
| 1438 |
def returns_Promise_immediately_and_finishes_on_join(self): |
| 1439 |
# Dummy subclass with controllable process_is_finished flag |
| 1440 |
class _Finisher(_Dummy): |
| 1441 |
_finished = False |
| 1442 |
|
| 1443 |
@property |
| 1444 |
def process_is_finished(self): |
| 1445 |
return self._finished |
| 1446 |
|
| 1447 |
runner = _Finisher(Context()) |
| 1448 |
# Set up mocks and go |
| 1449 |
runner.start = Mock() |
| 1450 |
for method in _async_skipped_methods: |
| 1451 |
setattr(runner, method, Mock()) |
| 1452 |
result = runner.run(_, asynchronous=True) |
| 1453 |
# Got a Promise (its attrs etc are in its own test subsuite) |
| 1454 |
assert isinstance(result, Promise) |
| 1455 |
# Started, but did not stop (as would've happened for disown) |
| 1456 |
assert runner.start.called |
| 1457 |
for method in _async_skipped_methods: |
| 1458 |
assert not getattr(runner, method).called |
| 1459 |
# Set proc completion flag to truthy and join() |
| 1460 |
runner._finished = True |
| 1461 |
result.join() |
| 1462 |
for method in _async_skipped_methods: |
| 1463 |
assert getattr(runner, method).called |
| 1464 |
|
| 1465 |
@trap |
| 1466 |
def hides_output(self): |
| 1467 |
# Run w/ faux subproc stdout/err data, but async |
| 1468 |
self._runner(out="foo", err="bar").run(_, asynchronous=True).join() |
| 1469 |
# Expect that default out/err streams did not get printed to. |
| 1470 |
assert sys.stdout.getvalue() == "" |
| 1471 |
assert sys.stderr.getvalue() == "" |
| 1472 |
|
| 1473 |
def does_not_forward_stdin(self): |
| 1474 |
class MockedHandleStdin(_Dummy): |
| 1475 |
pass |
| 1476 |
|
| 1477 |
MockedHandleStdin.handle_stdin = Mock() |
| 1478 |
runner = self._runner(klass=MockedHandleStdin) |
| 1479 |
runner.run(_, asynchronous=True).join() |
| 1480 |
# As with the main test for setting this to False, we know that |
| 1481 |
# when stdin is disabled, the handler is never even called (no |
| 1482 |
# thread is created for it). |
| 1483 |
assert not MockedHandleStdin.handle_stdin.called |
| 1484 |
|
| 1485 |
def leaves_overridden_streams_alone(self): |
| 1486 |
# NOTE: technically a duplicate test of the generic tests for #637 |
| 1487 |
# re: intersect of hide and overridden streams. But that's an |
| 1488 |
# implementation detail so this is still valuable. |
| 1489 |
klass = self._mock_stdin_writer() |
| 1490 |
out, err, in_ = StringIO(), StringIO(), StringIO("hallo") |
| 1491 |
runner = self._runner(out="foo", err="bar", klass=klass) |
| 1492 |
runner.run( |
| 1493 |
_, |
| 1494 |
asynchronous=True, |
| 1495 |
out_stream=out, |
| 1496 |
err_stream=err, |
| 1497 |
in_stream=in_, |
| 1498 |
).join() |
| 1499 |
assert out.getvalue() == "foo" |
| 1500 |
assert err.getvalue() == "bar" |
| 1501 |
assert klass.write_proc_stdin.called # lazy |
| 1502 |
|
| 1503 |
class disown: |
| 1504 |
@patch.object(threading.Thread, "start") |
| 1505 |
def starts_but_does_nothing_else_and_returns_emptyish_Result( |
| 1506 |
self, thread_start |
| 1507 |
): |
| 1508 |
runner = Runner(Context()) |
| 1509 |
runner.start = Mock() |
| 1510 |
runner.get_pid = Mock() |
| 1511 |
for method in _disown_skipped_methods: |
| 1512 |
setattr(runner, method, Mock()) |
| 1513 |
result = runner.run(_, disown=True) |
| 1514 |
# Result contains the pid but not much else |
| 1515 |
assert result.command == _ |
| 1516 |
assert result.pid == runner.get_pid.return_value |
| 1517 |
# Subprocess kicked off |
| 1518 |
assert runner.start.called |
| 1519 |
# No timer or IO threads started |
| 1520 |
assert not thread_start.called |
| 1521 |
# No wait or shutdown related Runner methods called |
| 1522 |
for method in _disown_skipped_methods: |
| 1523 |
assert not getattr(runner, method).called |
| 1524 |
|
| 1525 |
def cannot_be_given_alongside_asynchronous(self): |
| 1526 |
with raises(ValueError) as info: |
| 1527 |
self._runner().run(_, asynchronous=True, disown=True) |
| 1528 |
sentinel = "Cannot give both 'asynchronous' and 'disown'" |
| 1529 |
assert sentinel in str(info.value) |
| 1530 |
|
| 1531 |
class get_pid: |
| 1532 |
def returns_None_by_default(self): |
| 1533 |
runner = self._runner() |
| 1534 |
runner.run(_) |
| 1535 |
assert runner.get_pid() is None |
| 1536 |
|
| 1537 |
|
| 1538 |
class _FastLocal(Local): |
| 1539 |
# Neuter this for same reason as in _Dummy above |
| 1540 |
input_sleep = 0 |
| 1541 |
|
| 1542 |
|
| 1543 |
class Local_: |
| 1544 |
def _run(self, *args, **kwargs): |
| 1545 |
return _run(*args, **dict(kwargs, klass=_FastLocal)) |
| 1546 |
|
| 1547 |
def _runner(self, *args, **kwargs): |
| 1548 |
return _runner(*args, **dict(kwargs, klass=_FastLocal)) |
| 1549 |
|
| 1550 |
class stop: |
| 1551 |
@mock_subprocess() |
| 1552 |
def calls_super(self): |
| 1553 |
# Re #910 |
| 1554 |
runner = self._runner() |
| 1555 |
runner._timer = Mock() # twiddled by parent class stop() |
| 1556 |
runner.run(_) |
| 1557 |
runner._timer.cancel.assert_called_once_with() |
| 1558 |
|
| 1559 |
class pty: |
| 1560 |
@mock_pty() |
| 1561 |
def when_pty_True_we_use_pty_fork_and_os_exec(self): |
| 1562 |
"when pty=True, we use pty.fork and os.exec*" |
| 1563 |
self._run(_, pty=True) |
| 1564 |
# @mock_pty's asserts check os/pty calls for us. |
| 1565 |
|
| 1566 |
@mock_pty(insert_os=True) |
| 1567 |
def _expect_exit_check(self, exited, mock_os): |
| 1568 |
if exited: |
| 1569 |
expected_check = mock_os.WIFEXITED |
| 1570 |
expected_get = mock_os.WEXITSTATUS |
| 1571 |
unexpected_check = mock_os.WIFSIGNALED |
| 1572 |
unexpected_get = mock_os.WTERMSIG |
| 1573 |
else: |
| 1574 |
expected_check = mock_os.WIFSIGNALED |
| 1575 |
expected_get = mock_os.WTERMSIG |
| 1576 |
unexpected_check = mock_os.WIFEXITED |
| 1577 |
unexpected_get = mock_os.WEXITSTATUS |
| 1578 |
expected_check.return_value = True |
| 1579 |
unexpected_check.return_value = False |
| 1580 |
self._run(_, pty=True) |
| 1581 |
exitstatus = mock_os.waitpid.return_value[1] |
| 1582 |
expected_get.assert_called_once_with(exitstatus) |
| 1583 |
assert not unexpected_get.called |
| 1584 |
|
| 1585 |
def pty_uses_WEXITSTATUS_if_WIFEXITED(self): |
| 1586 |
self._expect_exit_check(True) |
| 1587 |
|
| 1588 |
def pty_uses_WTERMSIG_if_WIFSIGNALED(self): |
| 1589 |
self._expect_exit_check(False) |
| 1590 |
|
| 1591 |
@mock_pty(insert_os=True) |
| 1592 |
def WTERMSIG_result_turned_negative_to_match_subprocess(self, mock_os): |
| 1593 |
mock_os.WIFEXITED.return_value = False |
| 1594 |
mock_os.WIFSIGNALED.return_value = True |
| 1595 |
mock_os.WTERMSIG.return_value = 2 |
| 1596 |
assert self._run(_, pty=True, warn=True).exited == -2 |
| 1597 |
|
| 1598 |
@mock_pty() |
| 1599 |
def pty_is_set_to_controlling_terminal_size(self): |
| 1600 |
self._run(_, pty=True) |
| 1601 |
# @mock_pty's asserts check the TIOC[GS]WINSZ calls for us |
| 1602 |
|
| 1603 |
def warning_only_fires_once(self): |
| 1604 |
# I.e. if implementation checks pty-ness >1 time, only one warning |
| 1605 |
# is emitted. This is kinda implementation-specific, but... |
| 1606 |
skip() |
| 1607 |
|
| 1608 |
@patch("invoke.runners.sys") |
| 1609 |
def replaced_stdin_objects_dont_explode(self, mock_sys): |
| 1610 |
# Replace sys.stdin with an object lacking .isatty(), which |
| 1611 |
# normally causes an AttributeError unless we are being careful. |
| 1612 |
mock_sys.stdin = object() |
| 1613 |
# Test. If bug is present, this will error. |
| 1614 |
runner = Local(Context()) |
| 1615 |
assert runner.should_use_pty(pty=True, fallback=True) is False |
| 1616 |
|
| 1617 |
@mock_pty(trailing_error=OSError("Input/output error")) |
| 1618 |
def spurious_OSErrors_handled_gracefully(self): |
| 1619 |
# Doesn't-blow-up test. |
| 1620 |
self._run(_, pty=True) |
| 1621 |
|
| 1622 |
@mock_pty(trailing_error=OSError("I/O error")) |
| 1623 |
def other_spurious_OSErrors_handled_gracefully(self): |
| 1624 |
# Doesn't-blow-up test. |
| 1625 |
self._run(_, pty=True) |
| 1626 |
|
| 1627 |
@mock_pty(trailing_error=OSError("wat")) |
| 1628 |
def non_spurious_OSErrors_bubble_up(self): |
| 1629 |
try: |
| 1630 |
self._run(_, pty=True) |
| 1631 |
except ThreadException as e: |
| 1632 |
e = e.exceptions[0] |
| 1633 |
assert e.type == OSError |
| 1634 |
assert str(e.value) == "wat" |
| 1635 |
|
| 1636 |
@mock_pty(os_close_error=True) |
| 1637 |
def stop_mutes_errors_on_pty_close(self): |
| 1638 |
# Another doesn't-blow-up test, this time around os.close() of the |
| 1639 |
# pty itself (due to os_close_error=True) |
| 1640 |
self._run(_, pty=True) |
| 1641 |
|
| 1642 |
class fallback: |
| 1643 |
@mock_pty(isatty=False) |
| 1644 |
def can_be_overridden_by_kwarg(self): |
| 1645 |
self._run(_, pty=True, fallback=False) |
| 1646 |
# @mock_pty's asserts will be mad if pty-related os/pty calls |
| 1647 |
# didn't fire, so we're done. |
| 1648 |
|
| 1649 |
@mock_pty(isatty=False) |
| 1650 |
def can_be_overridden_by_config(self): |
| 1651 |
self._runner(run={"fallback": False}).run(_, pty=True) |
| 1652 |
# @mock_pty's asserts will be mad if pty-related os/pty calls |
| 1653 |
# didn't fire, so we're done. |
| 1654 |
|
| 1655 |
@trap |
| 1656 |
@mock_subprocess(isatty=False) |
| 1657 |
def affects_result_pty_value(self, *mocks): |
| 1658 |
assert self._run(_, pty=True).pty is False |
| 1659 |
|
| 1660 |
@mock_pty(isatty=False) |
| 1661 |
def overridden_fallback_affects_result_pty_value(self): |
| 1662 |
assert self._run(_, pty=True, fallback=False).pty is True |
| 1663 |
|
| 1664 |
class shell: |
| 1665 |
@mock_pty(insert_os=True) |
| 1666 |
def defaults_to_bash_or_cmdexe_when_pty_True(self, mock_os): |
| 1667 |
# NOTE: yea, windows can't run pty is true, but this is really |
| 1668 |
# testing config behavior, so...meh |
| 1669 |
self._run(_, pty=True) |
| 1670 |
_expect_platform_shell(mock_os.execvpe.call_args_list[0][0][0]) |
| 1671 |
|
| 1672 |
@mock_subprocess(insert_Popen=True) |
| 1673 |
def defaults_to_bash_or_cmdexe_when_pty_False(self, mock_Popen): |
| 1674 |
self._run(_, pty=False) |
| 1675 |
_expect_platform_shell( |
| 1676 |
mock_Popen.call_args_list[0][1]["executable"] |
| 1677 |
) |
| 1678 |
|
| 1679 |
@mock_pty(insert_os=True) |
| 1680 |
def may_be_overridden_when_pty_True(self, mock_os): |
| 1681 |
self._run(_, pty=True, shell="/bin/zsh") |
| 1682 |
assert mock_os.execvpe.call_args_list[0][0][0] == "/bin/zsh" |
| 1683 |
|
| 1684 |
@mock_subprocess(insert_Popen=True) |
| 1685 |
def may_be_overridden_when_pty_False(self, mock_Popen): |
| 1686 |
self._run(_, pty=False, shell="/bin/zsh") |
| 1687 |
assert mock_Popen.call_args_list[0][1]["executable"] == "/bin/zsh" |
| 1688 |
|
| 1689 |
class env: |
| 1690 |
# NOTE: update-vs-replace semantics are tested 'purely' up above in |
| 1691 |
# regular Runner tests. |
| 1692 |
|
| 1693 |
@mock_subprocess(insert_Popen=True) |
| 1694 |
def uses_Popen_kwarg_for_pty_False(self, mock_Popen): |
| 1695 |
self._run(_, pty=False, env={"FOO": "BAR"}) |
| 1696 |
expected = dict(os.environ, FOO="BAR") |
| 1697 |
env = mock_Popen.call_args_list[0][1]["env"] |
| 1698 |
assert env == expected |
| 1699 |
|
| 1700 |
@mock_pty(insert_os=True) |
| 1701 |
def uses_execve_for_pty_True(self, mock_os): |
| 1702 |
type(mock_os).environ = {"OTHERVAR": "OTHERVAL"} |
| 1703 |
self._run(_, pty=True, env={"FOO": "BAR"}) |
| 1704 |
expected = {"OTHERVAR": "OTHERVAL", "FOO": "BAR"} |
| 1705 |
env = mock_os.execvpe.call_args_list[0][0][2] |
| 1706 |
assert env == expected |
| 1707 |
|
| 1708 |
class close_proc_stdin: |
| 1709 |
def raises_SubprocessPipeError_when_pty_in_use(self): |
| 1710 |
with raises(SubprocessPipeError): |
| 1711 |
runner = Local(Context()) |
| 1712 |
runner.using_pty = True |
| 1713 |
runner.close_proc_stdin() |
| 1714 |
|
| 1715 |
def closes_process_stdin(self): |
| 1716 |
runner = Local(Context()) |
| 1717 |
runner.process = Mock() |
| 1718 |
runner.using_pty = False |
| 1719 |
runner.close_proc_stdin() |
| 1720 |
runner.process.stdin.close.assert_called_once_with() |
| 1721 |
|
| 1722 |
class timeout: |
| 1723 |
@patch("invoke.runners.os") |
| 1724 |
def kill_uses_self_pid_when_pty(self, mock_os): |
| 1725 |
runner = self._runner() |
| 1726 |
runner.using_pty = True |
| 1727 |
runner.pid = 50 |
| 1728 |
runner.kill() |
| 1729 |
mock_os.kill.assert_called_once_with(50, signal.SIGKILL) |
| 1730 |
|
| 1731 |
@patch("invoke.runners.os") |
| 1732 |
def kill_uses_self_process_pid_when_not_pty(self, mock_os): |
| 1733 |
runner = self._runner() |
| 1734 |
runner.using_pty = False |
| 1735 |
runner.process = Mock(pid=30) |
| 1736 |
runner.kill() |
| 1737 |
mock_os.kill.assert_called_once_with(30, signal.SIGKILL) |
| 1738 |
|
| 1739 |
class get_pid: |
| 1740 |
@mock_pty(insert_os=True) |
| 1741 |
def is_top_level_pid_when_using_pty(self, mock_os): |
| 1742 |
runner = self._runner() |
| 1743 |
runner.run(_, pty=True) |
| 1744 |
# exitstatus = mock_os.waitpid.return_value[1] |
| 1745 |
assert runner.get_pid() is runner.pid |
| 1746 |
|
| 1747 |
@mock_subprocess() |
| 1748 |
def is_process_attribute_pid_when_no_pty(self): |
| 1749 |
runner = self._runner() |
| 1750 |
runner.run(_, pty=False) |
| 1751 |
assert runner.get_pid() is runner.process.pid |
| 1752 |
|
| 1753 |
|
| 1754 |
class Result_: |
| 1755 |
def nothing_is_required(self): |
| 1756 |
Result() |
| 1757 |
|
| 1758 |
def first_posarg_is_stdout(self): |
| 1759 |
assert Result("foo").stdout == "foo" |
| 1760 |
|
| 1761 |
def command_defaults_to_empty_string(self): |
| 1762 |
assert Result().command == "" |
| 1763 |
|
| 1764 |
def shell_defaults_to_empty_string(self): |
| 1765 |
assert Result().shell == "" |
| 1766 |
|
| 1767 |
def encoding_defaults_to_local_default_encoding(self): |
| 1768 |
assert Result().encoding == default_encoding() |
| 1769 |
|
| 1770 |
def env_defaults_to_empty_dict(self): |
| 1771 |
assert Result().env == {} |
| 1772 |
|
| 1773 |
def stdout_defaults_to_empty_string(self): |
| 1774 |
assert Result().stdout == "" |
| 1775 |
|
| 1776 |
def stderr_defaults_to_empty_string(self): |
| 1777 |
assert Result().stderr == "" |
| 1778 |
|
| 1779 |
def exited_defaults_to_zero(self): |
| 1780 |
assert Result().exited == 0 |
| 1781 |
|
| 1782 |
def pty_defaults_to_False(self): |
| 1783 |
assert Result().pty is False |
| 1784 |
|
| 1785 |
def pid_defaults_to_None(self): |
| 1786 |
assert Result().pid is None |
| 1787 |
|
| 1788 |
def repr_contains_useful_info(self): |
| 1789 |
assert repr(Result(command="foo")) == "<Result cmd='foo' exited=0>" |
| 1790 |
|
| 1791 |
class tail: |
| 1792 |
def setup_method(self): |
| 1793 |
self.sample = "\n".join(str(x) for x in range(25)) |
| 1794 |
|
| 1795 |
def returns_last_10_lines_of_given_stream_plus_whitespace(self): |
| 1796 |
expected = """ |
| 1797 |
|
| 1798 |
15 |
| 1799 |
16 |
| 1800 |
17 |
| 1801 |
18 |
| 1802 |
19 |
| 1803 |
20 |
| 1804 |
21 |
| 1805 |
22 |
| 1806 |
23 |
| 1807 |
24""" |
| 1808 |
assert Result(stdout=self.sample).tail("stdout") == expected |
| 1809 |
|
| 1810 |
def line_count_is_configurable(self): |
| 1811 |
expected = """ |
| 1812 |
|
| 1813 |
23 |
| 1814 |
24""" |
| 1815 |
tail = Result(stdout=self.sample).tail("stdout", count=2) |
| 1816 |
assert tail == expected |
| 1817 |
|
| 1818 |
def works_for_stderr_too(self): |
| 1819 |
# Dumb test is dumb, but whatever |
| 1820 |
expected = """ |
| 1821 |
|
| 1822 |
23 |
| 1823 |
24""" |
| 1824 |
tail = Result(stderr=self.sample).tail("stderr", count=2) |
| 1825 |
assert tail == expected |
| 1826 |
|
| 1827 |
|
| 1828 |
class Promise_: |
| 1829 |
def explicitly_inherits_from_abstract_base_class(self) -> None: |
| 1830 |
# Supports improved downstream typechecking. |
| 1831 |
assert AbstractContextManager in Promise.__mro__ |
| 1832 |
|
| 1833 |
def repr_degrades_gracefully(self) -> None: |
| 1834 |
promise = _runner().run( |
| 1835 |
_, pty=True, encoding="utf-17", shell="sea", asynchronous=True |
| 1836 |
) |
| 1837 |
assert repr(promise) == f"<Promise cmd='{_}'>" |
| 1838 |
|
| 1839 |
def exposes_read_only_run_params(self): |
| 1840 |
runner = _runner() |
| 1841 |
promise = runner.run( |
| 1842 |
_, pty=True, encoding="utf-17", shell="sea", asynchronous=True |
| 1843 |
) |
| 1844 |
assert promise.command == _ |
| 1845 |
assert promise.pty is True |
| 1846 |
assert promise.encoding == "utf-17" |
| 1847 |
assert promise.shell == "sea" |
| 1848 |
assert not hasattr(promise, "stdout") |
| 1849 |
assert not hasattr(promise, "stderr") |
| 1850 |
|
| 1851 |
class join: |
| 1852 |
# NOTE: high level Runner lifecycle mechanics of join() (re: wait(), |
| 1853 |
# process_is_finished() etc) are tested in main suite. |
| 1854 |
|
| 1855 |
def returns_Result_on_success(self): |
| 1856 |
result = _runner().run(_, asynchronous=True).join() |
| 1857 |
assert isinstance(result, Result) |
| 1858 |
# Sanity |
| 1859 |
assert result.command == _ |
| 1860 |
assert result.exited == 0 |
| 1861 |
|
| 1862 |
def raises_main_thread_exception_on_kaboom(self): |
| 1863 |
runner = _runner(klass=_GenericExceptingRunner) |
| 1864 |
with raises(_GenericException): |
| 1865 |
runner.run(_, asynchronous=True).join() |
| 1866 |
|
| 1867 |
def raises_subthread_exception_on_their_kaboom(self): |
| 1868 |
class Kaboom(_Dummy): |
| 1869 |
def handle_stdout(self, **kwargs): |
| 1870 |
raise OhNoz() |
| 1871 |
|
| 1872 |
runner = _runner(klass=Kaboom) |
| 1873 |
promise = runner.run(_, asynchronous=True) |
| 1874 |
with raises(ThreadException) as info: |
| 1875 |
promise.join() |
| 1876 |
assert isinstance(info.value.exceptions[0].value, OhNoz) |
| 1877 |
|
| 1878 |
def raises_Failure_on_failure(self): |
| 1879 |
runner = _runner(exits=1) |
| 1880 |
promise = runner.run(_, asynchronous=True) |
| 1881 |
with raises(Failure): |
| 1882 |
promise.join() |
| 1883 |
|
| 1884 |
class context_manager: |
| 1885 |
def calls_join_or_wait_on_close_of_block(self): |
| 1886 |
promise = _runner().run(_, asynchronous=True) |
| 1887 |
promise.join = Mock() |
| 1888 |
with promise: |
| 1889 |
pass |
| 1890 |
promise.join.assert_called_once_with() |
| 1891 |
|
| 1892 |
def yields_self(self): |
| 1893 |
promise = _runner().run(_, asynchronous=True) |
| 1894 |
with promise as value: |
| 1895 |
assert value is promise |