test_borgmatic.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. import logging
  2. import subprocess
  3. from flexmock import flexmock
  4. import borgmatic.hooks.command
  5. from borgmatic.commands import borgmatic as module
  6. def test_run_configuration_runs_actions_for_each_repository():
  7. flexmock(module.borg_environment).should_receive('initialize')
  8. expected_results = [flexmock(), flexmock()]
  9. flexmock(module).should_receive('run_actions').and_return(expected_results[:1]).and_return(
  10. expected_results[1:]
  11. )
  12. config = {'location': {'repositories': ['foo', 'bar']}}
  13. arguments = {'global': flexmock(monitoring_verbosity=1)}
  14. results = list(module.run_configuration('test.yaml', config, arguments))
  15. assert results == expected_results
  16. def test_run_configuration_calls_hooks_for_prune_action():
  17. flexmock(module.borg_environment).should_receive('initialize')
  18. flexmock(module.command).should_receive('execute_hook').twice()
  19. flexmock(module.dispatch).should_receive('call_hooks').at_least().twice()
  20. flexmock(module).should_receive('run_actions').and_return([])
  21. config = {'location': {'repositories': ['foo']}}
  22. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'prune': flexmock()}
  23. list(module.run_configuration('test.yaml', config, arguments))
  24. def test_run_configuration_executes_and_calls_hooks_for_create_action():
  25. flexmock(module.borg_environment).should_receive('initialize')
  26. flexmock(module.command).should_receive('execute_hook').twice()
  27. flexmock(module.dispatch).should_receive('call_hooks').at_least().twice()
  28. flexmock(module).should_receive('run_actions').and_return([])
  29. config = {'location': {'repositories': ['foo']}}
  30. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  31. list(module.run_configuration('test.yaml', config, arguments))
  32. def test_run_configuration_calls_hooks_for_check_action():
  33. flexmock(module.borg_environment).should_receive('initialize')
  34. flexmock(module.command).should_receive('execute_hook').twice()
  35. flexmock(module.dispatch).should_receive('call_hooks').at_least().twice()
  36. flexmock(module).should_receive('run_actions').and_return([])
  37. config = {'location': {'repositories': ['foo']}}
  38. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'check': flexmock()}
  39. list(module.run_configuration('test.yaml', config, arguments))
  40. def test_run_configuration_does_not_trigger_hooks_for_list_action():
  41. flexmock(module.borg_environment).should_receive('initialize')
  42. flexmock(module.command).should_receive('execute_hook').never()
  43. flexmock(module.dispatch).should_receive('call_hooks').never()
  44. flexmock(module).should_receive('run_actions').and_return([])
  45. config = {'location': {'repositories': ['foo']}}
  46. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'list': flexmock()}
  47. list(module.run_configuration('test.yaml', config, arguments))
  48. def test_run_configuration_logs_actions_error():
  49. flexmock(module.borg_environment).should_receive('initialize')
  50. flexmock(module.command).should_receive('execute_hook')
  51. flexmock(module.dispatch).should_receive('call_hooks')
  52. expected_results = [flexmock()]
  53. flexmock(module).should_receive('make_error_log_records').and_return(expected_results)
  54. flexmock(module).should_receive('run_actions').and_raise(OSError)
  55. config = {'location': {'repositories': ['foo']}}
  56. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  57. results = list(module.run_configuration('test.yaml', config, arguments))
  58. assert results == expected_results
  59. def test_run_configuration_logs_pre_hook_error():
  60. flexmock(module.borg_environment).should_receive('initialize')
  61. flexmock(module.command).should_receive('execute_hook').and_raise(OSError).and_return(None)
  62. expected_results = [flexmock()]
  63. flexmock(module).should_receive('make_error_log_records').and_return(expected_results)
  64. flexmock(module).should_receive('run_actions').never()
  65. config = {'location': {'repositories': ['foo']}}
  66. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  67. results = list(module.run_configuration('test.yaml', config, arguments))
  68. assert results == expected_results
  69. def test_run_configuration_bails_for_pre_hook_soft_failure():
  70. flexmock(module.borg_environment).should_receive('initialize')
  71. error = subprocess.CalledProcessError(borgmatic.hooks.command.SOFT_FAIL_EXIT_CODE, 'try again')
  72. flexmock(module.command).should_receive('execute_hook').and_raise(error).and_return(None)
  73. flexmock(module).should_receive('make_error_log_records').never()
  74. flexmock(module).should_receive('run_actions').never()
  75. config = {'location': {'repositories': ['foo']}}
  76. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  77. results = list(module.run_configuration('test.yaml', config, arguments))
  78. assert results == []
  79. def test_run_configuration_logs_post_hook_error():
  80. flexmock(module.borg_environment).should_receive('initialize')
  81. flexmock(module.command).should_receive('execute_hook').and_return(None).and_raise(
  82. OSError
  83. ).and_return(None)
  84. flexmock(module.dispatch).should_receive('call_hooks')
  85. expected_results = [flexmock()]
  86. flexmock(module).should_receive('make_error_log_records').and_return(expected_results)
  87. flexmock(module).should_receive('run_actions').and_return([])
  88. config = {'location': {'repositories': ['foo']}}
  89. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  90. results = list(module.run_configuration('test.yaml', config, arguments))
  91. assert results == expected_results
  92. def test_run_configuration_bails_for_post_hook_soft_failure():
  93. flexmock(module.borg_environment).should_receive('initialize')
  94. error = subprocess.CalledProcessError(borgmatic.hooks.command.SOFT_FAIL_EXIT_CODE, 'try again')
  95. flexmock(module.command).should_receive('execute_hook').and_return(None).and_raise(
  96. error
  97. ).and_return(None)
  98. flexmock(module.dispatch).should_receive('call_hooks')
  99. flexmock(module).should_receive('make_error_log_records').never()
  100. flexmock(module).should_receive('run_actions').and_return([])
  101. config = {'location': {'repositories': ['foo']}}
  102. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  103. results = list(module.run_configuration('test.yaml', config, arguments))
  104. assert results == []
  105. def test_run_configuration_logs_on_error_hook_error():
  106. flexmock(module.borg_environment).should_receive('initialize')
  107. flexmock(module.command).should_receive('execute_hook').and_raise(OSError)
  108. expected_results = [flexmock(), flexmock()]
  109. flexmock(module).should_receive('make_error_log_records').and_return(
  110. expected_results[:1]
  111. ).and_return(expected_results[1:])
  112. flexmock(module).should_receive('run_actions').and_raise(OSError)
  113. config = {'location': {'repositories': ['foo']}}
  114. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  115. results = list(module.run_configuration('test.yaml', config, arguments))
  116. assert results == expected_results
  117. def test_run_configuration_bails_for_on_error_hook_soft_failure():
  118. flexmock(module.borg_environment).should_receive('initialize')
  119. error = subprocess.CalledProcessError(borgmatic.hooks.command.SOFT_FAIL_EXIT_CODE, 'try again')
  120. flexmock(module.command).should_receive('execute_hook').and_return(None).and_raise(error)
  121. expected_results = [flexmock()]
  122. flexmock(module).should_receive('make_error_log_records').and_return(expected_results)
  123. flexmock(module).should_receive('run_actions').and_raise(OSError)
  124. config = {'location': {'repositories': ['foo']}}
  125. arguments = {'global': flexmock(monitoring_verbosity=1, dry_run=False), 'create': flexmock()}
  126. results = list(module.run_configuration('test.yaml', config, arguments))
  127. assert results == expected_results
  128. def test_load_configurations_collects_parsed_configurations():
  129. configuration = flexmock()
  130. other_configuration = flexmock()
  131. flexmock(module.validate).should_receive('parse_configuration').and_return(
  132. configuration
  133. ).and_return(other_configuration)
  134. configs, logs = tuple(module.load_configurations(('test.yaml', 'other.yaml')))
  135. assert configs == {'test.yaml': configuration, 'other.yaml': other_configuration}
  136. assert logs == []
  137. def test_load_configurations_logs_critical_for_parse_error():
  138. flexmock(module.validate).should_receive('parse_configuration').and_raise(ValueError)
  139. configs, logs = tuple(module.load_configurations(('test.yaml',)))
  140. assert configs == {}
  141. assert {log.levelno for log in logs} == {logging.CRITICAL}
  142. def test_log_record_does_not_raise():
  143. module.log_record(levelno=1, foo='bar', baz='quux')
  144. def test_log_record_with_suppress_does_not_raise():
  145. module.log_record(levelno=1, foo='bar', baz='quux', suppress_log=True)
  146. def test_make_error_log_records_generates_output_logs_for_message_only():
  147. flexmock(module).should_receive('log_record').replace_with(dict)
  148. logs = tuple(module.make_error_log_records('Error'))
  149. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  150. def test_make_error_log_records_generates_output_logs_for_called_process_error():
  151. flexmock(module).should_receive('log_record').replace_with(dict)
  152. flexmock(module.logger).should_receive('getEffectiveLevel').and_return(logging.WARNING)
  153. logs = tuple(
  154. module.make_error_log_records(
  155. 'Error', subprocess.CalledProcessError(1, 'ls', 'error output')
  156. )
  157. )
  158. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  159. assert any(log for log in logs if 'error output' in str(log))
  160. def test_make_error_log_records_generates_logs_for_value_error():
  161. flexmock(module).should_receive('log_record').replace_with(dict)
  162. logs = tuple(module.make_error_log_records('Error', ValueError()))
  163. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  164. def test_make_error_log_records_generates_logs_for_os_error():
  165. flexmock(module).should_receive('log_record').replace_with(dict)
  166. logs = tuple(module.make_error_log_records('Error', OSError()))
  167. assert {log['levelno'] for log in logs} == {logging.CRITICAL}
  168. def test_make_error_log_records_generates_nothing_for_other_error():
  169. flexmock(module).should_receive('log_record').replace_with(dict)
  170. logs = tuple(module.make_error_log_records('Error', KeyError()))
  171. assert logs == ()
  172. def test_get_local_path_uses_configuration_value():
  173. assert module.get_local_path({'test.yaml': {'location': {'local_path': 'borg1'}}}) == 'borg1'
  174. def test_get_local_path_without_location_defaults_to_borg():
  175. assert module.get_local_path({'test.yaml': {}}) == 'borg'
  176. def test_get_local_path_without_local_path_defaults_to_borg():
  177. assert module.get_local_path({'test.yaml': {'location': {}}}) == 'borg'
  178. def test_collect_configuration_run_summary_logs_info_for_success():
  179. flexmock(module.command).should_receive('execute_hook').never()
  180. flexmock(module).should_receive('run_configuration').and_return([])
  181. arguments = {}
  182. logs = tuple(
  183. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  184. )
  185. assert {log.levelno for log in logs} == {logging.INFO}
  186. def test_collect_configuration_run_summary_executes_hooks_for_create():
  187. flexmock(module).should_receive('run_configuration').and_return([])
  188. arguments = {'create': flexmock(), 'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  189. logs = tuple(
  190. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  191. )
  192. assert {log.levelno for log in logs} == {logging.INFO}
  193. def test_collect_configuration_run_summary_logs_info_for_success_with_extract():
  194. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  195. flexmock(module).should_receive('run_configuration').and_return([])
  196. arguments = {'extract': flexmock(repository='repo')}
  197. logs = tuple(
  198. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  199. )
  200. assert {log.levelno for log in logs} == {logging.INFO}
  201. def test_collect_configuration_run_summary_logs_extract_with_repository_error():
  202. flexmock(module.validate).should_receive('guard_configuration_contains_repository').and_raise(
  203. ValueError
  204. )
  205. expected_logs = (flexmock(),)
  206. flexmock(module).should_receive('make_error_log_records').and_return(expected_logs)
  207. arguments = {'extract': flexmock(repository='repo')}
  208. logs = tuple(
  209. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  210. )
  211. assert logs == expected_logs
  212. def test_collect_configuration_run_summary_logs_info_for_success_with_mount():
  213. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  214. flexmock(module).should_receive('run_configuration').and_return([])
  215. arguments = {'mount': flexmock(repository='repo')}
  216. logs = tuple(
  217. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  218. )
  219. assert {log.levelno for log in logs} == {logging.INFO}
  220. def test_collect_configuration_run_summary_logs_mount_with_repository_error():
  221. flexmock(module.validate).should_receive('guard_configuration_contains_repository').and_raise(
  222. ValueError
  223. )
  224. expected_logs = (flexmock(),)
  225. flexmock(module).should_receive('make_error_log_records').and_return(expected_logs)
  226. arguments = {'mount': flexmock(repository='repo')}
  227. logs = tuple(
  228. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  229. )
  230. assert logs == expected_logs
  231. def test_collect_configuration_run_summary_logs_missing_configs_error():
  232. arguments = {'global': flexmock(config_paths=[])}
  233. expected_logs = (flexmock(),)
  234. flexmock(module).should_receive('make_error_log_records').and_return(expected_logs)
  235. logs = tuple(module.collect_configuration_run_summary_logs({}, arguments=arguments))
  236. assert logs == expected_logs
  237. def test_collect_configuration_run_summary_logs_pre_hook_error():
  238. flexmock(module.command).should_receive('execute_hook').and_raise(ValueError)
  239. expected_logs = (flexmock(),)
  240. flexmock(module).should_receive('make_error_log_records').and_return(expected_logs)
  241. arguments = {'create': flexmock(), 'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  242. logs = tuple(
  243. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  244. )
  245. assert logs == expected_logs
  246. def test_collect_configuration_run_summary_logs_post_hook_error():
  247. flexmock(module.command).should_receive('execute_hook').and_return(None).and_raise(ValueError)
  248. flexmock(module).should_receive('run_configuration').and_return([])
  249. expected_logs = (flexmock(),)
  250. flexmock(module).should_receive('make_error_log_records').and_return(expected_logs)
  251. arguments = {'create': flexmock(), 'global': flexmock(monitoring_verbosity=1, dry_run=False)}
  252. logs = tuple(
  253. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  254. )
  255. assert expected_logs[0] in logs
  256. def test_collect_configuration_run_summary_logs_for_list_with_archive_and_repository_error():
  257. flexmock(module.validate).should_receive('guard_configuration_contains_repository').and_raise(
  258. ValueError
  259. )
  260. expected_logs = (flexmock(),)
  261. flexmock(module).should_receive('make_error_log_records').and_return(expected_logs)
  262. arguments = {'list': flexmock(repository='repo', archive='test')}
  263. logs = tuple(
  264. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  265. )
  266. assert logs == expected_logs
  267. def test_collect_configuration_run_summary_logs_info_for_success_with_list():
  268. flexmock(module).should_receive('run_configuration').and_return([])
  269. arguments = {'list': flexmock(repository='repo', archive=None)}
  270. logs = tuple(
  271. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  272. )
  273. assert {log.levelno for log in logs} == {logging.INFO}
  274. def test_collect_configuration_run_summary_logs_run_configuration_error():
  275. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  276. flexmock(module).should_receive('run_configuration').and_return(
  277. [logging.makeLogRecord(dict(levelno=logging.CRITICAL, levelname='CRITICAL', msg='Error'))]
  278. )
  279. flexmock(module).should_receive('make_error_log_records').and_return([])
  280. arguments = {}
  281. logs = tuple(
  282. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  283. )
  284. assert {log.levelno for log in logs} == {logging.CRITICAL}
  285. def test_collect_configuration_run_summary_logs_run_umount_error():
  286. flexmock(module.validate).should_receive('guard_configuration_contains_repository')
  287. flexmock(module).should_receive('run_configuration').and_return([])
  288. flexmock(module.borg_umount).should_receive('unmount_archive').and_raise(OSError)
  289. flexmock(module).should_receive('make_error_log_records').and_return(
  290. [logging.makeLogRecord(dict(levelno=logging.CRITICAL, levelname='CRITICAL', msg='Error'))]
  291. )
  292. arguments = {'umount': flexmock(mount_point='/mnt')}
  293. logs = tuple(
  294. module.collect_configuration_run_summary_logs({'test.yaml': {}}, arguments=arguments)
  295. )
  296. assert {log.levelno for log in logs} == {logging.INFO, logging.CRITICAL}
  297. def test_collect_configuration_run_summary_logs_outputs_merged_json_results():
  298. flexmock(module).should_receive('run_configuration').and_return(['foo', 'bar']).and_return(
  299. ['baz']
  300. )
  301. flexmock(module.sys.stdout).should_receive('write').with_args('["foo", "bar", "baz"]').once()
  302. arguments = {}
  303. tuple(
  304. module.collect_configuration_run_summary_logs(
  305. {'test.yaml': {}, 'test2.yaml': {}}, arguments=arguments
  306. )
  307. )