test_passcommand.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import json
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. import tempfile
  7. def generate_configuration(config_path, repository_path):
  8. '''
  9. Generate borgmatic configuration into a file at the config path, and update the defaults so as
  10. to work for testing, including updating the source directories, injecting the given repository
  11. path, and tacking on an encryption passcommand.
  12. '''
  13. subprocess.check_call(f'borgmatic config generate --destination {config_path}'.split(' '))
  14. config = (
  15. open(config_path)
  16. .read()
  17. .replace('ssh://user@backupserver/./sourcehostname.borg', repository_path)
  18. .replace('- path: /mnt/backup', '')
  19. .replace('label: local', '')
  20. .replace('- /home/user/path with spaces', '')
  21. .replace('- /home', f'- {config_path}')
  22. .replace('- /etc', '')
  23. .replace('- /var/log/syslog*', '')
  24. + '\nencryption_passcommand: "echo test"'
  25. )
  26. config_file = open(config_path, 'w')
  27. config_file.write(config)
  28. config_file.close()
  29. def test_borgmatic_command():
  30. # Create a Borg repository.
  31. temporary_directory = tempfile.mkdtemp()
  32. repository_path = os.path.join(temporary_directory, 'test.borg')
  33. extract_path = os.path.join(temporary_directory, 'extract')
  34. original_working_directory = os.getcwd()
  35. os.mkdir(extract_path)
  36. os.chdir(extract_path)
  37. try:
  38. config_path = os.path.join(temporary_directory, 'test.yaml')
  39. generate_configuration(config_path, repository_path)
  40. subprocess.check_call(
  41. f'borgmatic -v 2 --config {config_path} repo-create --encryption repokey'.split(' ')
  42. )
  43. # Run borgmatic to generate a backup archive, and then list it to make sure it exists.
  44. subprocess.check_call(f'borgmatic -v 2 --config {config_path}'.split(' '))
  45. output = subprocess.check_output(
  46. f'borgmatic --config {config_path} list --json'.split(' ')
  47. ).decode(sys.stdout.encoding)
  48. parsed_output = json.loads(output)
  49. assert len(parsed_output) == 1
  50. assert len(parsed_output[0]['archives']) == 1
  51. finally:
  52. os.chdir(original_working_directory)
  53. shutil.rmtree(temporary_directory)