left4me/l4d2web/tests/test_host_commands.py

55 lines
1.7 KiB
Python

import pytest
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"]