test_borgmatic.py 18 KB

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