"""Tests for ``muse merge --dry-run``. Verifies that --dry-run: - Reports the correct outcome for all three cases (up-to-date, fast-forward, three-way merge) - NEVER writes to the working tree, ref files, snapshot store, or commits - Works with --format json (identical shape, dry_run: true field added) - Reports conflicts without writing MERGE_STATE.json - Includes files_changed stats on fast-forward and clean merge - Skips the require_clean_workdir check (dry-run never needs a clean tree) """ 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 from muse.core.paths import commits_dir, heads_dir, logs_dir, merge_state_path, muse_dir, ref_path, snapshots_dir cli = None runner = CliRunner() # --------------------------------------------------------------------------- # Helpers (shared with test_cmd_merge.py — intentionally duplicated for isolation) # --------------------------------------------------------------------------- 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": "code", "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").mkdir() return tmp_path, repo_id def _make_commit( root: pathlib.Path, repo_id: str, branch: str = "main", message: str = "test", manifest: Manifest | None = None, ) -> str: from muse.core.store import CommitRecord, SnapshotRecord, write_commit, write_snapshot from muse.core.ids import hash_snapshot, hash_commit ref_file = ref_path(root, branch) parent_id = ref_file.read_text().strip() if ref_file.exists() else None m = manifest or {} snap_id = hash_snapshot(m) 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=m)) write_commit(root, CommitRecord( commit_id=commit_id, branch=branch, 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 def _write_object(root: pathlib.Path, content: bytes) -> str: from muse.core.object_store import write_object obj_id = blob_id(content) write_object(root, obj_id, content) return obj_id def _head_ref(root: pathlib.Path, branch: str = "main") -> str: return (ref_path(root, branch)).read_text().strip() # --------------------------------------------------------------------------- # up-to-date # --------------------------------------------------------------------------- class TestDryRunUpToDate: def test_text_output(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) commit_id = _make_commit(root, repo_id, branch="main") # feature branch = same commit (heads_dir(root) / "feature").write_text(commit_id) result = runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 assert "up to date" in result.output.lower() def test_json_output_has_dry_run_true(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) commit_id = _make_commit(root, repo_id, branch="main") (heads_dir(root) / "feature").write_text(commit_id) result = runner.invoke(cli, ["merge", "--dry-run", "--json", "feature"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 data = json.loads(result.output) assert data["status"] == "up_to_date" assert data["dry_run"] is True def test_refs_not_modified(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) commit_id = _make_commit(root, repo_id, branch="main") (heads_dir(root) / "feature").write_text(commit_id) before = _head_ref(root, "main") runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) assert _head_ref(root, "main") == before # --------------------------------------------------------------------------- # fast-forward # --------------------------------------------------------------------------- class TestDryRunFastForward: def _setup(self, tmp_path: pathlib.Path) -> tuple[pathlib.Path, str, str, str]: root, repo_id = _init_repo(tmp_path) base_id = _make_commit(root, repo_id, branch="main", message="base") (heads_dir(root) / "feature").write_text(base_id) obj = _write_object(root, b"new track data") feature_id = _make_commit(root, repo_id, branch="feature", message="add track", manifest={"track.mid": obj}) return root, repo_id, base_id, feature_id def test_exit_code_zero(self, tmp_path: pathlib.Path) -> None: root, _, _, _ = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 def test_main_ref_not_advanced(self, tmp_path: pathlib.Path) -> None: root, _, base_id, _ = self._setup(tmp_path) runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) # main must still point to base, not the feature commit assert _head_ref(root, "main") == base_id def test_working_tree_not_modified(self, tmp_path: pathlib.Path) -> None: root, _, _, _ = self._setup(tmp_path) # No files should appear in the repo root after dry-run runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) assert not (root / "track.mid").exists() def test_no_reflog_entry_written(self, tmp_path: pathlib.Path) -> None: root, _, _, _ = self._setup(tmp_path) reflog = logs_dir(root) / "refs" / "heads" / "main" existed_before = reflog.exists() runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) if not existed_before: assert not reflog.exists() else: # If it existed, ensure no new entry was appended for the dry-run lines_before = reflog.read_text().splitlines() if reflog.exists() else [] runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root)) lines_after = reflog.read_text().splitlines() if reflog.exists() else [] assert len(lines_after) == len(lines_before) def test_text_mentions_would_fast_forward(self, tmp_path: pathlib.Path) -> None: root, _, _, _ = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) assert "would fast-forward" in result.output.lower() or "dry-run" in result.output.lower() def test_json_status_and_dry_run_field(self, tmp_path: pathlib.Path) -> None: root, _, base_id, feature_id = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "--json", "feature"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 data = json.loads(result.output) assert data["status"] == "fast_forward" assert data["dry_run"] is True # commit_id is None in dry-run (nothing committed) assert data["commit_id"] is None assert "files_changed" in data def test_files_changed_stats_correct(self, tmp_path: pathlib.Path) -> None: root, _, _, _ = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "--json", "feature"], env=_env(root), catch_exceptions=False) data = json.loads(result.output) fc = data["files_changed"] assert fc["added"] == 1 assert fc["modified"] == 0 assert fc["deleted"] == 0 # --------------------------------------------------------------------------- # three-way clean merge # --------------------------------------------------------------------------- class TestDryRunThreeWayClean: def _setup(self, tmp_path: pathlib.Path) -> tuple[pathlib.Path, str]: root, repo_id = _init_repo(tmp_path) base_obj = _write_object(root, b"base track") base_id = _make_commit(root, repo_id, branch="main", message="base", manifest={"base.mid": base_obj}) (heads_dir(root) / "feature").write_text(base_id) # main and feature both diverge from base — true three-way main_obj = _write_object(root, b"main track addition") _make_commit(root, repo_id, branch="main", message="main work", manifest={"base.mid": base_obj, "main.mid": main_obj}) feat_obj = _write_object(root, b"feature track addition") _make_commit(root, repo_id, branch="feature", message="feat work", manifest={"base.mid": base_obj, "feat.mid": feat_obj}) return root, repo_id def test_exit_code_zero(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 def test_main_ref_not_advanced(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) before = _head_ref(root, "main") runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) assert _head_ref(root, "main") == before def test_no_new_snapshot_written(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) snaps_before = set((snapshots_dir(root)).iterdir()) runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) snaps_after = set((snapshots_dir(root)).iterdir()) assert snaps_after == snaps_before def test_no_new_commit_written(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) commits_before = set((commits_dir(root)).iterdir()) runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) commits_after = set((commits_dir(root)).iterdir()) assert commits_after == commits_before def test_json_dry_run_true_and_no_commit_id(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "--json", "feature"], env=_env(root), catch_exceptions=False) assert result.exit_code == 0 data = json.loads(result.output) assert data["status"] == "merged" assert data["dry_run"] is True assert data["commit_id"] is None assert data["conflicts"] == [] assert "files_changed" in data def test_dirty_workdir_allowed_with_dry_run(self, tmp_path: pathlib.Path) -> None: """--dry-run skips the require_clean_workdir check.""" root, _ = self._setup(tmp_path) # Create an uncommitted file to make the working tree dirty (root / "untracked.txt").write_text("dirty") result = runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root), catch_exceptions=False) # Should succeed even with a dirty workdir assert result.exit_code == 0 # --------------------------------------------------------------------------- # three-way with conflicts # --------------------------------------------------------------------------- class TestDryRunConflict: def _setup(self, tmp_path: pathlib.Path) -> tuple[pathlib.Path, str]: root, repo_id = _init_repo(tmp_path) shared_obj_v1 = _write_object(root, b"shared v1") base_id = _make_commit(root, repo_id, branch="main", message="base", manifest={"shared.mid": shared_obj_v1}) (heads_dir(root) / "feature").write_text(base_id) # Both branches modify the same file differently → conflict shared_main = _write_object(root, b"shared main version") _make_commit(root, repo_id, branch="main", message="main mod", manifest={"shared.mid": shared_main}) shared_feat = _write_object(root, b"shared feature version") _make_commit(root, repo_id, branch="feature", message="feat mod", manifest={"shared.mid": shared_feat}) return root, repo_id def test_exit_code_nonzero(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root)) assert result.exit_code != 0 def test_no_merge_state_written(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) merge_state = merge_state_path(root) runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root)) assert not merge_state.exists() def test_ref_not_modified_on_conflict(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) before = _head_ref(root, "main") runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root)) assert _head_ref(root, "main") == before def test_json_conflict_status_and_dry_run(self, tmp_path: pathlib.Path) -> None: root, _ = self._setup(tmp_path) result = runner.invoke(cli, ["merge", "--dry-run", "--json", "feature"], env=_env(root)) data = json.loads(result.output) assert data["status"] == "conflict" assert data["dry_run"] is True assert len(data["conflicts"]) > 0 def test_live_merge_after_dry_run_still_reports_conflict(self, tmp_path: pathlib.Path) -> None: """Dry-run must not leave any state that affects a subsequent live merge.""" root, _ = self._setup(tmp_path) # dry-run first runner.invoke(cli, ["merge", "--dry-run", "feature"], env=_env(root)) # live merge live = runner.invoke(cli, ["merge", "feature"], env=_env(root)) assert live.exit_code != 0 # still conflicts # --------------------------------------------------------------------------- # semver impact (Muse-unique) # --------------------------------------------------------------------------- class TestDryRunSemverImpact: """The semver_impact field is Muse-unique: git has no equivalent.""" def test_json_includes_semver_impact_key(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) base_id = _make_commit(root, repo_id, branch="main", message="base") (heads_dir(root) / "feature").write_text(base_id) obj = _write_object(root, b"data") _make_commit(root, repo_id, branch="feature", message="feat", manifest={"f.mid": obj}) result = runner.invoke(cli, ["merge", "--dry-run", "--json", "feature"], env=_env(root), catch_exceptions=False) data = json.loads(result.output) assert "semver_impact" in data # --------------------------------------------------------------------------- # Live merge unaffected by --dry-run flag absence # --------------------------------------------------------------------------- class TestDryRunFlagAbsent: def test_live_merge_still_commits(self, tmp_path: pathlib.Path) -> None: root, repo_id = _init_repo(tmp_path) base_id = _make_commit(root, repo_id, branch="main", message="base") (heads_dir(root) / "feature").write_text(base_id) _make_commit(root, repo_id, branch="feature", message="feat") before = _head_ref(root, "main") runner.invoke(cli, ["merge", "feature"], env=_env(root), catch_exceptions=False) assert _head_ref(root, "main") != before