"""Supercharge tests for ``muse code entangle`` — agent-usability gaps. The existing TestEntangle in test_code_commands.py covers correctness, JSON schema, pair schema, co-change rate, filters (--top, --min-co-changes, --min-rate, --symbol, --since, --include-same-file), sorting, and validation. 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: _EntangleOutputJson 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 — two files that co-change with no import link # --------------------------------------------------------------------------- @pytest.fixture() def entangle_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo where billing.py::Invoice and serializers.py::to_json co-change twice but share no import link — a textbook entanglement. Commit 1 — seed both files. Commit 2 — both symbols change together (co-change #1). Commit 3 — both symbols change 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("""\ class Invoice: def compute_total(self, items): return sum(items) """)) (tmp_path / "serializers.py").write_text(textwrap.dedent("""\ def to_json(obj): return str(obj) """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "seed") assert r.exit_code == 0, r.output # commit 2 — co-change #1 (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items): return round(sum(items), 2) """)) (tmp_path / "serializers.py").write_text(textwrap.dedent("""\ def to_json(obj): import json return json.dumps(obj) """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "co-change 1") assert r.exit_code == 0, r.output # commit 3 — co-change #2 (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items): return round(sum(items), 4) """)) (tmp_path / "serializers.py").write_text(textwrap.dedent("""\ def to_json(obj): import json return json.dumps(obj, indent=2) """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "co-change 2") 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, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") json.loads(r.output) # must not raise def test_j_alias_has_pairs_key(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert "pairs" in json.loads(r.output) def test_j_alias_has_commits_analysed_key(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert "commits_analysed" in json.loads(r.output) def test_j_alias_has_filters_key(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert "filters" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, entangle_repo: pathlib.Path ) -> None: r1 = _run(entangle_repo, "code", "entangle", "--json") r2 = _run(entangle_repo, "code", "entangle", "-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, entangle_repo: pathlib.Path ) -> None: r1 = _run(entangle_repo, "code", "entangle", "--json", "--min-co-changes", "1") r2 = _run(entangle_repo, "code", "entangle", "-j", "--min-co-changes", "1") assert len(json.loads(r1.output)["pairs"]) == len(json.loads(r2.output)["pairs"]) def test_j_alias_with_min_co_changes(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j", "--min-co-changes", "1") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["filters"]["min_co_changes"] == 1 def test_j_alias_with_top_filter(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j", "--top", "5") assert r.exit_code == 0, r.output assert len(json.loads(r.output)["pairs"]) <= 5 # --------------------------------------------------------------------------- # 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, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert "duration_ms" in json.loads(r.output) def test_duration_ms_with_min_co_changes(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json", "--min-co-changes", "1") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_min_rate(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json", "--min-rate", "0.5", "--min-co-changes", "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, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_with_min_co_changes( self, entangle_repo: pathlib.Path ) -> None: r = _run(entangle_repo, "code", "entangle", "--json", "--min-co-changes", "1") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_top_filter(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json", "--top", "5") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_empty_result(self, entangle_repo: pathlib.Path) -> None: """exit_code is 0 even when no pairs meet the threshold.""" r = _run(entangle_repo, "code", "entangle", "--json", "--min-co-changes", "999") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 assert data["pairs"] == [] # --------------------------------------------------------------------------- # TestTypedDicts — _EntangleOutputJson carries exit_code/duration_ms # --------------------------------------------------------------------------- class TestTypedDicts: """_EntangleOutputJson must carry exit_code and duration_ms annotations.""" def test_entangle_output_json_typeddict_exists(self) -> None: from muse.cli.commands.entangle import _EntangleOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.entangle import _EntangleOutputJson assert "exit_code" in _EntangleOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.entangle import _EntangleOutputJson assert "duration_ms" in _EntangleOutputJson.__annotations__ def test_retains_pairs_annotation(self) -> None: from muse.cli.commands.entangle import _EntangleOutputJson assert "pairs" in _EntangleOutputJson.__annotations__ def test_retains_commits_analysed_annotation(self) -> None: from muse.cli.commands.entangle import _EntangleOutputJson assert "commits_analysed" in _EntangleOutputJson.__annotations__ def test_retains_truncated_annotation(self) -> None: from muse.cli.commands.entangle import _EntangleOutputJson assert "truncated" in _EntangleOutputJson.__annotations__ def test_retains_filters_annotation(self) -> None: from muse.cli.commands.entangle import _EntangleOutputJson assert "filters" in _EntangleOutputJson.__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, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert "\x1b" not in r.output def test_json_output_no_ansi_with_results(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json", "--min-co-changes", "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, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--json") assert json.loads(r.output)["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "-j") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, entangle_repo: pathlib.Path) -> None: r = _run(entangle_repo, "code", "entangle", "--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.entangle 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(['entangle']) assert ns.json_out is False def test_json_out_true_with_json_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['entangle', '--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(['entangle', '-j']) assert ns.json_out is True