import sys from io import StringIO import pytest def test_run_command_passthrough_writes_to_sys_streams(monkeypatch: pytest.MonkeyPatch) -> None: from l4d2web.services.host_commands import run_command mock_stdout = StringIO() mock_stderr = StringIO() monkeypatch.setattr(sys, "stdout", mock_stdout) monkeypatch.setattr(sys, "stderr", mock_stderr) run_command( ["python3", "-c", "import sys; print('passed out'); print('passed err', file=sys.stderr)"], passthrough=True, ) assert mock_stdout.getvalue() == "passed out\n" assert mock_stderr.getvalue() == "passed err\n" def test_run_command_streams_stdout_and_stderr_callbacks() -> None: from l4d2web.services.host_commands import run_command stdout: list[str] = [] stderr: list[str] = [] result = run_command( ["python3", "-c", "import sys; print('ok'); print('warn', file=sys.stderr)"], on_stdout=stdout.append, on_stderr=stderr.append, ) assert stdout == ["ok"] assert stderr == ["warn"] assert result.returncode == 0 assert result.stdout == "ok" assert result.stderr == "warn" def test_run_command_raises_host_error_on_nonzero_exit() -> None: from l4d2web.services.host_commands import HostCommandError, run_command with pytest.raises(HostCommandError) as exc_info: run_command(["python3", "-c", "import sys; print('bad', file=sys.stderr); sys.exit(7)"]) assert exc_info.value.returncode == 7 assert exc_info.value.stderr == "bad" def test_run_command_raises_cancelled_error_when_cancel_requested() -> None: from l4d2web.services.host_commands import CommandCancelledError, run_command stdout: list[str] = [] with pytest.raises(CommandCancelledError): run_command( ["python3", "-c", "import time; print('ready', flush=True); time.sleep(5)"], on_stdout=stdout.append, should_cancel=lambda: bool(stdout), cancel_poll_seconds=0.01, cancel_terminate_timeout=0.2, ) assert stdout == ["ready"] def test_stream_command_yields_stdout_lines() -> None: from l4d2web.services.host_commands import stream_command lines = list(stream_command(["python3", "-c", "print('one'); print('two')"])) assert lines == ["one", "two"]