"""Supercharge tests for ``muse code coupling`` — agent-usability gaps. The existing TestCoupling suite in test_code_commands.py covers correctness, JSON schema, all filters (--min, --top, --file, --from, --to, --max-commits), pair schema in both partner and pair modes, truncation, and error paths. 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 (both paths) - duration_ms: JSON output includes non-negative float duration_ms (both paths) - TypedDicts: _CouplingOutputJson 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 - Both paths: early-return (file-not-found) path also carries exit_code/duration_ms """ 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 where billing.py + models.py co-change twice # --------------------------------------------------------------------------- @pytest.fixture() def coupling_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with 3 commits where billing.py + models.py co-change twice. Commit 1 — billing.py only (seed). Commit 2 — billing.py + models.py change together (co-change #1). Commit 3 — billing.py + models.py change together again (co-change #2). """ 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(items): return sum(items) """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "seed billing") assert r.exit_code == 0, r.output # commit 2 — co-change #1 (tmp_path / "billing.py").write_text(textwrap.dedent("""\ def compute(items, tax=0.0): return sum(items) + tax """)) (tmp_path / "models.py").write_text(textwrap.dedent("""\ class Order: def total(self): return 0 """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "co-change 1: billing + models") assert r.exit_code == 0, r.output # commit 3 — co-change #2 (tmp_path / "billing.py").write_text(textwrap.dedent("""\ def compute(items, tax=0.0, discount=0.0): return sum(items) + tax - discount """)) (tmp_path / "models.py").write_text(textwrap.dedent("""\ class Order: def total(self): return 42 def apply(self): pass """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "co-change 2: billing + models again") 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, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") json.loads(r.output) # must not raise def test_j_alias_has_pairs_key(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") assert "pairs" in json.loads(r.output) def test_j_alias_has_commits_analysed_key(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") assert "commits_analysed" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, coupling_repo: pathlib.Path ) -> None: r1 = _run(coupling_repo, "code", "coupling", "--json") r2 = _run(coupling_repo, "code", "coupling", "-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_pair_count_matches_json_flag( self, coupling_repo: pathlib.Path ) -> None: r1 = _run(coupling_repo, "code", "coupling", "--json", "--min", "1") r2 = _run(coupling_repo, "code", "coupling", "-j", "--min", "1") assert len(json.loads(r1.output)["pairs"]) == len(json.loads(r2.output)["pairs"]) def test_j_alias_with_file_filter(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j", "--file", "billing.py", "--min", "1") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["filters"]["file"] == "billing.py" def test_j_alias_with_min_filter(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j", "--min", "2") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["filters"]["min_count"] == 2 # --------------------------------------------------------------------------- # 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, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") assert "duration_ms" in json.loads(r.output) def test_duration_ms_on_file_not_found_path( self, coupling_repo: pathlib.Path ) -> None: """Early-return (file-not-found) path must also carry duration_ms.""" r = _run(coupling_repo, "code", "coupling", "--json", "--file", "nonexistent_xyz.py") assert r.exit_code == 0, r.output data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_file_filter(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json", "--file", "billing.py", "--min", "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, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_on_file_not_found_path( self, coupling_repo: pathlib.Path ) -> None: """Early-return (file-not-found) path must also carry exit_code = 0.""" r = _run(coupling_repo, "code", "coupling", "--json", "--file", "nonexistent_xyz.py") assert r.exit_code == 0, r.output data = json.loads(r.output) assert "exit_code" in data assert data["exit_code"] == 0 def test_exit_code_zero_with_filters(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json", "--min", "2", "--top", "5") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_file_filter(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json", "--file", "billing.py", "--min", "1") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _CouplingOutputJson carries the new fields # --------------------------------------------------------------------------- class TestTypedDicts: """_CouplingOutputJson must carry exit_code and duration_ms annotations.""" def test_coupling_output_json_typeddict_exists(self) -> None: from muse.cli.commands.coupling import _CouplingOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.coupling import _CouplingOutputJson assert "exit_code" in _CouplingOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.coupling import _CouplingOutputJson assert "duration_ms" in _CouplingOutputJson.__annotations__ def test_retains_pairs_annotation(self) -> None: from muse.cli.commands.coupling import _CouplingOutputJson assert "pairs" in _CouplingOutputJson.__annotations__ def test_retains_commits_analysed_annotation(self) -> None: from muse.cli.commands.coupling import _CouplingOutputJson assert "commits_analysed" in _CouplingOutputJson.__annotations__ def test_retains_truncated_annotation(self) -> None: from muse.cli.commands.coupling import _CouplingOutputJson assert "truncated" in _CouplingOutputJson.__annotations__ def test_retains_filters_annotation(self) -> None: from muse.cli.commands.coupling import _CouplingOutputJson assert "filters" in _CouplingOutputJson.__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, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") assert "\x1b" not in r.output def test_json_output_no_ansi_with_file_filter( self, coupling_repo: pathlib.Path ) -> None: r = _run(coupling_repo, "code", "coupling", "--json", "--file", "billing.py", "--min", "1") 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, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--json") assert json.loads(r.output)["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "-j") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, coupling_repo: pathlib.Path) -> None: r = _run(coupling_repo, "code", "coupling", "--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.coupling 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(['coupling']) assert ns.json_out is False def test_json_out_true_with_json_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['coupling', '--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(['coupling', '-j']) assert ns.json_out is True