"""Supercharge tests for ``muse code api-surface`` — agent-usability gaps. Coverage matrix --------------- - --json / -j: -j alias works identically to --json for list and diff modes - exit_code: every JSON output path includes it (0 on success) - duration_ms: every JSON output path includes it; non-negative float - TypedDicts: _ListJson, _DiffJson annotations exist with required fields - Docstrings: run() docstring mentions exit_code and duration_ms - ANSI: address / string fields in JSON never contain escape sequences - Performance: duration_ms stays < 1000 ms for small repos - Schema: semver_impact valid values, stability_pct in 0-100, breaking_count int """ from __future__ import annotations from collections.abc import Mapping import json import pathlib import textwrap import pytest from tests.cli_test_helper import CliRunner 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 _commit_ids(root: pathlib.Path) -> list[str]: """Return all commit IDs newest-first via muse log --json.""" r = _run(root, "log", "--json") assert r.exit_code == 0, r.output data = json.loads(r.output) return [c["commit_id"] for c in data["commits"]] # --------------------------------------------------------------------------- # Fixture — repo with two commits giving api-surface meaningful diff data # --------------------------------------------------------------------------- @pytest.fixture() def api_repo(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> pathlib.Path: """Code-domain repo with two commits that change the public API surface. Commit 1: Invoice class with compute_total + apply_discount + process_order Commit 2: rename compute_total → compute_invoice_total, add send_email (one removal = MAJOR semver impact) """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output # Commit 1 (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items): return sum(items) def apply_discount(self, total, pct): return total * (1 - pct) def process_order(invoice, items): return invoice.compute_total(items) """)) r1 = _run(tmp_path, "code", "add", "billing.py") assert r1.exit_code == 0, r1.output r2 = _run(tmp_path, "commit", "-m", "initial billing module") assert r2.exit_code == 0, r2.output # Commit 2 — rename compute_total (breaking), add send_email (MINOR) (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_invoice_total(self, items): return sum(items) def apply_discount(self, total, pct): return total * (1 - pct) def generate_pdf(self): return b"pdf" def process_order(invoice, items): return invoice.compute_invoice_total(items) def send_email(address): pass """)) r3 = _run(tmp_path, "code", "add", "billing.py") assert r3.exit_code == 0, r3.output r4 = _run(tmp_path, "commit", "-m", "rename compute_total, add generate_pdf + send_email") assert r4.exit_code == 0, r4.output return tmp_path # --------------------------------------------------------------------------- # TestJsonAlias — -j works identically to --json # --------------------------------------------------------------------------- class TestJsonAlias: """The -j shorthand must behave identically to --json.""" def test_j_alias_list_mode_exits_zero(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "-j") assert r.exit_code == 0, r.output def test_j_alias_list_mode_valid_json(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "-j") assert r.exit_code == 0, r.output json.loads(r.output) # must not raise def test_j_alias_list_mode_has_results_key(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "-j") data = json.loads(r.output) assert "results" in data def test_j_alias_diff_mode_exits_zero(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) assert len(ids) >= 2 r = _run(api_repo, "code", "api-surface", "-j", "--diff", ids[-1]) assert r.exit_code == 0, r.output def test_j_alias_diff_mode_valid_json(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "-j", "--diff", ids[-1]) json.loads(r.output) # must not raise def test_j_alias_list_same_keys_as_json_flag(self, api_repo: pathlib.Path) -> None: r1 = _run(api_repo, "code", "api-surface", "--json") r2 = _run(api_repo, "code", "api-surface", "-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_diff_same_keys_as_json_flag(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r1 = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) r2 = _run(api_repo, "code", "api-surface", "-j", "--diff", ids[-1]) 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()) # --------------------------------------------------------------------------- # TestDurationMs — every JSON path emits duration_ms # --------------------------------------------------------------------------- class TestDurationMs: """Every JSON output path must include a non-negative float duration_ms.""" def test_list_json_has_duration_ms(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert "duration_ms" in data def test_list_json_duration_ms_nonnegative(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert data["duration_ms"] >= 0 def test_list_json_duration_ms_is_float(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float) def test_diff_json_has_duration_ms(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert "duration_ms" in data def test_diff_json_duration_ms_nonnegative(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert data["duration_ms"] >= 0 def test_diff_json_duration_ms_is_float(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert isinstance(data["duration_ms"], float) def test_j_alias_duration_ms_present(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "-j") data = json.loads(r.output) assert "duration_ms" in data # --------------------------------------------------------------------------- # TestExitCode — every JSON path emits exit_code # --------------------------------------------------------------------------- class TestExitCode: """Every JSON output path must include exit_code; 0 on success.""" def test_list_json_has_exit_code(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert "exit_code" in data def test_list_json_exit_code_zero_on_success(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 def test_list_json_exit_code_is_int(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert isinstance(data["exit_code"], int) def test_diff_json_has_exit_code(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert "exit_code" in data def test_diff_json_exit_code_zero_on_success(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) # exit_code in JSON is 0 even when there are breaking changes # (breaking changes cause a non-zero process exit only with --breaking flag) data = json.loads(r.output) assert data["exit_code"] == 0 def test_diff_json_exit_code_is_int(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert isinstance(data["exit_code"], int) def test_list_exit_code_mirrors_process_exit(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert data["exit_code"] == r.exit_code def test_j_alias_exit_code_present(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "-j") data = json.loads(r.output) assert "exit_code" in data # --------------------------------------------------------------------------- # TestTypedDicts — envelope TypedDicts exist with the required fields # --------------------------------------------------------------------------- class TestTypedDicts: """_ListJson and _DiffJson TypedDicts must exist and carry exit_code/duration_ms.""" def test_list_json_typed_dict_exists(self) -> None: from muse.cli.commands.api_surface import _ListJson # noqa: F401 def test_list_json_has_exit_code_annotation(self) -> None: from muse.cli.commands.api_surface import _ListJson assert "exit_code" in _ListJson.__annotations__ def test_list_json_has_duration_ms_annotation(self) -> None: from muse.cli.commands.api_surface import _ListJson assert "duration_ms" in _ListJson.__annotations__ def test_list_json_has_results_annotation(self) -> None: from muse.cli.commands.api_surface import _ListJson assert "results" in _ListJson.__annotations__ def test_diff_json_typed_dict_exists(self) -> None: from muse.cli.commands.api_surface import _DiffJson # noqa: F401 def test_diff_json_has_exit_code_annotation(self) -> None: from muse.cli.commands.api_surface import _DiffJson assert "exit_code" in _DiffJson.__annotations__ def test_diff_json_has_duration_ms_annotation(self) -> None: from muse.cli.commands.api_surface import _DiffJson assert "duration_ms" in _DiffJson.__annotations__ def test_diff_json_has_semver_impact_annotation(self) -> None: from muse.cli.commands.api_surface import _DiffJson assert "semver_impact" in _DiffJson.__annotations__ def test_diff_json_has_breaking_count_annotation(self) -> None: from muse.cli.commands.api_surface import _DiffJson assert "breaking_count" in _DiffJson.__annotations__ def test_public_symbol_dict_exists(self) -> None: from muse.cli.commands.api_surface import _PublicSymbolDict # noqa: F401 # --------------------------------------------------------------------------- # TestDocstrings — run() docstring documents new fields # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # TestSchema — diff JSON shape and value constraints # --------------------------------------------------------------------------- class TestSchema: """Validate the shape and value constraints of the diff JSON output.""" def test_diff_json_semver_impact_valid(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert data["semver_impact"] in ("MAJOR", "MINOR", "PATCH", "NONE") def test_diff_json_stability_pct_in_range(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert 0 <= data["stability_pct"] <= 100 def test_diff_json_breaking_count_is_int(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert isinstance(data["breaking_count"], int) assert data["breaking_count"] >= 0 def test_diff_json_added_is_list(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert isinstance(data["added"], list) def test_diff_json_removed_is_list(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert isinstance(data["removed"], list) def test_diff_json_changed_is_list(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert isinstance(data["changed"], list) def test_diff_json_changed_entries_have_breaking_flag(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) for entry in data["changed"]: assert "breaking" in entry assert isinstance(entry["breaking"], bool) def test_list_json_total_matches_results_len(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert data["total"] == len(data["results"]) def test_list_json_results_have_address_and_kind(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) for entry in data["results"]: assert "address" in entry assert "kind" in entry # --------------------------------------------------------------------------- # TestAnsiSanitization — JSON fields must not contain terminal escape codes # --------------------------------------------------------------------------- class TestAnsiSanitization: """No ANSI escape sequences in JSON string fields.""" def test_list_json_no_ansi_in_output(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") assert "\x1b" not in r.output def test_diff_json_no_ansi_in_output(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) assert "\x1b" not in r.output def test_list_json_addresses_no_ansi(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) for entry in data["results"]: assert "\x1b" not in entry["address"] # --------------------------------------------------------------------------- # TestPerformance — duration_ms stays in a reasonable range # --------------------------------------------------------------------------- class TestPerformance: """duration_ms must be non-negative and under 1000 ms for small repos.""" def test_list_json_duration_under_1000ms(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert data["duration_ms"] < 1000 def test_diff_json_duration_under_1000ms(self, api_repo: pathlib.Path) -> None: ids = _commit_ids(api_repo) r = _run(api_repo, "code", "api-surface", "--json", "--diff", ids[-1]) data = json.loads(r.output) assert data["duration_ms"] < 1000 def test_duration_ms_is_float_not_int(self, api_repo: pathlib.Path) -> None: r = _run(api_repo, "code", "api-surface", "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float)