test_hooks.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Test hooks"""
  2. import pytest
  3. @pytest.mark.parametrize(
  4. 'pre, pre_code, post, post_code', [
  5. (False, 0, False, 0),
  6. (True, 0, False, 0),
  7. (True, 5, False, 0),
  8. (False, 0, True, 0),
  9. (False, 0, True, 5),
  10. (True, 0, True, 0),
  11. (True, 5, True, 5),
  12. ], ids=[
  13. 'no-hooks',
  14. 'pre-success',
  15. 'pre-fail',
  16. 'post-success',
  17. 'post-fail',
  18. 'pre-post-success',
  19. 'pre-post-fail',
  20. ])
  21. def test_hooks(
  22. runner, yadm_y, paths,
  23. pre, pre_code, post, post_code):
  24. """Test pre/post hook"""
  25. # generate hooks
  26. if pre:
  27. create_hook(paths, 'pre_version', pre_code)
  28. if post:
  29. create_hook(paths, 'post_version', post_code)
  30. # run yadm
  31. run = runner(yadm_y('version'))
  32. # when a pre hook fails, yadm should exit with the hook's code
  33. assert run.code == pre_code
  34. assert run.err == ''
  35. if pre:
  36. assert 'HOOK:pre_version' in run.out
  37. # if pre hook is missing or successful, yadm itself should exit 0
  38. if run.success:
  39. if post:
  40. assert 'HOOK:post_version' in run.out
  41. else:
  42. # when a pre hook fails, yadm should not run the command
  43. assert 'version will not be run' in run.out
  44. # when a pre hook fails, yadm should not run the post hook
  45. assert 'HOOK:post_version' not in run.out
  46. # repo fixture is needed to test the population of YADM_HOOK_WORK
  47. @pytest.mark.usefixtures('ds1_repo_copy')
  48. def test_hook_env(runner, yadm_y, paths):
  49. """Test hook environment"""
  50. # test will be done with a non existent "git" passthru command
  51. # which should exit with a failing code
  52. cmd = 'passthrucmd'
  53. # write the hook
  54. hook = paths.hooks.join(f'post_{cmd}')
  55. hook.write('#!/bin/sh\nenv\n')
  56. hook.chmod(0o755)
  57. run = runner(yadm_y(cmd, 'extra_args'))
  58. # expect passthru to fail
  59. assert run.failure
  60. assert f"'{cmd}' is not a git command" in run.err
  61. # verify hook environment
  62. assert 'YADM_HOOK_EXIT=1\n' in run.out
  63. assert f'YADM_HOOK_COMMAND={cmd}\n' in run.out
  64. assert f'YADM_HOOK_FULL_COMMAND={cmd} extra_args\n' in run.out
  65. assert f'YADM_HOOK_REPO={paths.repo}\n' in run.out
  66. assert f'YADM_HOOK_WORK={paths.work}\n' in run.out
  67. def create_hook(paths, name, code):
  68. """Create hook"""
  69. hook = paths.hooks.join(name)
  70. hook.write(
  71. '#!/bin/sh\n'
  72. f'echo HOOK:{name}\n'
  73. f'exit {code}\n'
  74. )
  75. hook.chmod(0o755)