test_shell_utils.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import pytest
  2. import subprocess
  3. import json
  4. import sys
  5. from numpy.distutils import _shell_utils
  6. from numpy.testing import IS_WASM
  7. argv_cases = [
  8. [r'exe'],
  9. [r'path/exe'],
  10. [r'path\exe'],
  11. [r'\\server\path\exe'],
  12. [r'path to/exe'],
  13. [r'path to\exe'],
  14. [r'exe', '--flag'],
  15. [r'path/exe', '--flag'],
  16. [r'path\exe', '--flag'],
  17. [r'path to/exe', '--flag'],
  18. [r'path to\exe', '--flag'],
  19. # flags containing literal quotes in their name
  20. [r'path to/exe', '--flag-"quoted"'],
  21. [r'path to\exe', '--flag-"quoted"'],
  22. [r'path to/exe', '"--flag-quoted"'],
  23. [r'path to\exe', '"--flag-quoted"'],
  24. ]
  25. @pytest.fixture(params=[
  26. _shell_utils.WindowsParser,
  27. _shell_utils.PosixParser
  28. ])
  29. def Parser(request):
  30. return request.param
  31. @pytest.fixture
  32. def runner(Parser):
  33. if Parser != _shell_utils.NativeParser:
  34. pytest.skip('Unable to run with non-native parser')
  35. if Parser == _shell_utils.WindowsParser:
  36. return lambda cmd: subprocess.check_output(cmd)
  37. elif Parser == _shell_utils.PosixParser:
  38. # posix has no non-shell string parsing
  39. return lambda cmd: subprocess.check_output(cmd, shell=True)
  40. else:
  41. raise NotImplementedError
  42. @pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
  43. @pytest.mark.parametrize('argv', argv_cases)
  44. def test_join_matches_subprocess(Parser, runner, argv):
  45. """
  46. Test that join produces strings understood by subprocess
  47. """
  48. # invoke python to return its arguments as json
  49. cmd = [
  50. sys.executable, '-c',
  51. 'import json, sys; print(json.dumps(sys.argv[1:]))'
  52. ]
  53. joined = Parser.join(cmd + argv)
  54. json_out = runner(joined).decode()
  55. assert json.loads(json_out) == argv
  56. @pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
  57. @pytest.mark.parametrize('argv', argv_cases)
  58. def test_roundtrip(Parser, argv):
  59. """
  60. Test that split is the inverse operation of join
  61. """
  62. try:
  63. joined = Parser.join(argv)
  64. assert argv == Parser.split(joined)
  65. except NotImplementedError:
  66. pytest.skip("Not implemented")