"""Supercharge tests for ``muse code impact`` — agent-usability gaps. No prior tests existed for ``muse code impact``. This file covers: 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: _ImpactJson carries exit_code and duration_ms - ForwardJson: forward mode JSON carries exit_code and 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 - Shapes: reverse mode vs forward mode JSON shapes are distinct """ 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 — minimal Python repo with call relationships # --------------------------------------------------------------------------- @pytest.fixture() def impact_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with a simple call graph. core.py — compute(x) + validate(x) service.py — process(x) calls compute(x) api.py — handle(req) calls process(x) """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output (tmp_path / "core.py").write_text(textwrap.dedent("""\ def compute(x): return x * 2 def validate(x): return x > 0 """)) (tmp_path / "service.py").write_text(textwrap.dedent("""\ from core import compute def process(x): return compute(x) """)) (tmp_path / "api.py").write_text(textwrap.dedent("""\ from service import process def handle(req): return process(req) """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "seed impact repo") 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, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") json.loads(r.output) # must not raise def test_j_alias_has_blast_radius_key(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert "blast_radius" in json.loads(r.output) def test_j_alias_has_mode_key(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert "mode" in json.loads(r.output) def test_j_alias_same_keys_as_json_flag(self, impact_repo: pathlib.Path) -> None: r1 = _run(impact_repo, "code", "impact", "core.py::compute", "--json") r2 = _run(impact_repo, "code", "impact", "core.py::compute", "-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_mode_is_reverse(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert json.loads(r.output)["mode"] == "reverse" def test_j_alias_address_echoed(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert json.loads(r.output)["address"] == "core.py::compute" def test_j_alias_forward_mode(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j", "--forward") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["mode"] == "forward" def test_j_alias_total_is_int(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert isinstance(json.loads(r.output)["total"], int) # --------------------------------------------------------------------------- # 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, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert "duration_ms" in json.loads(r.output) def test_forward_mode_duration_ms_present(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json", "--forward") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) def test_duration_ms_under_2000ms(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert json.loads(r.output)["duration_ms"] < 2000 # --------------------------------------------------------------------------- # 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, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_forward_mode_exit_code_zero(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json", "--forward") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_leaf_symbol(self, impact_repo: pathlib.Path) -> None: """exit_code is 0 even for a symbol with no callers.""" r = _run(impact_repo, "code", "impact", "core.py::validate", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _ImpactJson carries exit_code and duration_ms # --------------------------------------------------------------------------- class TestTypedDicts: """_ImpactJson must carry exit_code and duration_ms annotations.""" def test_impact_json_typeddict_exists(self) -> None: from muse.cli.commands.impact import _ImpactJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.impact import _ImpactJson assert "exit_code" in _ImpactJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.impact import _ImpactJson assert "duration_ms" in _ImpactJson.__annotations__ def test_retains_blast_radius_annotation(self) -> None: from muse.cli.commands.impact import _ImpactJson assert "blast_radius" in _ImpactJson.__annotations__ def test_retains_mode_annotation(self) -> None: from muse.cli.commands.impact import _ImpactJson assert "mode" in _ImpactJson.__annotations__ def test_retains_address_annotation(self) -> None: from muse.cli.commands.impact import _ImpactJson assert "address" in _ImpactJson.__annotations__ def test_retains_total_annotation(self) -> None: from muse.cli.commands.impact import _ImpactJson assert "total" in _ImpactJson.__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, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "-j") assert "\x1b" not in r.output def test_forward_mode_no_ansi(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json", "--forward") assert "\x1b" not in r.output # --------------------------------------------------------------------------- # TestForwardMode — forward mode shape # --------------------------------------------------------------------------- class TestForwardMode: """--forward mode must emit a valid, distinct JSON shape.""" def test_forward_has_callees_key(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json", "--forward") assert r.exit_code == 0, r.output assert "callees" in json.loads(r.output) def test_forward_mode_field_is_forward(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json", "--forward") assert json.loads(r.output)["mode"] == "forward" def test_forward_has_total_key(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json", "--forward") data = json.loads(r.output) assert "total" in data assert isinstance(data["total"], int) def test_forward_and_json_not_reverse(self, impact_repo: pathlib.Path) -> None: r = _run(impact_repo, "code", "impact", "core.py::compute", "--json", "--forward") data = json.loads(r.output) assert "blast_radius" not in data # --------------------------------------------------------------------------- # 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.impact 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(["impact", "core.py::Fn", "--json"]) assert ns.json_out is True def test_j_alias(self) -> None: ns = self._make_parser().parse_args(["impact", "core.py::Fn", "-j"]) assert ns.json_out is True def test_default_is_text(self) -> None: ns = self._make_parser().parse_args(["impact", "core.py::Fn"]) assert ns.json_out is False def test_dest_is_json_out(self) -> None: ns = self._make_parser().parse_args(["impact", "core.py::Fn", "-j"]) assert hasattr(ns, "json_out") assert not hasattr(ns, "fmt")