test_execute.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import logging
  2. import subprocess
  3. import pytest
  4. from flexmock import flexmock
  5. from borgmatic import execute as module
  6. def test_log_output_logs_each_line_separately():
  7. flexmock(module.logger).should_receive('log').with_args(logging.INFO, 'hi').once()
  8. flexmock(module.logger).should_receive('log').with_args(logging.INFO, 'there').once()
  9. flexmock(module).should_receive('exit_code_indicates_error').and_return(False)
  10. hi_process = subprocess.Popen(['echo', 'hi'], stdout=subprocess.PIPE)
  11. module.log_output(
  12. ['echo', 'hi'],
  13. hi_process,
  14. hi_process.stdout,
  15. output_log_level=logging.INFO,
  16. error_on_warnings=False,
  17. )
  18. there_process = subprocess.Popen(['echo', 'there'], stdout=subprocess.PIPE)
  19. module.log_output(
  20. ['echo', 'there'],
  21. there_process,
  22. there_process.stdout,
  23. output_log_level=logging.INFO,
  24. error_on_warnings=False,
  25. )
  26. def test_log_output_includes_error_output_in_exception():
  27. flexmock(module.logger).should_receive('log')
  28. flexmock(module).should_receive('exit_code_indicates_error').and_return(True)
  29. process = subprocess.Popen(['grep'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  30. with pytest.raises(subprocess.CalledProcessError) as error:
  31. module.log_output(
  32. ['grep'],
  33. process,
  34. process.stdout,
  35. output_log_level=logging.INFO,
  36. error_on_warnings=False,
  37. )
  38. assert error.value.returncode == 2
  39. assert error.value.output
  40. def test_log_output_truncates_long_error_output():
  41. flexmock(module).ERROR_OUTPUT_MAX_LINE_COUNT = 0
  42. flexmock(module.logger).should_receive('log')
  43. flexmock(module).should_receive('exit_code_indicates_error').and_return(True)
  44. process = subprocess.Popen(['grep'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  45. with pytest.raises(subprocess.CalledProcessError) as error:
  46. module.log_output(
  47. ['grep'],
  48. process,
  49. process.stdout,
  50. output_log_level=logging.INFO,
  51. error_on_warnings=False,
  52. )
  53. assert error.value.returncode == 2
  54. assert error.value.output.startswith('...')
  55. def test_log_output_with_no_output_logs_nothing():
  56. flexmock(module.logger).should_receive('log').never()
  57. flexmock(module).should_receive('exit_code_indicates_error').and_return(False)
  58. process = subprocess.Popen(['true'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  59. module.log_output(
  60. ['true'], process, process.stdout, output_log_level=logging.INFO, error_on_warnings=False
  61. )