import sys
import unittest
from textwrap import dedent
-from typing import Any, Iterator, Optional, Sequence
+from typing import Any, Iterator, Optional, Sequence, TextIO, Union
import pexpect # type: ignore
class Machine:
- def __init__(self, args: Sequence[str] = [], debug: bool = False) -> None:
+ def __init__(self, args: Sequence[str] = []) -> None:
# Remains None until image is built and booted, then receives pexpect process.
self._serial: Optional[pexpect.spawn] = None
self.exit_code: int = -1
- self.debug = debug
self.stack = contextlib.ExitStack()
self.args: MkosiArgs
self._serial.expect("#")
self.stack = stack.pop_all()
- def run(self, commands: Sequence[str], timeout: int = 900, check: bool = True) -> CompletedProcess:
+ def run(
+ self,
+ commands: Sequence[str],
+ timeout: int = 900,
+ check: bool = True,
+ capture_output: bool = False,
+ ) -> CompletedProcess:
self._ensure_booted()
- process = run_command_image(self.args, commands, timeout, check, subprocess.PIPE, subprocess.PIPE)
- if self.debug:
- print(f"Stdout:\n {process.stdout}")
- print(f"Stderr:\n {process.stderr}")
+ stdout: Union[int, TextIO] = subprocess.PIPE if capture_output else sys.stdout
+ stderr: Union[int, TextIO] = subprocess.PIPE if capture_output else sys.stderr
- return process
+ return run_command_image(self.args, commands, timeout, check, stdout, stderr)
def kill(self) -> None:
self.__exit__(None, None, None)
pytest.xfail("QEMU's CPU does not support the CentOS EPEL image arch when running without KVM")
def test_simple_run(self) -> None:
- process = self.machine.run(["echo", "This is a test."])
+ process = self.machine.run(["echo", "This is a test."], capture_output=True)
assert process.stdout.strip("\n") == "This is a test."
def test_wrong_command(self) -> None:
result = self.machine.run(["NonExisting", "Command"], check=False)
assert result.returncode in (1, 127, 203)
- result = self.machine.run(["ls", "-"], check=False)
+ result = self.machine.run(["ls", "-"], check=False, capture_output=True)
assert result.returncode == 2
assert "No such file or directory" in result.stderr