test_borgmatic.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. finally:
  45. shutil.rmtree(temporary_directory)