utils.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from __future__ import annotations
  2. import sys
  3. from subprocess import PIPE, Popen
  4. from typing import Any, Sequence
  5. def get_output_error_code(cmd: str | Sequence[str]) -> tuple[str, str, Any]:
  6. """Get stdout, stderr, and exit code from running a command"""
  7. p = Popen(cmd, stdout=PIPE, stderr=PIPE) # noqa: S603
  8. out, err = p.communicate()
  9. out_str = out.decode("utf8", "replace")
  10. err_str = err.decode("utf8", "replace")
  11. return out_str, err_str, p.returncode
  12. def check_help_output(pkg: str, subcommand: Sequence[str] | None = None) -> tuple[str, str]:
  13. """test that `python -m PKG [subcommand] -h` works"""
  14. cmd = [sys.executable, "-m", pkg]
  15. if subcommand:
  16. cmd.extend(subcommand)
  17. cmd.append("-h")
  18. out, err, rc = get_output_error_code(cmd)
  19. assert rc == 0, err
  20. assert "Traceback" not in err
  21. assert "Options" in out
  22. assert "--help-all" in out
  23. return out, err
  24. def check_help_all_output(pkg: str, subcommand: Sequence[str] | None = None) -> tuple[str, str]:
  25. """test that `python -m PKG --help-all` works"""
  26. cmd = [sys.executable, "-m", pkg]
  27. if subcommand:
  28. cmd.extend(subcommand)
  29. cmd.append("--help-all")
  30. out, err, rc = get_output_error_code(cmd)
  31. assert rc == 0, err
  32. assert "Traceback" not in err
  33. assert "Options" in out
  34. assert "Class options" in out
  35. return out, err