"""Supercharge tests for ``muse code detect-refactor`` — agent-usability gaps. The existing TestDetectRefactorV2 in test_code_commands.py covers correctness, JSON schema, event schema, rename detection, implementation classification, reformatted-skip, truncation, --kind filter, invalid kind, and BFS merge-parent-2 traversal. This file targets only the gaps those tests leave open: Coverage matrix --------------- - --json / -j: -j alias works identically to --json - exit_code: JSON output includes exit_code = 0 on success - duration_ms: JSON output includes non-negative float duration_ms - TypedDicts: _RefactorOutputJson carries exit_code/duration_ms annotations - Docstrings: run() docstring mentions exit_code and duration_ms - ANSI: JSON output never contains terminal escape sequences - Performance: duration_ms stays under 2000 ms for a small repo """ from __future__ import annotations from collections.abc import Mapping import argparse import json import pathlib import textwrap import pytest from tests.cli_test_helper import CliRunner, InvokeResult runner = CliRunner() # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _env(root: pathlib.Path) -> Mapping[str, str]: return {"MUSE_REPO_ROOT": str(root)} def _run(root: pathlib.Path, *args: str) -> InvokeResult: return runner.invoke(None, list(args), env=_env(root)) # --------------------------------------------------------------------------- # Fixture — repo with a rename event and an implementation-change event # --------------------------------------------------------------------------- @pytest.fixture() def refactor_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with two commits that produce detectable refactoring events. Commit 1 — seed: billing.py with compute_total + validate_amount. Commit 2 — refactor: compute_total renamed to calculate_total; validate_amount body changed (implementation). The same body hash under a new name triggers a rename event. A body change under the same name triggers an implementation event. """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output # commit 1 — seed (tmp_path / "billing.py").write_text(textwrap.dedent("""\ def compute_total(items): return sum(items) def validate_amount(amount): return amount > 0 """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "initial: add billing functions") assert r.exit_code == 0, r.output # commit 2 — rename compute_total → calculate_total; change validate_amount body (tmp_path / "billing.py").write_text(textwrap.dedent("""\ def calculate_total(items): return sum(items) def validate_amount(amount): return amount >= 0 """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "refactor: rename compute_total, tighten validate") assert r.exit_code == 0, r.output return tmp_path # --------------------------------------------------------------------------- # TestJsonAlias — -j works identically to --json # --------------------------------------------------------------------------- class TestJsonAlias: """-j shorthand must behave identically to --json.""" def test_j_alias_exits_zero(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") json.loads(r.output) # must not raise def test_j_alias_has_events_key(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert "events" in json.loads(r.output) def test_j_alias_has_commits_scanned_key(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert "commits_scanned" in json.loads(r.output) def test_j_alias_has_total_key(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert "total" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, refactor_repo: pathlib.Path ) -> None: r1 = _run(refactor_repo, "code", "detect-refactor", "--json") r2 = _run(refactor_repo, "code", "detect-refactor", "-j") d1 = json.loads(r1.output) d2 = json.loads(r2.output) d1.pop("duration_ms", None) d2.pop("duration_ms", None) assert set(d1.keys()) == set(d2.keys()) def test_j_alias_event_count_matches_json_flag( self, refactor_repo: pathlib.Path ) -> None: r1 = _run(refactor_repo, "code", "detect-refactor", "--json") r2 = _run(refactor_repo, "code", "detect-refactor", "-j") assert len(json.loads(r1.output)["events"]) == len(json.loads(r2.output)["events"]) def test_j_alias_with_kind_filter(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j", "--kind", "implementation") assert r.exit_code == 0, r.output data = json.loads(r.output) for ev in data["events"]: assert ev["kind"] == "implementation" def test_j_alias_with_max_filter(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j", "--max", "10") assert r.exit_code == 0, r.output json.loads(r.output) # valid JSON # --------------------------------------------------------------------------- # TestDurationMs — JSON output must include duration_ms # --------------------------------------------------------------------------- class TestDurationMs: """JSON output must include a non-negative float duration_ms.""" def test_json_has_duration_ms(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert "duration_ms" in json.loads(r.output) def test_duration_ms_with_kind_filter(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json", "--kind", "implementation") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_max_filter(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json", "--max", "1") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) # --------------------------------------------------------------------------- # TestExitCode — JSON includes exit_code = 0 on success # --------------------------------------------------------------------------- class TestExitCode: """JSON exit_code must be 0 on success.""" def test_json_has_exit_code(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_with_kind_filter(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json", "--kind", "implementation") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_max_filter(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json", "--max", "5") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_from_to(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json", "--from", "HEAD~1", "--to", "HEAD") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _RefactorOutputJson carries exit_code/duration_ms # --------------------------------------------------------------------------- class TestTypedDicts: """_RefactorOutputJson must carry exit_code and duration_ms annotations.""" def test_refactor_output_json_typeddict_exists(self) -> None: from muse.cli.commands.detect_refactor import _RefactorOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.detect_refactor import _RefactorOutputJson assert "exit_code" in _RefactorOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.detect_refactor import _RefactorOutputJson assert "duration_ms" in _RefactorOutputJson.__annotations__ def test_retains_schema_annotation(self) -> None: from muse.cli.commands.detect_refactor import _RefactorOutputJson assert "schema" in _RefactorOutputJson.__annotations__ def test_retains_events_annotation(self) -> None: from muse.cli.commands.detect_refactor import _RefactorOutputJson assert "events" in _RefactorOutputJson.__annotations__ def test_retains_commits_scanned_annotation(self) -> None: from muse.cli.commands.detect_refactor import _RefactorOutputJson assert "commits_scanned" in _RefactorOutputJson.__annotations__ def test_retains_truncated_annotation(self) -> None: from muse.cli.commands.detect_refactor import _RefactorOutputJson assert "truncated" in _RefactorOutputJson.__annotations__ # --------------------------------------------------------------------------- # TestAnsiSanitization — no escape codes in JSON output # --------------------------------------------------------------------------- class TestAnsiSanitization: """No ANSI escape sequences anywhere in the JSON output.""" def test_json_output_no_ansi(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert "\x1b" not in r.output def test_json_output_no_ansi_with_kind_filter( self, refactor_repo: pathlib.Path ) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json", "--kind", "implementation") assert "\x1b" not in r.output # --------------------------------------------------------------------------- # TestPerformance — duration_ms under 2000 ms for a small repo # --------------------------------------------------------------------------- class TestPerformance: """duration_ms must stay under 2000 ms for small repos.""" def test_json_duration_under_2000ms(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert json.loads(r.output)["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "-j") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, refactor_repo: pathlib.Path) -> None: r = _run(refactor_repo, "code", "detect-refactor", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) # --------------------------------------------------------------------------- # TestRegisterFlags — --json / -j normalized at argparse level # --------------------------------------------------------------------------- class TestRegisterFlags: """register() must expose --json with -j shorthand and dest=json_out.""" def _make_parser(self) -> argparse.ArgumentParser: import argparse as ap from muse.cli.commands.detect_refactor import register root = ap.ArgumentParser() subs = root.add_subparsers() register(subs) return root def test_json_out_default_false(self) -> None: p = self._make_parser() ns = p.parse_args(['detect-refactor']) assert ns.json_out is False def test_json_out_true_with_json_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['detect-refactor', '--json']) assert ns.json_out is True def test_json_out_true_with_j_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['detect-refactor', '-j']) assert ns.json_out is True