test_database.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import json
  2. import os
  3. import shutil
  4. import subprocess
  5. import sys
  6. import tempfile
  7. def write_configuration(config_path, repository_path, borgmatic_source_directory):
  8. '''
  9. Write out borgmatic configuration into a file at the config path. Set the options so as to work
  10. for testing. This includes injecting the given repository path, borgmatic source directory for
  11. storing database dumps, and encryption passphrase.
  12. '''
  13. config = '''
  14. location:
  15. source_directories:
  16. - {}
  17. repositories:
  18. - {}
  19. borgmatic_source_directory: {}
  20. storage:
  21. encryption_passphrase: "test"
  22. hooks:
  23. postgresql_databases:
  24. - name: test
  25. hostname: postgresql
  26. username: postgres
  27. password: test
  28. mysql_databases:
  29. - name: test
  30. hostname: mysql
  31. username: root
  32. password: test
  33. '''.format(
  34. config_path, repository_path, borgmatic_source_directory
  35. )
  36. config_file = open(config_path, 'w')
  37. config_file.write(config)
  38. config_file.close()
  39. def test_database_dump_and_restore():
  40. # Create a Borg repository.
  41. temporary_directory = tempfile.mkdtemp()
  42. repository_path = os.path.join(temporary_directory, 'test.borg')
  43. borgmatic_source_directory = os.path.join(temporary_directory, '.borgmatic')
  44. original_working_directory = os.getcwd()
  45. try:
  46. config_path = os.path.join(temporary_directory, 'test.yaml')
  47. write_configuration(config_path, repository_path, borgmatic_source_directory)
  48. subprocess.check_call(
  49. 'borgmatic -v 2 --config {} init --encryption repokey'.format(config_path).split(' ')
  50. )
  51. # Run borgmatic to generate a backup archive including a database dump
  52. subprocess.check_call('borgmatic create --config {} -v 2'.format(config_path).split(' '))
  53. # Get the created archive name.
  54. output = subprocess.check_output(
  55. 'borgmatic --config {} list --json'.format(config_path).split(' ')
  56. ).decode(sys.stdout.encoding)
  57. parsed_output = json.loads(output)
  58. assert len(parsed_output) == 1
  59. assert len(parsed_output[0]['archives']) == 1
  60. archive_name = parsed_output[0]['archives'][0]['archive']
  61. # Restore the database from the archive.
  62. subprocess.check_call(
  63. 'borgmatic --config {} restore --archive {}'.format(config_path, archive_name).split(
  64. ' '
  65. )
  66. )
  67. finally:
  68. os.chdir(original_working_directory)
  69. shutil.rmtree(temporary_directory)