"""Supercharge tests for ``muse code grep`` — agent-usability gaps. The existing test_cmd_grep.py covers correctness, --regex, --kind, --language, --file, --count, --hashes, --commit, --json schema (source_ref, working_tree, pattern, total_matches, results), qualified-name search, ReDoS guards, and a 1000-symbol stress test. 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: _GrepOutputJson 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 """ 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 repo with named symbols # --------------------------------------------------------------------------- @pytest.fixture() def grep_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with two Python files and several named symbols. billing.py — Invoice class + validate_amount function auth.py — verify_token function + AuthError class """ 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("""\ class Invoice: def compute_total(self, items): return sum(items) def validate_amount(amount): if amount < 0: raise ValueError("negative amount") return amount """)) (tmp_path / "auth.py").write_text(textwrap.dedent("""\ class AuthError(Exception): pass def verify_token(token): if not token: raise AuthError("missing token") return True """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "seed grep 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, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") json.loads(r.output) # must not raise def test_j_alias_has_results_key(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") assert "results" in json.loads(r.output) def test_j_alias_has_total_matches_key(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") assert "total_matches" in json.loads(r.output) def test_j_alias_has_pattern_key(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") assert "pattern" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, grep_repo: pathlib.Path ) -> None: r1 = _run(grep_repo, "code", "grep", "validate", "--json") r2 = _run(grep_repo, "code", "grep", "validate", "-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_match_count_matches_json_flag( self, grep_repo: pathlib.Path ) -> None: r1 = _run(grep_repo, "code", "grep", "validate", "--json") r2 = _run(grep_repo, "code", "grep", "validate", "-j") assert json.loads(r1.output)["total_matches"] == json.loads(r2.output)["total_matches"] def test_j_alias_pattern_echoed(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "Invoice", "-j") assert json.loads(r.output)["pattern"] == "Invoice" def test_j_alias_no_match_empty_results(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "zzz_never", "-j") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["results"] == [] assert data["total_matches"] == 0 def test_j_alias_with_kind_filter(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "Invoice", "-j", "--kind", "class") assert r.exit_code == 0, r.output data = json.loads(r.output) for res in data["results"]: assert res["kind"] == "class" # --------------------------------------------------------------------------- # 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, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") assert "duration_ms" in json.loads(r.output) def test_duration_ms_no_results(self, grep_repo: pathlib.Path) -> None: """duration_ms present even when no symbols match.""" r = _run(grep_repo, "code", "grep", "zzz_never", "--json") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_kind_filter(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "Invoice", "--json", "--kind", "class") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) def test_duration_ms_with_regex(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "^validate", "--json", "--regex") 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, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_empty_results(self, grep_repo: pathlib.Path) -> None: """exit_code is 0 even when no symbols match.""" r = _run(grep_repo, "code", "grep", "zzz_never", "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 assert data["results"] == [] def test_exit_code_zero_with_kind_filter(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "Invoice", "--json", "--kind", "class") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_regex(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate.*", "--json", "--regex") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _GrepOutputJson carries all fields # --------------------------------------------------------------------------- class TestTypedDicts: """_GrepOutputJson must carry exit_code and duration_ms annotations.""" def test_grep_output_json_typeddict_exists(self) -> None: from muse.cli.commands.grep import _GrepOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.grep import _GrepOutputJson assert "exit_code" in _GrepOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.grep import _GrepOutputJson assert "duration_ms" in _GrepOutputJson.__annotations__ def test_retains_results_annotation(self) -> None: from muse.cli.commands.grep import _GrepOutputJson assert "results" in _GrepOutputJson.__annotations__ def test_retains_total_matches_annotation(self) -> None: from muse.cli.commands.grep import _GrepOutputJson assert "total_matches" in _GrepOutputJson.__annotations__ def test_retains_pattern_annotation(self) -> None: from muse.cli.commands.grep import _GrepOutputJson assert "pattern" in _GrepOutputJson.__annotations__ def test_retains_source_ref_annotation(self) -> None: from muse.cli.commands.grep import _GrepOutputJson assert "source_ref" in _GrepOutputJson.__annotations__ def test_retains_working_tree_annotation(self) -> None: from muse.cli.commands.grep import _GrepOutputJson assert "working_tree" in _GrepOutputJson.__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, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "-j") assert "\x1b" not in r.output def test_json_no_ansi_with_results(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "Invoice", "--json") 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, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--json") assert json.loads(r.output)["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "Invoice", "-j") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, grep_repo: pathlib.Path) -> None: r = _run(grep_repo, "code", "grep", "validate", "--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.grep 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(["grep", "X", "--json"]) assert ns.json_out is True def test_j_alias(self) -> None: ns = self._make_parser().parse_args(["grep", "X", "-j"]) assert ns.json_out is True def test_default_is_text(self) -> None: ns = self._make_parser().parse_args(["grep", "X"]) assert ns.json_out is False def test_dest_is_json_out(self) -> None: ns = self._make_parser().parse_args(["grep", "X", "-j"]) assert hasattr(ns, "json_out") assert not hasattr(ns, "fmt")