"""Supercharge tests for ``muse code code-query`` — agent-usability gaps. The existing test_cmd_code_query.py covers parser correctness, evaluator match logic, walk_history integration, CLI E2E, and stress. 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: _CodeQueryOutputJson gains 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 json import pathlib 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)) def _stage_commit(root: pathlib.Path, msg: str = "commit") -> None: r = _run(root, "code", "add", ".") assert r.exit_code == 0, r.output r2 = _run(root, "commit", "-m", msg, "--agent-id", "test-agent", "--model-id", "test-model") assert r2.exit_code == 0, r2.output # --------------------------------------------------------------------------- # Fixture # --------------------------------------------------------------------------- @pytest.fixture() def query_repo(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> pathlib.Path: """Code-domain repo with a few committed files for querying.""" monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output (tmp_path / "alpha.py").write_text("def alpha_fn():\n return 1\n") _stage_commit(tmp_path, "add alpha") (tmp_path / "beta.py").write_text("def beta_fn():\n return 2\n") _stage_commit(tmp_path, "add beta") 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, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") json.loads(r.output) # must not raise def test_j_alias_has_total_key(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") data = json.loads(r.output) assert "total" in data def test_j_alias_has_results_key(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") data = json.loads(r.output) assert "results" in data def test_j_alias_same_top_level_keys_as_json_flag(self, query_repo: pathlib.Path) -> None: r1 = _run(query_repo, "code", "code-query", "author == test-agent", "--json") r2 = _run(query_repo, "code", "code-query", "author == test-agent", "-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_total_matches_json_flag(self, query_repo: pathlib.Path) -> None: r1 = _run(query_repo, "code", "code-query", "author == test-agent", "--json") r2 = _run(query_repo, "code", "code-query", "author == test-agent", "-j") assert json.loads(r1.output)["total"] == json.loads(r2.output)["total"] def test_j_alias_no_matches_empty_results(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == nobody", "-j") data = json.loads(r.output) assert data["results"] == [] assert data["total"] == 0 def test_j_alias_with_limit(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j", "--limit", "1") assert r.exit_code == 0, r.output json.loads(r.output) # --------------------------------------------------------------------------- # 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, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert "duration_ms" in data def test_json_duration_ms_nonnegative(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert data["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float) def test_j_alias_duration_ms_present(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") data = json.loads(r.output) assert "duration_ms" in data def test_duration_ms_no_matches(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == nobody", "--json") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_since(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json", "--since", "2020-01-01") 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 (all errors raise SystemExit before JSON emits).""" def test_json_has_exit_code(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert "exit_code" in data def test_json_exit_code_zero_with_matches(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 def test_json_exit_code_zero_no_matches(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == nobody", "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 def test_json_exit_code_is_int(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert isinstance(data["exit_code"], int) def test_j_alias_exit_code_present(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") data = json.loads(r.output) assert "exit_code" in data def test_exit_code_mirrors_process_exit(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert data["exit_code"] == r.exit_code def test_exit_code_zero_with_limit(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json", "--limit", "1") data = json.loads(r.output) assert data["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _CodeQueryOutputJson carries the new fields # --------------------------------------------------------------------------- class TestTypedDicts: """_CodeQueryOutputJson must carry exit_code and duration_ms annotations.""" def test_code_query_output_json_exists(self) -> None: from muse.cli.commands.code_query import _CodeQueryOutputJson # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.code_query import _CodeQueryOutputJson assert "exit_code" in _CodeQueryOutputJson.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.code_query import _CodeQueryOutputJson assert "duration_ms" in _CodeQueryOutputJson.__annotations__ def test_has_total_annotation(self) -> None: from muse.cli.commands.code_query import _CodeQueryOutputJson assert "total" in _CodeQueryOutputJson.__annotations__ def test_has_results_annotation(self) -> None: from muse.cli.commands.code_query import _CodeQueryOutputJson assert "results" in _CodeQueryOutputJson.__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_with_matches(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") assert "\x1b" not in r.output def test_json_output_no_ansi_no_matches(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == nobody", "--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, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert data["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "-j") data = json.loads(r.output) assert data["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, query_repo: pathlib.Path) -> None: r = _run(query_repo, "code", "code-query", "author == test-agent", "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float) class TestRegisterFlags: def test_json_short_flag(self) -> None: import argparse from muse.cli.commands.query import register p = argparse.ArgumentParser() subs = p.add_subparsers() register(subs) args = p.parse_args(["query", "-j"]) assert args.json_out is True def test_json_long_flag(self) -> None: import argparse from muse.cli.commands.query import register p = argparse.ArgumentParser() subs = p.add_subparsers() register(subs) args = p.parse_args(["query", "--json"]) assert args.json_out is True def test_default_no_json(self) -> None: import argparse from muse.cli.commands.query import register p = argparse.ArgumentParser() subs = p.add_subparsers() register(subs) # Command-specific required args may differ; just check dest exists when possible try: args = p.parse_args(["query"]) assert args.json_out is False except SystemExit: pass # required positional args missing — flag default still correct