"""Unit tests for RetentionEngine and lifecycle pruning.""" from contextlib import redirect_stdout, redirect_stderr import datetime import io import json import os import shutil import tempfile import unittest from tests.helpers import env_override from linux_backuper.cli import main from linux_backuper.core.archiver import SnapshotArchiver from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_GENERIC_ERROR from linux_backuper.core.retention import RetentionEngine, parse_snapshot_datetime from linux_backuper.models import SnapshotManifest class TestRetentionEngine(unittest.TestCase): def setUp(self): self.test_dir = tempfile.mkdtemp(prefix="test_retention_") self.backup_dir = os.path.join(self.test_dir, "backups") os.makedirs(self.backup_dir, exist_ok=True) def tearDown(self): shutil.rmtree(self.test_dir, ignore_errors=True) def _create_synthetic_manifest(self, snap_id: str, dt_str: str) -> SnapshotManifest: return SnapshotManifest( schema_version="1.0", snapshot_id=snap_id, created_at=dt_str, hostname="testhost", profile="quick", compression="gzip", os={}, package_manager="dpkg", package_count=0, included_paths=["/etc"], stats={"file_count": 10, "uncompressed_bytes": 1000, "compressed_bytes": 500}, files_sha256={} ) def test_keep_last(self): # 5 snapshots snaps = [ self._create_synthetic_manifest(f"snap_{i}", f"2026-10-0{i+1}T10:00:00Z") for i in range(5) ] retention = RetentionEngine(keep_last=2) kept, pruned = retention.calculate_prune_set(snaps) self.assertEqual(len(kept), 2) self.assertEqual(len(pruned), 3) self.assertEqual([s.snapshot_id for s in kept], ["snap_4", "snap_3"]) self.assertEqual([s.snapshot_id for s in pruned], ["snap_0", "snap_1", "snap_2"]) def test_keep_daily(self): # Multiple snapshots on same days snaps = [ # Day 1: 3 snapshots self._create_synthetic_manifest("d1_1", "2026-10-01T08:00:00Z"), self._create_synthetic_manifest("d1_2", "2026-10-01T12:00:00Z"), self._create_synthetic_manifest("d1_3", "2026-10-01T20:00:00Z"), # Day 2: 2 snapshots self._create_synthetic_manifest("d2_1", "2026-10-02T10:00:00Z"), self._create_synthetic_manifest("d2_2", "2026-10-02T22:00:00Z"), # Day 3: 1 snapshot self._create_synthetic_manifest("d3_1", "2026-10-03T15:00:00Z"), ] # Keep 2 daily retention = RetentionEngine(keep_daily=2) kept, pruned = retention.calculate_prune_set(snaps) # Should keep newest of Day 3 (d3_1) and newest of Day 2 (d2_2) kept_ids = [s.snapshot_id for s in kept] self.assertEqual(len(kept_ids), 2) self.assertIn("d3_1", kept_ids) self.assertIn("d2_2", kept_ids) self.assertEqual(len(pruned), 4) def test_keep_weekly_and_monthly(self): snaps = [ # Month 1, Week 1 self._create_synthetic_manifest("m1_w1", "2026-08-03T10:00:00Z"), # Month 1, Week 2 self._create_synthetic_manifest("m1_w2", "2026-08-10T10:00:00Z"), # Month 2, Week 1 self._create_synthetic_manifest("m2_w1", "2026-09-07T10:00:00Z"), # Month 2, Week 2 self._create_synthetic_manifest("m2_w2", "2026-09-14T10:00:00Z"), # Month 3, Week 1 self._create_synthetic_manifest("m3_w1", "2026-10-05T10:00:00Z"), ] # Keep 1 monthly retention = RetentionEngine(keep_monthly=1) kept, pruned = retention.calculate_prune_set(snaps) self.assertEqual(len(kept), 1) self.assertEqual(kept[0].snapshot_id, "m3_w1") def test_execute_prune_dry_run_vs_live(self): archiver = SnapshotArchiver(target_dir=self.backup_dir) # Create 3 real tiny snapshot archives on disk snap_ids = [] manifests = [] for i in range(3): s_id = f"snap_real_{i}" snap_ids.append(s_id) dummy_file = os.path.join(self.test_dir, f"file_{i}.txt") with open(dummy_file, "w") as f: f.write(f"content {i}\n") entries, sha, uncomp, _ = archiver.collect_file_list([dummy_file]) m = self._create_synthetic_manifest(s_id, f"2026-10-0{i+1}T12:00:00Z") m.files_sha256 = sha archiver.create_snapshot_archive(s_id, m, entries) manifests.append(m) # Verify all 3 exist for s_id in snap_ids: path = SnapshotArchiver.resolve_archive_path(self.backup_dir, s_id) self.assertTrue(os.path.isfile(path)) retention = RetentionEngine(keep_last=1) kept, pruned = retention.calculate_prune_set(manifests) self.assertEqual(len(pruned), 2) # Test dry-run: files must NOT be deleted pid_file = os.path.join(self.test_dir, "test.pid") results = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=True, pid_path=pid_file) self.assertEqual(len(results), 2) for r in results: self.assertEqual(r["action"], "would_delete") self.assertTrue(os.path.isfile(r["archive_path"])) # Test live prune: files MUST be deleted with env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): results_live = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=False, pid_path=pid_file) self.assertEqual(len(results_live), 2) for r in results_live: self.assertEqual(r["action"], "deleted") self.assertFalse(os.path.isfile(r["archive_path"])) # Kept archive must still exist kept_path = SnapshotArchiver.resolve_archive_path(self.backup_dir, kept[0].snapshot_id) self.assertTrue(os.path.isfile(kept_path)) def test_cli_prune_command(self): archiver = SnapshotArchiver(target_dir=self.backup_dir) # Create 2 archives for i in range(2): s_id = f"cli_snap_{i}" f_path = os.path.join(self.test_dir, f"f_{i}.txt") with open(f_path, "w") as f: f.write(f"val {i}") entries, sha, uncomp, _ = archiver.collect_file_list([f_path]) m = self._create_synthetic_manifest(s_id, f"2026-10-0{i+1}T12:00:00Z") m.files_sha256 = sha archiver.create_snapshot_archive(s_id, m, entries) # 1. Prune without rules -> error stdout = io.StringIO() with redirect_stderr(stdout): code = main(["prune", "--target-dir", self.backup_dir]) self.assertEqual(code, EXIT_GENERIC_ERROR) # 2. Prune dry-run (default without --force) stdout_dry = io.StringIO() with redirect_stdout(stdout_dry): code = main(["prune", "--keep-last", "1", "--target-dir", self.backup_dir, "--json"]) self.assertEqual(code, EXIT_SUCCESS) data = json.loads(stdout_dry.getvalue().strip()) self.assertEqual(data["mode"], "dry-run") self.assertEqual(data["kept_count"], 1) self.assertEqual(data["pruned_count"], 1) # 3. Prune with --force pid_file = os.path.join(self.test_dir, "prune_test.pid") stdout_live = io.StringIO() with redirect_stdout(stdout_live), env_override({"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): code = main([ "prune", "--keep-last", "1", "--force", "--target-dir", self.backup_dir, "--pid-path", pid_file, "--json" ]) self.assertEqual(code, EXIT_SUCCESS) data_live = json.loads(stdout_live.getvalue().strip()) self.assertEqual(data_live["mode"], "live") self.assertEqual(data_live["pruned"][0]["action"], "deleted") if __name__ == "__main__": unittest.main()