Files
backup-docker-to-local/tests/unit/backup/test_app_volume_failure.py
T

119 lines
4.4 KiB
Python
Raw Normal View History

from __future__ import annotations
import contextlib
import io
import json
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from baudolo.backup import app
from baudolo.backup.dumps import VolumeOutcome
from baudolo.backup.shell import BackupError
from baudolo.backup.volume import Backing
from baudolo.generation import MANIFEST_FILE
from . import REQUIRED_PAIRS
BROKEN = "broken"
LATER = "later"
PROBE_ERROR = "docker exec probe exited 1"
def drive(backups_dir: str, dump_error: Exception) -> dict:
"""Run main() over a failing volume followed by a healthy one.
Args:
backups_dir: real directory the generation is written into.
dump_error: what the dump step raises for the first volume, after
leaving a partial file in its directory.
Returns:
``rc`` main's return value, ``copied`` the volumes whose files were
copied, ``stamped`` the generation's entries and manifest volumes at
stamp time, ``stderr`` what main wrote there.
"""
argv = ["baudolo"]
for flag, value in REQUIRED_PAIRS:
argv += [flag, backups_dir if flag == "--backups-dir" else value]
copied: list[str] = []
stamped: dict = {}
def dumps(*, containers, vol_dir, databases_df, database_containers):
if Path(vol_dir).name == BROKEN:
(Path(vol_dir) / "partial.sql.gz").write_bytes(b"half")
raise dump_error
return VolumeOutcome(database=False, dumped=False)
def copy(versions_dir, volume_name, volume_dir, *, authoritative, source):
copied.append(volume_name)
def stamp(version_dir: str) -> None:
stamped["entries"] = sorted(p.name for p in Path(version_dir).iterdir())
manifest = json.loads((Path(version_dir) / MANIFEST_FILE).read_text())
stamped["volumes"] = sorted(manifest["volumes"])
stderr = io.StringIO()
with (
mock.patch("sys.argv", argv),
mock.patch.object(app, "get_machine_id", return_value="machine"),
mock.patch.object(app, "load_databases_df", return_value=None),
mock.patch.object(app, "docker_volume_names", return_value=[BROKEN, LATER]),
mock.patch.object(app, "containers_using_volume", return_value=["c"]),
mock.patch.object(app, "volume_is_fully_ignored", return_value=False),
mock.patch.object(app, "backup_dumps_for_volume", side_effect=dumps),
mock.patch.object(app, "inspect_backing", return_value=Backing("/data")),
mock.patch.object(app, "requires_stop", return_value=False),
mock.patch.object(app, "backup_volume", side_effect=copy),
mock.patch.object(app, "stamp_directory", side_effect=stamp),
mock.patch.object(app, "handle_docker_compose_services"),
contextlib.redirect_stdout(io.StringIO()),
contextlib.redirect_stderr(stderr),
):
rc = app.main()
return {
"rc": rc,
"copied": copied,
"stamped": stamped,
"stderr": stderr.getvalue(),
}
class TestVolumeFailure(unittest.TestCase):
def setUp(self) -> None:
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.backups_dir = tmp.name
def run_with_probe_failure(self) -> dict:
return drive(self.backups_dir, BackupError(PROBE_ERROR, returncode=1))
def test_the_run_exits_non_zero(self) -> None:
self.assertNotEqual(self.run_with_probe_failure()["rc"], 0)
def test_a_later_volume_is_still_copied(self) -> None:
self.assertEqual(self.run_with_probe_failure()["copied"], [LATER])
def test_the_stamp_covers_no_directory_of_the_failed_volume(self) -> None:
entries = self.run_with_probe_failure()["stamped"]["entries"]
self.assertNotIn(BROKEN, entries)
self.assertIn(LATER, entries)
def test_the_manifest_lists_only_the_volume_that_succeeded(self) -> None:
self.assertEqual(self.run_with_probe_failure()["stamped"]["volumes"], [LATER])
def test_the_failure_is_logged_with_volume_and_error(self) -> None:
stderr = self.run_with_probe_failure()["stderr"]
self.assertIn(BROKEN, stderr)
self.assertIn(PROBE_ERROR, stderr)
def test_an_error_other_than_backup_error_still_aborts_the_run(self) -> None:
with self.assertRaises(RuntimeError):
drive(self.backups_dir, RuntimeError("bug"))
self.assertEqual(list(Path(self.backups_dir).rglob(MANIFEST_FILE)), [])
if __name__ == "__main__":
unittest.main()