"""Supercharge tests for ``muse code clones`` — agent-usability gaps. The existing test_cmd_clones.py covers correctness, JSON schema, flags, E2E, and stress. 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: _ClonesOutputJson gains 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 json import pathlib import textwrap import pytest from tests.cli_test_helper import CliRunner 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 exact and near clones committed # --------------------------------------------------------------------------- @pytest.fixture() def clones_repo(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> pathlib.Path: """Code-domain repo with committed duplicate symbols. billing.py and payments.py both define compute_total with identical bodies (exact clone). validate() in both files shares the same signature but has different bodies (near-clone). """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output (tmp_path / "billing.py").write_text(textwrap.dedent("""\ def compute_total(items): return sum(items) def validate(value): if value is None: raise ValueError("billing: value required") return True """)) (tmp_path / "payments.py").write_text(textwrap.dedent("""\ def compute_total(items): return sum(items) def validate(value): if not isinstance(value, (int, float)): raise TypeError("payments: numeric value required") return True """)) r1 = _run(tmp_path, "code", "add", "billing.py") assert r1.exit_code == 0, r1.output r2 = _run(tmp_path, "code", "add", "payments.py") assert r2.exit_code == 0, r2.output r3 = _run(tmp_path, "commit", "-m", "add billing and payments with clones") assert r3.exit_code == 0, r3.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, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") json.loads(r.output) # must not raise def test_j_alias_has_clusters_key(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") data = json.loads(r.output) assert "clusters" in data def test_j_alias_has_commit_key(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") data = json.loads(r.output) assert "commit" in data def test_j_alias_same_top_level_keys_as_json_flag(self, clones_repo: pathlib.Path) -> None: r1 = _run(clones_repo, "code", "clones", "--json") r2 = _run(clones_repo, "code", "clones", "-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_same_cluster_count(self, clones_repo: pathlib.Path) -> None: r1 = _run(clones_repo, "code", "clones", "--json") r2 = _run(clones_repo, "code", "clones", "-j") assert json.loads(r1.output)["exact_clone_clusters"] == \ json.loads(r2.output)["exact_clone_clusters"] def test_j_alias_with_tier_exact(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--tier", "exact", "-j") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["tier"] == "exact" def test_j_alias_with_tier_near(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--tier", "near", "-j") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["tier"] == "near" # --------------------------------------------------------------------------- # 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, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert "duration_ms" in data def test_json_duration_ms_nonnegative(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert data["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float) def test_j_alias_duration_ms_present(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") data = json.loads(r.output) assert "duration_ms" in data def test_duration_ms_with_tier_exact(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json", "--tier", "exact") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_no_clones(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: """duration_ms is present even when no clones are found.""" monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0 (tmp_path / "solo.py").write_text("def unique_fn():\n return 42\n") _run(tmp_path, "code", "add", "solo.py") _run(tmp_path, "commit", "-m", "solo") r2 = _run(tmp_path, "code", "clones", "--json") data = json.loads(r2.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 # --------------------------------------------------------------------------- # TestExitCode — JSON output must include exit_code = 0 # --------------------------------------------------------------------------- class TestExitCode: """JSON output must include exit_code = 0 on success.""" def test_json_has_exit_code(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert "exit_code" in data def test_json_exit_code_zero_on_success(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 def test_json_exit_code_is_int(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert isinstance(data["exit_code"], int) def test_j_alias_exit_code_present(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") data = json.loads(r.output) assert "exit_code" in data def test_exit_code_mirrors_process_exit(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert data["exit_code"] == r.exit_code def test_exit_code_zero_with_no_clones(self, tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.chdir(tmp_path) _run(tmp_path, "init", "--domain", "code") (tmp_path / "solo.py").write_text("def unique_fn():\n return 42\n") _run(tmp_path, "code", "add", "solo.py") _run(tmp_path, "commit", "-m", "solo") r = _run(tmp_path, "code", "clones", "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 def test_exit_code_zero_with_tier_near(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json", "--tier", "near") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _ClonesOutputJson carries the new fields # --------------------------------------------------------------------------- class TestTypedDicts: """_ClonesOutputJson must carry exit_code and duration_ms annotations.""" def test_clones_output_json_exists(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson assert "exit_code" in _ClonesOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson assert "duration_ms" in _ClonesOutputJson.__annotations__ def test_retains_clusters_annotation(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson assert "clusters" in _ClonesOutputJson.__annotations__ def test_retains_commit_annotation(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson assert "commit" in _ClonesOutputJson.__annotations__ def test_retains_exact_clone_clusters_annotation(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson assert "exact_clone_clusters" in _ClonesOutputJson.__annotations__ def test_retains_near_clone_clusters_annotation(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson assert "near_clone_clusters" in _ClonesOutputJson.__annotations__ def test_retains_file_hotspots_annotation(self) -> None: from muse.cli.commands.clones import _ClonesOutputJson assert "file_hotspots" in _ClonesOutputJson.__annotations__ def test_member_dict_exists(self) -> None: from muse.cli.commands.clones import _MemberDict # noqa: F401 def test_cluster_dict_exists(self) -> None: from muse.cli.commands.clones import _ClusterDict # noqa: F401 # --------------------------------------------------------------------------- # TestDocstrings — run() docstring documents new fields # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # 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, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") assert "\x1b" not in r.output def test_tier_near_json_no_ansi(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json", "--tier", "near") 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, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert data["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "-j") data = json.loads(r.output) assert data["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, clones_repo: pathlib.Path) -> None: r = _run(clones_repo, "code", "clones", "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float)