"""Supercharge tests for ``muse code hotspots`` — agent-usability gaps. There are NO existing hotspot tests (confirmed: no test_cmd_hotspots.py, no hotspot entries in the collected test suite). This file covers both correctness and agent-usability gaps: 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: _HotspotsOutputJson carries all fields including exit_code/duration_ms - 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 - Schema: JSON has required top-level keys (from_ref, to_ref, commits_analysed, truncated, filters, hotspots) - Filters: filters dict carries kind, language, include_imports, min_changes - Hotspot items: each item has address and changes keys - --min filter: filters before ranking - --top filter: bounds result count """ 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 repeated symbol changes to generate churn # --------------------------------------------------------------------------- @pytest.fixture() def hotspots_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo where billing.py::compute_total changes 3 times, creating churn. Commit 1 — seed: billing.py + helpers.py Commit 2 — modify compute_total (churn #1) Commit 3 — modify compute_total again (churn #2) Commit 4 — modify helpers.py::format_currency once Churn ranking after 4 commits: billing.py::compute_total → 3 changes (introduced + 2 modifications) helpers.py::format_currency → 2 changes (introduced + 1 modification) """ 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) class Invoice: pass """)) (tmp_path / "helpers.py").write_text(textwrap.dedent("""\ def format_currency(amount): return f"${amount:.2f}" """)) 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 — modify compute_total (tmp_path / "billing.py").write_text(textwrap.dedent("""\ def compute_total(items): return round(sum(items), 2) class Invoice: pass """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "round total") assert r.exit_code == 0, r.output # commit 3 — modify compute_total again (tmp_path / "billing.py").write_text(textwrap.dedent("""\ def compute_total(items, tax=0.0): return round(sum(items) * (1 + tax), 2) class Invoice: pass """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "add tax parameter") assert r.exit_code == 0, r.output # commit 4 — modify format_currency (tmp_path / "helpers.py").write_text(textwrap.dedent("""\ def format_currency(amount, symbol="$"): return f"{symbol}{amount:.2f}" """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "parameterise symbol") 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, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") json.loads(r.output) # must not raise def test_j_alias_has_hotspots_key(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert "hotspots" in json.loads(r.output) def test_j_alias_has_commits_analysed_key(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert "commits_analysed" in json.loads(r.output) def test_j_alias_has_filters_key(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert "filters" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, hotspots_repo: pathlib.Path ) -> None: r1 = _run(hotspots_repo, "code", "hotspots", "--json") r2 = _run(hotspots_repo, "code", "hotspots", "-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_hotspot_count_matches_json_flag( self, hotspots_repo: pathlib.Path ) -> None: r1 = _run(hotspots_repo, "code", "hotspots", "--json") r2 = _run(hotspots_repo, "code", "hotspots", "-j") assert len(json.loads(r1.output)["hotspots"]) == len( json.loads(r2.output)["hotspots"] ) def test_j_alias_with_top_filter(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j", "--top", "1") assert r.exit_code == 0, r.output assert len(json.loads(r.output)["hotspots"]) <= 1 def test_j_alias_with_kind_filter(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j", "--kind", "function") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["filters"]["kind"] == "function" # --------------------------------------------------------------------------- # 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, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert "duration_ms" in json.loads(r.output) def test_duration_ms_with_min_filter(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--min", "2") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_kind_filter(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--kind", "function") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) def test_duration_ms_with_top_filter(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--top", "1") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 # --------------------------------------------------------------------------- # 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, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_with_min_filter(self, hotspots_repo: pathlib.Path) -> None: """exit_code is 0 even when --min filters out all results.""" r = _run(hotspots_repo, "code", "hotspots", "--json", "--min", "999") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 assert data["hotspots"] == [] def test_exit_code_zero_with_kind_filter(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--kind", "function") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_top_filter(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--top", "1") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _HotspotsOutputJson carries all fields # --------------------------------------------------------------------------- class TestTypedDicts: """_HotspotsOutputJson must carry exit_code and duration_ms annotations.""" def test_hotspots_output_json_typeddict_exists(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "exit_code" in _HotspotsOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "duration_ms" in _HotspotsOutputJson.__annotations__ def test_retains_hotspots_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "hotspots" in _HotspotsOutputJson.__annotations__ def test_retains_commits_analysed_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "commits_analysed" in _HotspotsOutputJson.__annotations__ def test_retains_truncated_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "truncated" in _HotspotsOutputJson.__annotations__ def test_retains_filters_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "filters" in _HotspotsOutputJson.__annotations__ def test_retains_from_ref_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "from_ref" in _HotspotsOutputJson.__annotations__ def test_retains_to_ref_annotation(self) -> None: from muse.cli.commands.hotspots import _HotspotsOutputJson assert "to_ref" in _HotspotsOutputJson.__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, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert "\x1b" not in r.output def test_json_no_ansi_with_results(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--min", "1") assert "\x1b" not in r.output # --------------------------------------------------------------------------- # TestSchema — JSON shape correctness # --------------------------------------------------------------------------- class TestSchema: """JSON envelope must carry all documented top-level keys.""" def test_has_from_ref(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert "from_ref" in json.loads(r.output) def test_has_to_ref(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert "to_ref" in json.loads(r.output) def test_has_truncated(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert "truncated" in json.loads(r.output) def test_truncated_is_bool(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert isinstance(json.loads(r.output)["truncated"], bool) def test_commits_analysed_positive(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert json.loads(r.output)["commits_analysed"] > 0 def test_hotspot_items_have_address(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") data = json.loads(r.output) for item in data["hotspots"]: assert "address" in item def test_hotspot_items_have_changes(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") data = json.loads(r.output) for item in data["hotspots"]: assert "changes" in item assert item["changes"] >= 1 def test_filters_has_kind(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") data = json.loads(r.output) assert "kind" in data["filters"] def test_filters_has_min_changes(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") data = json.loads(r.output) assert "min_changes" in data["filters"] def test_filters_has_include_imports(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") data = json.loads(r.output) assert "include_imports" in data["filters"] def test_top_bounds_hotspot_count(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--top", "1") assert len(json.loads(r.output)["hotspots"]) <= 1 def test_min_filter_removes_low_churn(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json", "--min", "999") assert json.loads(r.output)["hotspots"] == [] # --------------------------------------------------------------------------- # 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, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert json.loads(r.output)["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "-j") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, hotspots_repo: pathlib.Path) -> None: r = _run(hotspots_repo, "code", "hotspots", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) # --------------------------------------------------------------------------- # TestRegisterFlags — argparse-level verification # --------------------------------------------------------------------------- class TestRegisterFlags: """Verify that register() wires --json / -j correctly.""" def _make_parser(self) -> "argparse.ArgumentParser": import argparse from muse.cli.commands.hotspots import register ap = argparse.ArgumentParser() subs = ap.add_subparsers() register(subs) return ap def test_json_flag_long(self) -> None: ns = self._make_parser().parse_args(["hotspots", "--json"]) assert ns.json_out is True def test_j_alias(self) -> None: ns = self._make_parser().parse_args(["hotspots", "-j"]) assert ns.json_out is True def test_default_is_text(self) -> None: ns = self._make_parser().parse_args(["hotspots"]) assert ns.json_out is False def test_dest_is_json_out(self) -> None: ns = self._make_parser().parse_args(["hotspots", "-j"]) assert hasattr(ns, "json_out") assert not hasattr(ns, "fmt")