test_container.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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, secrets_directory):
  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 passphrase loaded from container secrets in the given secrets
  12. directory.
  13. '''
  14. subprocess.check_call(f'borgmatic config generate --destination {config_path}'.split(' '))
  15. config = (
  16. open(config_path)
  17. .read()
  18. .replace('ssh://user@backupserver/./sourcehostname.borg', repository_path)
  19. .replace('- path: /mnt/backup', '')
  20. .replace('label: local', '')
  21. .replace('- /home/user/path with spaces', '')
  22. .replace('- /home', f'- {config_path}')
  23. .replace('- /etc', '')
  24. .replace('- /var/log/syslog*', '')
  25. + '\nencryption_passphrase: "{credential container mysecret}"'
  26. + f'\ncontainer:\n secrets_directory: {secrets_directory}'
  27. )
  28. config_file = open(config_path, 'w')
  29. config_file.write(config)
  30. config_file.close()
  31. def test_container_secret():
  32. # Create a Borg repository.
  33. temporary_directory = tempfile.mkdtemp()
  34. repository_path = os.path.join(temporary_directory, 'test.borg')
  35. original_working_directory = os.getcwd()
  36. os.chdir(temporary_directory)
  37. try:
  38. config_path = os.path.join(temporary_directory, 'test.yaml')
  39. generate_configuration(config_path, repository_path, secrets_directory=temporary_directory)
  40. secret_path = os.path.join(temporary_directory, 'mysecret')
  41. with open(secret_path, 'w') as secret_file:
  42. secret_file.write('test')
  43. subprocess.check_call(
  44. f'borgmatic -v 2 --config {config_path} repo-create --encryption repokey'.split(' '),
  45. )
  46. # Run borgmatic to generate a backup archive, and then list it to make sure it exists.
  47. subprocess.check_call(
  48. f'borgmatic --config {config_path}'.split(' '),
  49. )
  50. output = subprocess.check_output(
  51. f'borgmatic --config {config_path} list --json'.split(' '),
  52. ).decode(sys.stdout.encoding)
  53. parsed_output = json.loads(output)
  54. assert len(parsed_output) == 1
  55. assert len(parsed_output[0]['archives']) == 1
  56. finally:
  57. os.chdir(original_working_directory)
  58. shutil.rmtree(temporary_directory)