170 lines
6.4 KiB
Python
170 lines
6.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Unit tests for backup_manager.py"""
|
|
import json
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from datetime import datetime, timedelta
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
|
|
from backup_manager import (
|
|
_resolve,
|
|
CronExpression,
|
|
StateDB,
|
|
is_excluded,
|
|
parse_schedule_md,
|
|
perform_backup,
|
|
rotate,
|
|
verify_snapshot,
|
|
)
|
|
|
|
|
|
class TestCronExpression(unittest.TestCase):
|
|
def test_every_minute(self):
|
|
self.assertTrue(CronExpression("* * * * *").matches(datetime(2026, 1, 1, 12, 34)))
|
|
|
|
def test_fixed_time(self):
|
|
cron = CronExpression("0 3 * * *")
|
|
self.assertTrue(cron.matches(datetime(2026, 1, 1, 3, 0)))
|
|
self.assertFalse(cron.matches(datetime(2026, 1, 1, 3, 1)))
|
|
self.assertFalse(cron.matches(datetime(2026, 1, 1, 4, 0)))
|
|
|
|
def test_step_values(self):
|
|
cron = CronExpression("*/15 * * * *")
|
|
self.assertTrue(cron.matches(datetime(2026, 1, 1, 0, 15)))
|
|
self.assertFalse(cron.matches(datetime(2026, 1, 1, 0, 16)))
|
|
|
|
def test_range(self):
|
|
cron = CronExpression("0 2 * * 1-5")
|
|
monday = datetime(2026, 1, 5, 2, 0)
|
|
sunday = datetime(2026, 1, 4, 2, 0)
|
|
self.assertTrue(cron.matches(monday))
|
|
self.assertFalse(cron.matches(sunday))
|
|
|
|
def test_invalid(self):
|
|
with self.assertRaises(ValueError):
|
|
CronExpression("0 0 * *")
|
|
with self.assertRaises(ValueError):
|
|
CronExpression("99 0 * * *")
|
|
|
|
|
|
class TestScheduleMd(unittest.TestCase):
|
|
def test_parse(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = Path(tmp) / "schedule.md"
|
|
path.write_text("# S\n\n- **cron:** `*/30 2 * * 1-5`\n")
|
|
self.assertEqual(parse_schedule_md(path).expression, "*/30 2 * * 1-5")
|
|
|
|
def test_missing_schedule(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = Path(tmp) / "schedule.md"
|
|
path.write_text("# nothing here\n")
|
|
with self.assertRaises(ValueError):
|
|
parse_schedule_md(path)
|
|
|
|
|
|
class TestHelpers(unittest.TestCase):
|
|
def test_is_excluded(self):
|
|
self.assertTrue(is_excluded(Path("a/.git/config"), [".git"]))
|
|
self.assertTrue(is_excluded(Path("a/x.tmp"), ["*.tmp"]))
|
|
self.assertFalse(is_excluded(Path("a/b.txt"), [".git", "*.tmp"]))
|
|
|
|
def test_state_db(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
db = StateDB(Path(tmp) / "state.db")
|
|
self.assertIsNone(db.get("src", "a"))
|
|
db.upsert("src", "a", 3, 1.5, "abc")
|
|
self.assertEqual(db.get("src", "a"), (3, 1.5, "abc"))
|
|
db.upsert("src", "a", 4, 2.5, "def")
|
|
self.assertEqual(db.get("src", "a"), (4, 2.5, "def"))
|
|
db.delete_missing("src", set())
|
|
self.assertIsNone(db.get("src", "a"))
|
|
db.close()
|
|
|
|
|
|
class TestBackupFlow(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.root = Path(self.tmp.name)
|
|
self.src = self.root / "src"
|
|
self.dst = self.root / "dst"
|
|
(self.src / "sub").mkdir(parents=True)
|
|
(self.src / "a.txt").write_text("hello")
|
|
(self.src / "sub" / "b.txt").write_text("world")
|
|
(self.src / "skip.tmp").write_text("tmp")
|
|
self.base = datetime(2026, 1, 1, 3, 0, 0)
|
|
self.config = _resolve(
|
|
{
|
|
"sources": [{"name": "s", "path": str(self.src), "exclude": ["*.tmp"]}],
|
|
"destination": str(self.dst),
|
|
"retention_days": 14,
|
|
"state_db": str(self.root / "state.db"),
|
|
"follow_symlinks": False,
|
|
},
|
|
self.root,
|
|
)
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
def test_first_run_copies_new_files(self):
|
|
snap = perform_backup(self.config, now=self.base)
|
|
self.assertTrue((snap / "s" / "a.txt").is_file())
|
|
self.assertTrue((snap / "s" / "sub" / "b.txt").is_file())
|
|
self.assertFalse((snap / "s" / "skip.tmp").exists())
|
|
manifest = json.loads((snap / "manifest.json").read_text())
|
|
self.assertEqual(manifest["stats"]["copied"], 2)
|
|
self.assertEqual(manifest["stats"]["linked"], 0)
|
|
|
|
def test_second_run_links_unchanged_and_copies_changed(self):
|
|
first = perform_backup(self.config, now=self.base)
|
|
(self.src / "a.txt").write_text("hello changed")
|
|
second = perform_backup(self.config, now=self.base + timedelta(minutes=1))
|
|
|
|
manifest = json.loads((second / "manifest.json").read_text())
|
|
actions = {f["relpath"]: f["action"] for f in manifest["sources"][0]["files"]}
|
|
self.assertEqual(actions["a.txt"], "copied")
|
|
self.assertEqual(actions["sub/b.txt"], "linked")
|
|
|
|
self.assertEqual((second / "s" / "a.txt").read_text(), "hello changed")
|
|
first_ino = os.stat(first / "s" / "sub" / "b.txt").st_ino
|
|
second_ino = os.stat(second / "s" / "sub" / "b.txt").st_ino
|
|
self.assertEqual(first_ino, second_ino)
|
|
|
|
def test_deleted_file_absent_from_new_snapshot(self):
|
|
perform_backup(self.config, now=self.base)
|
|
(self.src / "sub" / "b.txt").unlink()
|
|
second = perform_backup(self.config, now=self.base + timedelta(minutes=1))
|
|
self.assertFalse((second / "s" / "sub" / "b.txt").exists())
|
|
manifest = json.loads((second / "manifest.json").read_text())
|
|
self.assertEqual(manifest["sources"][0]["removed"], 1)
|
|
|
|
def test_rotation_removes_old_snapshots(self):
|
|
perform_backup(self.config, now=self.base - timedelta(days=30))
|
|
perform_backup(self.config, now=self.base)
|
|
remaining = sorted(p.name for p in self.dst.iterdir() if p.is_dir())
|
|
self.assertEqual(len(remaining), 1)
|
|
self.assertEqual(remaining[0], self.base.strftime("%Y-%m-%d_%H%M%S"))
|
|
|
|
def test_verify_snapshot_ok(self):
|
|
perform_backup(self.config, now=self.base)
|
|
self.assertEqual(verify_snapshot(self.config, None), 0)
|
|
|
|
def test_verify_detects_corruption(self):
|
|
snap = perform_backup(self.config, now=self.base)
|
|
(snap / "s" / "a.txt").write_text("tampered")
|
|
self.assertEqual(verify_snapshot(self.config, snap.name), 1)
|
|
|
|
def test_rotate_helper(self):
|
|
old = self.dst / "2020-01-01_000000"
|
|
old.mkdir(parents=True)
|
|
self.assertEqual(rotate(self.dst, 7, self.base), ["2020-01-01_000000"])
|
|
self.assertFalse(old.exists())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|