"""Supercharge tests for ``muse name-rev``. Coverage tiers -------------- - JSON envelope: exit_code and duration_ms present on all resolution outcomes - Error payload: errors go to stdout as JSON in --json mode, no dual stderr prose - Prefix resolution: bare hex short-prefix matches sha256:-prefixed keys in name_map - TypedDicts: _NameRevJson and _NameRevErrorJson with required annotations - Docstring: module docstring covers exit_code and duration_ms - No-prose pollution: JSON stdout is valid on all non-error paths - Stress: 100-commit chain, all entries have exit_code and duration_ms """ from __future__ import annotations from collections.abc import Mapping import datetime import json import pathlib from typing import get_type_hints from muse.core.ids import hash_commit as compute_commit_id, hash_snapshot as compute_snapshot_id from muse.core.commits import ( CommitRecord, write_commit, ) from muse.core.snapshots import ( SnapshotRecord, write_snapshot, ) from muse.core.paths import ref_path, muse_dir from tests.cli_test_helper import CliRunner, InvokeResult runner = CliRunner() _DT = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc) # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _init_repo(tmp_path: pathlib.Path) -> pathlib.Path: dot_muse = muse_dir(tmp_path) for d in ("commits", "snapshots", "objects", "refs/heads"): (dot_muse / d).mkdir(parents=True, exist_ok=True) (dot_muse / "HEAD").write_text("ref: refs/heads/main", encoding="utf-8") (dot_muse / "repo.json").write_text( json.dumps({"repo_id": "nr-supercharge", "domain": "midi"}), encoding="utf-8" ) return tmp_path def _env(root: pathlib.Path) -> Mapping[str, str]: return {"MUSE_REPO_ROOT": str(root)} def _commit( root: pathlib.Path, msg: str, branch: str = "main", parent: str | None = None, ) -> str: sid = compute_snapshot_id({}) write_snapshot(root, SnapshotRecord(snapshot_id=sid, manifest={}, created_at=_DT)) parent_ids = [parent] if parent else [] cid = compute_commit_id( parent_ids=parent_ids, snapshot_id=sid, message=msg, committed_at_iso=_DT.isoformat(), ) write_commit(root, CommitRecord( commit_id=cid, branch=branch, snapshot_id=sid, message=msg, committed_at=_DT, parent_commit_id=parent, )) ref = ref_path(root, branch) ref.parent.mkdir(parents=True, exist_ok=True) ref.write_text(cid, encoding="utf-8") return cid def _nr(root: pathlib.Path, *args: str, stdin: str | None = None) -> InvokeResult: from muse.cli.app import main as cli extra = [] if "--json" in args or "-j" in args else ["--json"] return runner.invoke(cli, ["name-rev", *extra, *args], env=_env(root), input=stdin) def _hex_prefix(cid: str, n: int = 8) -> str: """Extract n hex chars from a sha256:-prefixed commit ID.""" return cid[len("sha256:"):len("sha256:") + n] # --------------------------------------------------------------------------- # JSON envelope — exit_code # --------------------------------------------------------------------------- class TestJsonEnvelopeExitCode: def test_found_has_exit_code_zero(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) cid = _commit(root, "c1") r = _nr(root, cid) assert r.exit_code == 0 d = json.loads(r.output) assert "exit_code" in d, "exit_code missing from found envelope" assert d["exit_code"] == 0 def test_undefined_result_still_exit_code_zero(self, tmp_path: pathlib.Path) -> None: """undefined entries are a valid outcome — exit_code must still be 0.""" root = _init_repo(tmp_path) _commit(root, "c1") fake = "a" * 64 r = _nr(root, fake) assert r.exit_code == 0 d = json.loads(r.output) assert "exit_code" in d assert d["exit_code"] == 0 def test_mixed_found_and_undefined_exit_code_zero(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) cid = _commit(root, "c1") fake = "b" * 64 r = _nr(root, cid, fake) assert r.exit_code == 0 d = json.loads(r.output) assert d["exit_code"] == 0 # --------------------------------------------------------------------------- # JSON envelope — duration_ms # --------------------------------------------------------------------------- class TestJsonEnvelopeDurationMs: def test_found_has_duration_ms(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) cid = _commit(root, "c1") r = _nr(root, cid) d = json.loads(r.output) assert "duration_ms" in d, "duration_ms missing from found envelope" assert isinstance(d["duration_ms"], float) assert d["duration_ms"] >= 0.0 def test_undefined_has_duration_ms(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) _commit(root, "c1") r = _nr(root, "a" * 64) d = json.loads(r.output) assert "duration_ms" in d def test_branches_filter_has_duration_ms(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) cid = _commit(root, "c1", "main") r = _nr(root, cid, "--branches", "main") d = json.loads(r.output) assert "duration_ms" in d assert isinstance(d["duration_ms"], float) # --------------------------------------------------------------------------- # Error payload — errors route to stdout as JSON in --json mode # --------------------------------------------------------------------------- class TestErrorPayload: def test_no_inputs_error_goes_to_stdout(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) r = _nr(root, "--json") assert r.exit_code != 0 assert not r.stderr.strip(), f"unexpected stderr: {r.stderr!r}" d = json.loads(r.output) assert d["status"] == "error" def test_invalid_hex_error_goes_to_stdout(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) r = _nr(root, "--json", "not-hex!") assert r.exit_code != 0 assert not r.stderr.strip(), f"unexpected stderr: {r.stderr!r}" d = json.loads(r.output) assert d["status"] == "error" def test_bad_max_walk_error_goes_to_stdout(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) cid = _commit(root, "c1") r = _nr(root, "--json", cid, "--max-walk", "0") assert r.exit_code != 0 assert not r.stderr.strip(), f"unexpected stderr: {r.stderr!r}" d = json.loads(r.output) assert d["status"] == "error" def test_error_payload_has_status_error(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) r = _nr(root, "--json", "not-valid!") d = json.loads(r.output) assert d["status"] == "error" def test_error_payload_has_exit_code(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) r = _nr(root, "--json", "not-valid!") d = json.loads(r.output) assert "exit_code" in d assert d["exit_code"] != 0 def test_error_payload_has_error_field(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) r = _nr(root, "--json") d = json.loads(r.output) assert "error" in d assert d["error"] def test_no_emoji_on_stderr_in_json_mode(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) r = _nr(root, "--json", "not-valid!") assert "❌" not in r.stderr # --------------------------------------------------------------------------- # Prefix resolution — bare hex prefix against sha256:-prefixed keys # --------------------------------------------------------------------------- class TestPrefixResolutionSha256: def test_bare_hex_8char_prefix_resolves(self, tmp_path: pathlib.Path) -> None: """Bare 8-char hex prefix must resolve against sha256:-prefixed name_map keys.""" root = _init_repo(tmp_path) cid = _commit(root, "c1") prefix = _hex_prefix(cid, 8) # first 8 hex chars, no sha256: prefix r = _nr(root, prefix) assert r.exit_code == 0 entry = json.loads(r.output)["results"][0] assert entry["commit_id"] == cid assert entry["undefined"] is False def test_bare_hex_4char_prefix_resolves(self, tmp_path: pathlib.Path) -> None: """4-char bare hex prefix must resolve when unambiguous.""" root = _init_repo(tmp_path) cid = _commit(root, "unique-c1-msg") prefix = _hex_prefix(cid, 4) r = _nr(root, prefix) assert r.exit_code == 0 entry = json.loads(r.output)["results"][0] # Either resolves to cid or is ambiguous — must not crash or error assert entry["input"] == prefix assert r.exit_code == 0 def test_sha256_prefixed_short_id_resolves(self, tmp_path: pathlib.Path) -> None: """sha256:-prefixed short IDs (e.g. sha256:abcd1234) must also resolve.""" root = _init_repo(tmp_path) cid = _commit(root, "c1") short = cid[:len("sha256:") + 8] # keep sha256: + 8 hex chars r = _nr(root, short) assert r.exit_code == 0 entry = json.loads(r.output)["results"][0] assert entry["commit_id"] == cid def test_input_field_preserves_bare_hex_prefix(self, tmp_path: pathlib.Path) -> None: """input field echoes the caller's original value, not the resolved full ID.""" root = _init_repo(tmp_path) cid = _commit(root, "c1") prefix = _hex_prefix(cid, 8) r = _nr(root, prefix) entry = json.loads(r.output)["results"][0] assert entry["input"] == prefix # --------------------------------------------------------------------------- # No-prose pollution # --------------------------------------------------------------------------- class TestNoProsePollution: def test_found_stdout_is_valid_json(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) cid = _commit(root, "c1") r = _nr(root, cid) json.loads(r.output) # must not raise def test_undefined_stdout_is_valid_json(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) _commit(root, "c1") json.loads(_nr(root, "a" * 64).output) def test_no_emoji_in_success_json(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) cid = _commit(root, "c1") r = _nr(root, cid) assert "✅" not in r.output assert "❌" not in r.output # --------------------------------------------------------------------------- # TypedDicts # --------------------------------------------------------------------------- class TestTypedDicts: def test_name_rev_json_typeddict_exists(self) -> None: from muse.cli.commands.name_rev import _NameRevJson assert _NameRevJson is not None def test_name_rev_error_json_typeddict_exists(self) -> None: from muse.cli.commands.name_rev import _NameRevErrorJson assert _NameRevErrorJson is not None def test_name_rev_json_has_exit_code_annotation(self) -> None: from muse.cli.commands.name_rev import _NameRevJson hints = get_type_hints(_NameRevJson) assert "exit_code" in hints def test_name_rev_json_has_duration_ms_annotation(self) -> None: from muse.cli.commands.name_rev import _NameRevJson hints = get_type_hints(_NameRevJson) assert "duration_ms" in hints def test_name_rev_error_json_has_required_fields(self) -> None: from muse.cli.commands.name_rev import _NameRevErrorJson hints = get_type_hints(_NameRevErrorJson) for field in ("status", "error", "exit_code"): assert field in hints, f"Missing annotation: {field!r}" # --------------------------------------------------------------------------- # Docstring coverage # --------------------------------------------------------------------------- class TestDocstring: def _doc(self) -> str: import muse.cli.commands.name_rev as mod return mod.__doc__ or "" def test_docstring_documents_exit_code(self) -> None: assert "exit_code" in self._doc() def test_docstring_documents_duration_ms(self) -> None: assert "duration_ms" in self._doc() # --------------------------------------------------------------------------- # Stress # --------------------------------------------------------------------------- class TestStress: def test_100_commit_chain_all_have_envelope_fields(self, tmp_path: pathlib.Path) -> None: root = _init_repo(tmp_path) parent: str | None = None commits: list[str] = [] for i in range(100): cid = _commit(root, f"c{i:03d}", parent=parent) commits.append(cid) parent = cid r = _nr(root, commits[0], commits[49], commits[-1]) assert r.exit_code == 0 d = json.loads(r.output) assert "exit_code" in d assert "duration_ms" in d assert d["exit_code"] == 0 assert isinstance(d["duration_ms"], float) # Tip at distance 0, midpoint at 50, root at 99 by_id = {e["commit_id"]: e for e in d["results"]} assert by_id[commits[-1]]["distance"] == 0 assert by_id[commits[49]]["distance"] == 50 assert by_id[commits[0]]["distance"] == 99