test_database.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. - name: all
  29. hostname: postgresql
  30. username: postgres
  31. password: test
  32. mysql_databases:
  33. - name: test
  34. hostname: mysql
  35. username: root
  36. password: test
  37. - name: all
  38. hostname: mysql
  39. username: root
  40. password: test
  41. '''.format(
  42. config_path, repository_path, borgmatic_source_directory
  43. )
  44. config_file = open(config_path, 'w')
  45. config_file.write(config)
  46. config_file.close()
  47. def test_database_dump_and_restore():
  48. # Create a Borg repository.
  49. temporary_directory = tempfile.mkdtemp()
  50. repository_path = os.path.join(temporary_directory, 'test.borg')
  51. borgmatic_source_directory = os.path.join(temporary_directory, '.borgmatic')
  52. original_working_directory = os.getcwd()
  53. try:
  54. config_path = os.path.join(temporary_directory, 'test.yaml')
  55. write_configuration(config_path, repository_path, borgmatic_source_directory)
  56. subprocess.check_call(
  57. 'borgmatic -v 2 --config {} init --encryption repokey'.format(config_path).split(' ')
  58. )
  59. # Run borgmatic to generate a backup archive including a database dump
  60. subprocess.check_call('borgmatic create --config {} -v 2'.format(config_path).split(' '))
  61. # Get the created archive name.
  62. output = subprocess.check_output(
  63. 'borgmatic --config {} list --json'.format(config_path).split(' ')
  64. ).decode(sys.stdout.encoding)
  65. parsed_output = json.loads(output)
  66. assert len(parsed_output) == 1
  67. assert len(parsed_output[0]['archives']) == 1
  68. archive_name = parsed_output[0]['archives'][0]['archive']
  69. # Restore the database from the archive.
  70. subprocess.check_call(
  71. 'borgmatic --config {} restore --archive {}'.format(config_path, archive_name).split(
  72. ' '
  73. )
  74. )
  75. finally:
  76. os.chdir(original_working_directory)
  77. shutil.rmtree(temporary_directory)