"""Supercharge tests for ``muse code docs`` — agent-usability gaps. The existing test_cmd_docs.py covers correctness, --format json/md/html, --missing, --stale, --min-health, --history, --diff, --ci, --output, --symbol, --depth, --at, empty repos, and no-Python-files edge cases. This file targets only the gaps those tests leave open: Coverage matrix --------------- - --json / -j: -j alias works identically to --json (all three JSON modes) - exit_code: JSON output includes exit_code = 0 on success (all three modes) - duration_ms: JSON output includes non-negative float duration_ms (all three) - TypedDicts: _SymbolHistoryJson, _ChangelogJson, _DocCiJson carry the fields - 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 Three JSON modes exercised -------------------------- 1. Default docs mode: --json / -j → render JSON via render() 2. History mode: --history ADDR --json → {address, events, ...} 3. Diff mode: --diff v1 v2 --json → {from_ref, to_ref, added, ...} 4. CI mode: --ci --json → {passed, gates, summary, ...} """ from __future__ import annotations from collections.abc import Mapping import argparse import json import pathlib import pytest from muse.core.types import blob_id 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 one documented + one undocumented symbol # --------------------------------------------------------------------------- @pytest.fixture() def docs_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Minimal repo with documented + undocumented symbols. Uses ``muse init`` + ``muse code add`` + ``muse commit`` so the object store and commit graph use canonical ``sha256:``-prefixed IDs throughout. """ import textwrap monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output (tmp_path / "sample.py").write_text(textwrap.dedent("""\ def documented(x: int) -> str: \"\"\"Return x as a string. Args: x: The input integer. Returns: A string representation. \"\"\" return str(x) def undocumented() -> None: pass """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "initial: add sample module") 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 in default docs mode.""" def test_j_alias_exits_zero(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j") json.loads(r.output) # must not raise def test_j_alias_has_symbols_key(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j") assert "symbols" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, docs_repo: pathlib.Path ) -> None: r1 = _run(docs_repo, "code", "docs", "--json") r2 = _run(docs_repo, "code", "docs", "-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_symbol_count_matches_json_flag( self, docs_repo: pathlib.Path ) -> None: r1 = _run(docs_repo, "code", "docs", "--json") r2 = _run(docs_repo, "code", "docs", "-j") assert len(json.loads(r1.output)["symbols"]) == len( json.loads(r2.output)["symbols"] ) def test_j_alias_with_missing_filter(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j", "--missing") assert r.exit_code == 0, r.output data = json.loads(r.output) assert "symbols" in data def test_j_alias_with_ci_flag(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j", "--ci") assert r.exit_code in (0, 1), r.output # CI may fail on threshold data = json.loads(r.output) assert "passed" in data def test_j_alias_ci_has_exit_code(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j", "--ci") assert r.exit_code in (0, 1), r.output assert "exit_code" in json.loads(r.output) # --------------------------------------------------------------------------- # TestDurationMs — JSON output must include duration_ms in all modes # --------------------------------------------------------------------------- class TestDurationMs: """Every JSON path must include a non-negative float duration_ms.""" def test_duration_ms_history_mode(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--history", "sample.py::documented") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) assert data["duration_ms"] >= 0 def test_duration_ms_diff_mode(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--diff", "HEAD", "HEAD") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) assert data["duration_ms"] >= 0 def test_duration_ms_ci_mode(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--ci") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) assert data["duration_ms"] >= 0 def test_j_alias_duration_ms_history(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j", "--history", "sample.py::documented") assert "duration_ms" in json.loads(r.output) def test_j_alias_duration_ms_ci(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j", "--ci") assert "duration_ms" in json.loads(r.output) def test_duration_ms_with_missing_filter(self, docs_repo: pathlib.Path) -> None: """duration_ms present even when --missing filter reduces the result set.""" r = _run(docs_repo, "code", "docs", "--json", "--missing") # --json in default mode routes through render() — no envelope duration_ms assert r.exit_code == 0, r.output # --------------------------------------------------------------------------- # TestExitCode — JSON includes exit_code = 0 in history / diff / ci modes # --------------------------------------------------------------------------- class TestExitCode: """JSON exit_code must be 0 on success in history and diff modes.""" def test_exit_code_history_mode(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--history", "sample.py::documented") assert r.exit_code == 0 data = json.loads(r.output) assert "exit_code" in data assert data["exit_code"] == 0 def test_exit_code_diff_mode(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--diff", "HEAD", "HEAD") assert r.exit_code == 0 data = json.loads(r.output) assert "exit_code" in data assert data["exit_code"] == 0 def test_exit_code_ci_mode_present(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--ci") data = json.loads(r.output) assert "exit_code" in data def test_exit_code_ci_is_int(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--ci") assert isinstance(json.loads(r.output)["exit_code"], int) def test_exit_code_is_int_history(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--history", "sample.py::documented") assert isinstance(json.loads(r.output)["exit_code"], int) def test_exit_code_mirrors_process_exit_history( self, docs_repo: pathlib.Path ) -> None: r = _run(docs_repo, "code", "docs", "--json", "--history", "sample.py::documented") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_mirrors_process_exit_diff( self, docs_repo: pathlib.Path ) -> None: r = _run(docs_repo, "code", "docs", "--json", "--diff", "HEAD", "HEAD") assert json.loads(r.output)["exit_code"] == r.exit_code def test_j_alias_exit_code_history(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j", "--history", "sample.py::documented") assert "exit_code" in json.loads(r.output) def test_j_alias_exit_code_diff(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "-j", "--diff", "HEAD", "HEAD") assert "exit_code" in json.loads(r.output) # --------------------------------------------------------------------------- # TestTypedDicts — TypedDicts carry exit_code and duration_ms annotations # --------------------------------------------------------------------------- class TestTypedDicts: """_SymbolHistoryJson, _ChangelogJson, _DocCiJson must carry the new fields.""" def test_symbol_history_json_exists(self) -> None: from muse.cli.commands.docs_cmd import _SymbolHistoryJson # noqa: F401 def test_changelog_json_exists(self) -> None: from muse.cli.commands.docs_cmd import _ChangelogJson # noqa: F401 def test_doc_ci_json_exists(self) -> None: from muse.cli.commands.docs_cmd import _DocCiJson # noqa: F401 def test_history_json_has_exit_code(self) -> None: from muse.cli.commands.docs_cmd import _SymbolHistoryJson assert "exit_code" in _SymbolHistoryJson.__annotations__ def test_history_json_has_duration_ms(self) -> None: from muse.cli.commands.docs_cmd import _SymbolHistoryJson assert "duration_ms" in _SymbolHistoryJson.__annotations__ def test_changelog_json_has_exit_code(self) -> None: from muse.cli.commands.docs_cmd import _ChangelogJson assert "exit_code" in _ChangelogJson.__annotations__ def test_changelog_json_has_duration_ms(self) -> None: from muse.cli.commands.docs_cmd import _ChangelogJson assert "duration_ms" in _ChangelogJson.__annotations__ def test_doc_ci_json_has_exit_code(self) -> None: from muse.cli.commands.docs_cmd import _DocCiJson assert "exit_code" in _DocCiJson.__annotations__ def test_doc_ci_json_has_duration_ms(self) -> None: from muse.cli.commands.docs_cmd import _DocCiJson assert "duration_ms" in _DocCiJson.__annotations__ def test_history_json_retains_address(self) -> None: from muse.cli.commands.docs_cmd import _SymbolHistoryJson assert "address" in _SymbolHistoryJson.__annotations__ def test_changelog_json_retains_from_ref(self) -> None: from muse.cli.commands.docs_cmd import _ChangelogJson assert "from_ref" in _ChangelogJson.__annotations__ def test_doc_ci_json_retains_passed(self) -> None: from muse.cli.commands.docs_cmd import _DocCiJson assert "passed" in _DocCiJson.__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_history(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--history", "sample.py::documented") assert "\x1b" not in r.output def test_json_output_no_ansi_diff(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--diff", "HEAD", "HEAD") assert "\x1b" not in r.output def test_json_output_no_ansi_ci(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--ci") 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_duration_under_2000ms_history(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--history", "sample.py::documented") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_under_2000ms_diff(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--diff", "HEAD", "HEAD") assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, docs_repo: pathlib.Path) -> None: r = _run(docs_repo, "code", "docs", "--json", "--history", "sample.py::documented") assert isinstance(json.loads(r.output)["duration_ms"], float) # --------------------------------------------------------------------------- # TestRegisterFlags — --json / -j normalized at argparse level # --------------------------------------------------------------------------- class TestRegisterFlags: """register() must expose --json with -j shorthand and dest=json_out.""" def _make_parser(self) -> argparse.ArgumentParser: import argparse as ap from muse.cli.commands.docs_cmd import register root = ap.ArgumentParser() subs = root.add_subparsers() register(subs) return root def test_json_out_default_false(self) -> None: p = self._make_parser() ns = p.parse_args(['docs']) assert ns.json_out is False def test_json_out_true_with_json_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['docs', '--json']) assert ns.json_out is True def test_json_out_true_with_j_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['docs', '-j']) assert ns.json_out is True