"""Comprehensive tests for ``muse gc``. Covers: - Unit: run_gc core logic (reachable vs unreachable objects) - Integration: gc cleans up orphaned objects after commits - E2E: full CLI via CliRunner (--dry-run, --verbose, --format json) - Security: only objects dir affected, no path traversal - Stress: gc with many orphaned objects """ from __future__ import annotations import datetime import json import pathlib import pytest from tests.cli_test_helper import CliRunner from muse.core.types import blob_id, fake_id, short_id from muse.core.object_store import object_path from muse.core.paths import heads_dir, muse_dir cli = None # argparse migration — CliRunner ignores this arg runner = CliRunner() # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _env(root: pathlib.Path) -> Manifest: return {"MUSE_REPO_ROOT": str(root)} def _init_repo(tmp_path: pathlib.Path) -> tuple[pathlib.Path, str]: dot_muse = muse_dir(tmp_path) dot_muse.mkdir() repo_id = fake_id("repo") (dot_muse / "repo.json").write_text(json.dumps({ "repo_id": repo_id, "domain": "midi", "default_branch": "main", "created_at": "2025-01-01T00:00:00+00:00", }), encoding="utf-8") (dot_muse / "HEAD").write_text("ref: refs/heads/main", encoding="utf-8") (dot_muse / "refs" / "heads").mkdir(parents=True) (dot_muse / "snapshots").mkdir() (dot_muse / "commits").mkdir() (dot_muse / "objects" / "sha256").mkdir(parents=True) return tmp_path, repo_id def _write_object(root: pathlib.Path, content: bytes) -> str: from muse.core.object_store import write_object oid = blob_id(content) write_object(root, oid, content) return oid def _make_commit(root: pathlib.Path, repo_id: str, message: str = "init") -> str: from muse.core.commits import ( CommitRecord, write_commit, ) from muse.core.snapshots import ( SnapshotRecord, write_snapshot, ) from muse.core.ids import hash_snapshot, hash_commit ref_file = heads_dir(root) / "main" parent_id = ref_file.read_text().strip() if ref_file.exists() else None manifest: Manifest = {} snap_id = hash_snapshot(manifest) committed_at = datetime.datetime.now(datetime.timezone.utc) commit_id = hash_commit( parent_ids=[parent_id] if parent_id else [], snapshot_id=snap_id, message=message, committed_at_iso=committed_at.isoformat(), ) write_snapshot(root, SnapshotRecord(snapshot_id=snap_id, manifest=manifest)) write_commit(root, CommitRecord( commit_id=commit_id, branch="main", snapshot_id=snap_id, message=message, committed_at=committed_at, parent_commit_id=parent_id, )) ref_file.parent.mkdir(parents=True, exist_ok=True) ref_file.write_text(commit_id, encoding="utf-8") return commit_id # --------------------------------------------------------------------------- # Unit tests # --------------------------------------------------------------------------- class TestRegisterFlags: def _parse(self, *args: str) -> "argparse.Namespace": import argparse from muse.cli.commands.gc import register p = argparse.ArgumentParser() sub = p.add_subparsers() register(sub) return p.parse_args(["gc", *args]) def test_default_json_out_is_false(self) -> None: ns = self._parse() assert ns.json_out is False def test_json_flag_sets_json_out(self) -> None: ns = self._parse("--json") assert ns.json_out is True def test_j_shorthand_sets_json_out(self) -> None: ns = self._parse("-j") assert ns.json_out is True class TestGcUnit: def test_run_gc_empty_repo(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) from muse.core.gc import run_gc result = run_gc(root, dry_run=False) assert result.collected_count == 0 def test_run_gc_dry_run_does_not_delete(self, tmp_path: pathlib.Path) -> None: root, _ = _init_repo(tmp_path) orphan_id = _write_object(root, b"orphaned content") from muse.core.gc import run_gc result = run_gc(root, dry_run=True, grace_period_seconds=0) assert object_path(root, orphan_id).exists() assert result.collected_count >= 1 def test_run_gc_collects_unreachable_objects(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _make_commit(root, repo_id, message="committed") orphan_id = _write_object(root, b"never committed content") from muse.core.gc import run_gc result = run_gc(root, dry_run=False, grace_period_seconds=0) assert not object_path(root, orphan_id).exists() assert orphan_id in result.collected_ids # --------------------------------------------------------------------------- # Integration (CLI) tests # --------------------------------------------------------------------------- class TestGcIntegration: def test_gc_default_clean_repo(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _make_commit(root, repo_id) result = runner.invoke(cli, ["gc"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 def test_gc_dry_run_reports_orphans(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _make_commit(root, repo_id) _write_object(root, b"orphan1") _write_object(root, b"orphan2") result = runner.invoke( cli, ["gc", "--dry-run", "--grace-period", "0"], env=_env(root), catch_exceptions=False, ) assert result.exit_code == 0 assert "2" in result.output or "collect" in result.output.lower() def test_gc_verbose_shows_ids(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _make_commit(root, repo_id) orphan_id = _write_object(root, b"verbose orphan") result = runner.invoke( cli, ["gc", "--verbose", "--grace-period", "0"], env=_env(root), catch_exceptions=False, ) assert result.exit_code == 0 assert short_id(orphan_id, strip=True) in result.output def test_gc_output_includes_count(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _write_object(root, b"orphan for count test") result = runner.invoke( cli, ["gc", "--grace-period", "0"], env=_env(root), catch_exceptions=False, ) assert result.exit_code == 0 assert "Removed" in result.output or "object" in result.output def test_gc_keeps_referenced_objects(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) content = b"referenced file content" obj_id = _write_object(root, content) from muse.core.commits import ( CommitRecord, write_commit, ) from muse.core.snapshots import ( SnapshotRecord, write_snapshot, ) from muse.core.ids import hash_snapshot, hash_commit manifest = {"file.mid": obj_id} snap_id = hash_snapshot(manifest) committed_at = datetime.datetime.now(datetime.timezone.utc) commit_id = hash_commit( parent_ids=[], snapshot_id=snap_id, message="with file", committed_at_iso=committed_at.isoformat(), ) write_snapshot(root, SnapshotRecord(snapshot_id=snap_id, manifest=manifest)) write_commit(root, CommitRecord( commit_id=commit_id, branch="main", snapshot_id=snap_id, message="with file", committed_at=committed_at, parent_commit_id=None, )) (heads_dir(root) / "main").write_text(commit_id) runner.invoke(cli, ["gc", "--grace-period", "0"], env=_env(root), catch_exceptions=False) assert object_path(root, obj_id).exists() def test_gc_short_flags(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _make_commit(root, repo_id) _write_object(root, b"short flag orphan") result = runner.invoke( cli, ["gc", "-n", "-v", "--grace-period", "0"], env=_env(root), catch_exceptions=False, ) assert result.exit_code == 0 # --------------------------------------------------------------------------- # Stress tests # --------------------------------------------------------------------------- class TestGcStress: def test_gc_many_orphaned_objects(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _make_commit(root, repo_id) orphan_ids = [_write_object(root, f"orphan {i}".encode()) for i in range(100)] result = runner.invoke( cli, ["gc", "--grace-period", "0"], env=_env(root), catch_exceptions=False, ) assert result.exit_code == 0 assert "100" in result.output for oid in orphan_ids: assert not object_path(root, oid).exists() def test_gc_repeated_runs_idempotent(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) _make_commit(root, repo_id) for _ in range(3): result = runner.invoke(cli, ["gc"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0