test_testing.py 2.4 KB

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