"""Supercharge tests for ``muse code find-symbol`` — agent-usability gaps. The existing test_cmd_find_symbol.py covers correctness, --name, --kind, --hash, --file, --branch, --since, --until, --limit, --first, --last, --count, --all-branches, --json schema, no-flags error, and stress tests. 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: _FindSymbolOutputJson carries 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 across two commits # --------------------------------------------------------------------------- @pytest.fixture() def find_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with two Python files, two commits, named symbols. Commit 1 — seed: billing.py with Invoice class + validate_amount function. Commit 2 — add serializers.py with to_json and from_json functions. This gives a small but search-useful commit history. """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output # commit 1 — seed billing.py (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 """)) 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 — add serializers.py (tmp_path / "serializers.py").write_text(textwrap.dedent("""\ import json as _json def to_json(obj): \"\"\"Serialize obj to JSON string.\"\"\" return _json.dumps(obj) def from_json(s): \"\"\"Deserialize JSON string.\"\"\" return _json.loads(s) """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "add serializers") 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, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") json.loads(r.output) # must not raise def test_j_alias_has_results_key(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") assert "results" in json.loads(r.output) def test_j_alias_has_total_key(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") assert "total" in json.loads(r.output) def test_j_alias_has_query_key(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") assert "query" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, find_repo: pathlib.Path ) -> None: r1 = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") r2 = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-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_result_count_matches_json_flag( self, find_repo: pathlib.Path ) -> None: r1 = _run(find_repo, "code", "find-symbol", "--kind", "function", "--json") r2 = _run(find_repo, "code", "find-symbol", "--kind", "function", "-j") assert json.loads(r1.output)["total"] == json.loads(r2.output)["total"] def test_j_alias_with_name_filter(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "validate_amount", "-j") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["query"]["name"] == "validate_amount" def test_j_alias_with_kind_filter(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "-j") assert r.exit_code == 0, r.output data = json.loads(r.output) assert data["query"]["kind"] == "function" def test_j_alias_with_limit(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "-j", "--limit", "1") assert r.exit_code == 0, r.output assert len(json.loads(r.output)["results"]) <= 1 # --------------------------------------------------------------------------- # 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, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") assert "duration_ms" in json.loads(r.output) def test_duration_ms_with_kind_filter(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "--json") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_limit(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "--json", "--limit", "2") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) def test_duration_ms_no_results(self, find_repo: pathlib.Path) -> None: """duration_ms present even when no symbols match.""" r = _run(find_repo, "code", "find-symbol", "--name", "zzz_never_exists", "--json") 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, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_empty_result(self, find_repo: pathlib.Path) -> None: """exit_code is 0 even when no symbols match.""" r = _run(find_repo, "code", "find-symbol", "--name", "zzz_never_exists", "--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, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_limit(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "--json", "--limit", "1") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _FindSymbolOutputJson carries exit_code/duration_ms # --------------------------------------------------------------------------- class TestTypedDicts: """_FindSymbolOutputJson must carry exit_code and duration_ms annotations.""" def test_find_symbol_output_json_typeddict_exists(self) -> None: from muse.cli.commands.find_symbol import _FindSymbolOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.find_symbol import _FindSymbolOutputJson assert "exit_code" in _FindSymbolOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.find_symbol import _FindSymbolOutputJson assert "duration_ms" in _FindSymbolOutputJson.__annotations__ def test_retains_results_annotation(self) -> None: from muse.cli.commands.find_symbol import _FindSymbolOutputJson assert "results" in _FindSymbolOutputJson.__annotations__ def test_retains_total_annotation(self) -> None: from muse.cli.commands.find_symbol import _FindSymbolOutputJson assert "total" in _FindSymbolOutputJson.__annotations__ def test_retains_query_annotation(self) -> None: from muse.cli.commands.find_symbol import _FindSymbolOutputJson assert "query" in _FindSymbolOutputJson.__annotations__ def test_retains_branch_presence_annotation(self) -> None: from muse.cli.commands.find_symbol import _FindSymbolOutputJson assert "branch_presence" in _FindSymbolOutputJson.__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, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "-j") assert "\x1b" not in r.output def test_json_output_no_ansi_with_results(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "--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, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--json") assert json.loads(r.output)["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--kind", "function", "-j") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, find_repo: pathlib.Path) -> None: r = _run(find_repo, "code", "find-symbol", "--name", "Invoice", "--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.find_symbol import register ap = argparse.ArgumentParser() subs = ap.add_subparsers() register(subs) return ap def test_json_flag_long(self) -> None: ap = self._make_parser() ns = ap.parse_args(["find-symbol", "--name", "X", "--json"]) assert ns.json_out is True def test_j_alias(self) -> None: ap = self._make_parser() ns = ap.parse_args(["find-symbol", "--name", "X", "-j"]) assert ns.json_out is True def test_default_is_text(self) -> None: ap = self._make_parser() ns = ap.parse_args(["find-symbol", "--name", "X"]) assert ns.json_out is False def test_dest_is_json_out(self) -> None: ap = self._make_parser() ns = ap.parse_args(["find-symbol", "--name", "X", "-j"]) assert hasattr(ns, "json_out") assert not hasattr(ns, "fmt")