test_testing.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import re
  2. import sys
  3. from joblib.testing import check_subprocess_call, raises
  4. def test_check_subprocess_call():
  5. code = "\n".join(
  6. ["result = 1 + 2 * 3", "print(result)", "my_list = [1, 2, 3]", "print(my_list)"]
  7. )
  8. check_subprocess_call([sys.executable, "-c", code])
  9. # Now checking stdout with a regex
  10. check_subprocess_call(
  11. [sys.executable, "-c", code],
  12. # Regex needed for platform-specific line endings
  13. stdout_regex=r"7\s{1,2}\[1, 2, 3\]",
  14. )
  15. def test_check_subprocess_call_non_matching_regex():
  16. code = "42"
  17. non_matching_pattern = "_no_way_this_matches_anything_"
  18. with raises(ValueError) as excinfo:
  19. check_subprocess_call(
  20. [sys.executable, "-c", code], stdout_regex=non_matching_pattern
  21. )
  22. excinfo.match("Unexpected stdout.+{}".format(non_matching_pattern))
  23. def test_check_subprocess_call_wrong_command():
  24. wrong_command = "_a_command_that_does_not_exist_"
  25. with raises(OSError):
  26. check_subprocess_call([wrong_command])
  27. def test_check_subprocess_call_non_zero_return_code():
  28. code_with_non_zero_exit = "\n".join(
  29. [
  30. "import sys",
  31. 'print("writing on stdout")',
  32. 'sys.stderr.write("writing on stderr")',
  33. "sys.exit(123)",
  34. ]
  35. )
  36. pattern = re.compile(
  37. "Non-zero return code: 123.+"
  38. "Stdout:\nwriting on stdout.+"
  39. "Stderr:\nwriting on stderr",
  40. re.DOTALL,
  41. )
  42. with raises(ValueError) as excinfo:
  43. check_subprocess_call([sys.executable, "-c", code_with_non_zero_exit])
  44. excinfo.match(pattern)
  45. def test_check_subprocess_call_timeout():
  46. code_timing_out = "\n".join(
  47. [
  48. "import time",
  49. "import sys",
  50. 'print("before sleep on stdout")',
  51. "sys.stdout.flush()",
  52. 'sys.stderr.write("before sleep on stderr")',
  53. "sys.stderr.flush()",
  54. # We need to sleep for at least 2 * timeout seconds in case the SIGKILL
  55. # is triggered.
  56. "time.sleep(10)",
  57. 'print("process should have be killed before")',
  58. "sys.stdout.flush()",
  59. ]
  60. )
  61. pattern = re.compile(
  62. "Non-zero return code:.+"
  63. "Stdout:\nbefore sleep on stdout\\s+"
  64. "Stderr:\nbefore sleep on stderr",
  65. re.DOTALL,
  66. )
  67. with raises(ValueError) as excinfo:
  68. check_subprocess_call([sys.executable, "-c", code_timing_out], timeout=1)
  69. excinfo.match(pattern)