test_borgmatic.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 injecting the given repository path).
  11. '''
  12. subprocess.check_call(f'generate-borgmatic-config --destination {config_path}'.split(' '))
  13. config = (
  14. open(config_path)
  15. .read()
  16. .replace('user@backupserver:sourcehostname.borg', repository_path)
  17. .replace('- /home', f'- {config_path}')
  18. .replace('- /etc', '')
  19. .replace('- /var/log/syslog*', '')
  20. )
  21. config_file = open(config_path, 'w')
  22. config_file.write(config)
  23. config_file.close()
  24. def test_borgmatic_command():
  25. # Create a Borg repository.
  26. temporary_directory = tempfile.mkdtemp()
  27. repository_path = os.path.join(temporary_directory, 'test.borg')
  28. try:
  29. subprocess.check_call(
  30. f'borg init --encryption repokey {repository_path}'.split(' '),
  31. env={'BORG_PASSPHRASE': '', **os.environ},
  32. )
  33. config_path = os.path.join(temporary_directory, 'test.yaml')
  34. generate_configuration(config_path, repository_path)
  35. # Run borgmatic to generate a backup archive, and then list it to make sure it exists.
  36. subprocess.check_call(f'borgmatic --config {config_path}'.split(' '))
  37. output = subprocess.check_output(
  38. f'borgmatic --config {config_path} --list --json'.split(' '),
  39. encoding=sys.stdout.encoding,
  40. )
  41. parsed_output = json.loads(output)
  42. assert len(parsed_output) == 1
  43. assert len(parsed_output[0]['archives']) == 1
  44. # Also exercise the info flag.
  45. output = subprocess.check_output(
  46. f'borgmatic --config {config_path} --info --json'.split(' '),
  47. encoding=sys.stdout.encoding,
  48. )
  49. parsed_output = json.loads(output)
  50. assert len(parsed_output) == 1
  51. assert 'repository' in parsed_output[0]
  52. finally:
  53. shutil.rmtree(temporary_directory)