"""Supercharge tests for ``muse code age`` — agent-usability gaps. Coverage matrix --------------- - --json / -j: -j alias works identically to --json for list and explain modes - exit_code: every JSON output path includes it (0 on success) - duration_ms: every JSON output path includes it; non-negative float - TypedDicts: _AgeListJson, _ExplainJson, _NoSymbolsJson annotations exist - 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 normal operations """ 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 _first_symbol_address(root: pathlib.Path) -> str: """Return the address of the first symbol in the age JSON output.""" r = _run(root, "code", "age", "--json") assert r.exit_code == 0, r.output data = json.loads(r.output) syms = data["symbols"] assert syms, "age_repo should always have at least one symbol with history" return syms[0]["address"] # --------------------------------------------------------------------------- # Fixture — repo with commit history so symbols have age data # --------------------------------------------------------------------------- @pytest.fixture() def age_repo(tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch) -> pathlib.Path: """Repo with three commits that give billing.py symbols measurable age. Commit 1: create billing.py (Invoice class + compute_total + stable_fn) Commit 2: modify compute_total body → 1 impl change Commit 3: modify compute_total body → 2 impl changes """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output # Commit 1 — create the file. (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items): return sum(items) def stable_fn(): return 42 """)) r1 = _run(tmp_path, "code", "add", "billing.py") assert r1.exit_code == 0, r1.output r2 = _run(tmp_path, "commit", "-m", "initial billing") assert r2.exit_code == 0, r2.output # Commit 2 — impl change to compute_total. (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items): return round(sum(items), 2) def stable_fn(): return 42 """)) r3 = _run(tmp_path, "code", "add", "billing.py") assert r3.exit_code == 0, r3.output r4 = _run(tmp_path, "commit", "-m", "round result") assert r4.exit_code == 0, r4.output # Commit 3 — second impl change to compute_total. (tmp_path / "billing.py").write_text(textwrap.dedent("""\ class Invoice: def compute_total(self, items): total = sum(items) return round(total, 4) def stable_fn(): return 42 """)) r5 = _run(tmp_path, "code", "add", "billing.py") assert r5.exit_code == 0, r5.output r6 = _run(tmp_path, "commit", "-m", "higher precision") assert r6.exit_code == 0, r6.output return tmp_path # --------------------------------------------------------------------------- # TestJsonAlias — -j works identically to --json # --------------------------------------------------------------------------- class TestJsonAlias: """The -j shorthand must behave identically to --json.""" def test_j_alias_main_exits_zero(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "-j") assert r.exit_code == 0, r.output def test_j_alias_main_valid_json(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "-j") assert r.exit_code == 0, r.output json.loads(r.output) # must not raise def test_j_alias_main_has_symbols_key(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "-j") data = json.loads(r.output) assert "symbols" in data def test_j_alias_explain_exits_zero(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "-j") assert r.exit_code == 0, r.output def test_j_alias_explain_valid_json(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "-j") assert r.exit_code == 0, r.output json.loads(r.output) # must not raise def test_j_alias_same_top_level_keys_as_json_flag(self, age_repo: pathlib.Path) -> None: r1 = _run(age_repo, "code", "age", "--json") r2 = _run(age_repo, "code", "age", "-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_explain_same_keys_as_json_flag(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r1 = _run(age_repo, "code", "age", "--explain", addr, "--json") r2 = _run(age_repo, "code", "age", "--explain", addr, "-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()) # --------------------------------------------------------------------------- # TestDurationMs — every JSON path emits duration_ms # --------------------------------------------------------------------------- class TestDurationMs: """Every JSON output path must include a non-negative float duration_ms.""" def test_main_json_has_duration_ms(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) assert "duration_ms" in data def test_main_json_duration_ms_nonnegative(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) assert data["duration_ms"] >= 0 def test_main_json_duration_ms_is_float(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float) def test_explain_json_has_duration_ms(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") data = json.loads(r.output) assert "duration_ms" in data def test_explain_json_duration_ms_nonnegative(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") data = json.loads(r.output) assert data["duration_ms"] >= 0 def test_explain_json_duration_ms_is_float(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") data = json.loads(r.output) assert isinstance(data["duration_ms"], float) def test_j_alias_duration_ms_present(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "-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_main_json_has_exit_code(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) assert "exit_code" in data def test_main_json_exit_code_zero_on_success(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 def test_main_json_exit_code_is_int(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) assert isinstance(data["exit_code"], int) def test_explain_json_has_exit_code(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") data = json.loads(r.output) assert "exit_code" in data def test_explain_json_exit_code_zero_on_success(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") assert r.exit_code == 0 data = json.loads(r.output) assert data["exit_code"] == 0 def test_explain_json_exit_code_is_int(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") data = json.loads(r.output) assert isinstance(data["exit_code"], int) def test_j_alias_exit_code_present(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "-j") data = json.loads(r.output) assert "exit_code" in data def test_exit_code_mirrors_process_exit(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) assert data["exit_code"] == r.exit_code # --------------------------------------------------------------------------- # TestTypedDicts — envelope TypedDicts exist with the required fields # --------------------------------------------------------------------------- class TestTypedDicts: """_AgeListJson, _ExplainJson TypedDicts must exist and include new fields.""" def test_age_list_json_typed_dict_exists(self) -> None: from muse.cli.commands.age import _AgeListJson # noqa: F401 def test_age_list_json_has_exit_code_annotation(self) -> None: from muse.cli.commands.age import _AgeListJson assert "exit_code" in _AgeListJson.__annotations__ def test_age_list_json_has_duration_ms_annotation(self) -> None: from muse.cli.commands.age import _AgeListJson assert "duration_ms" in _AgeListJson.__annotations__ def test_age_list_json_has_symbols_annotation(self) -> None: from muse.cli.commands.age import _AgeListJson assert "symbols" in _AgeListJson.__annotations__ def test_explain_json_typed_dict_exists(self) -> None: from muse.cli.commands.age import _ExplainJson # noqa: F401 def test_explain_json_has_exit_code_annotation(self) -> None: from muse.cli.commands.age import _ExplainJson assert "exit_code" in _ExplainJson.__annotations__ def test_explain_json_has_duration_ms_annotation(self) -> None: from muse.cli.commands.age import _ExplainJson assert "duration_ms" in _ExplainJson.__annotations__ def test_explain_json_has_events_annotation(self) -> None: from muse.cli.commands.age import _ExplainJson assert "events" in _ExplainJson.__annotations__ def test_age_record_typed_dict_exists(self) -> None: from muse.cli.commands.age import _AgeRecord # noqa: F401 def test_age_record_has_est_survival_pct(self) -> None: from muse.cli.commands.age import _AgeRecord assert "est_survival_pct" in _AgeRecord.__annotations__ # --------------------------------------------------------------------------- # TestDocstrings — run() docstring documents new fields # --------------------------------------------------------------------------- class TestDocstrings: """run() must document exit_code in its docstring.""" def test_run_docstring_documents_fields(self) -> None: from muse.cli.commands.age import run assert "Exit codes" in run.__doc__ # --------------------------------------------------------------------------- # TestAnsiSanitization — JSON fields must not contain terminal escape codes # --------------------------------------------------------------------------- class TestAnsiSanitization: """No ANSI escape sequences in JSON string fields.""" def test_main_json_no_ansi_in_output(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") assert "\x1b" not in r.output def test_explain_json_no_ansi_in_output(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") assert "\x1b" not in r.output def test_main_json_addresses_no_ansi(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) for sym in data["symbols"]: assert "\x1b" not in sym["address"] def test_explain_json_address_no_ansi(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") data = json.loads(r.output) assert "\x1b" not in data["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_main_json_duration_under_1000ms(self, age_repo: pathlib.Path) -> None: r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) assert data["duration_ms"] < 1000 def test_explain_json_duration_under_1000ms(self, age_repo: pathlib.Path) -> None: addr = _first_symbol_address(age_repo) r = _run(age_repo, "code", "age", "--explain", addr, "--json") data = json.loads(r.output) assert data["duration_ms"] < 1000 def test_duration_ms_type_is_float_not_int(self, age_repo: pathlib.Path) -> None: """duration_ms must always be float, never int — even if value is 0.""" r = _run(age_repo, "code", "age", "--json") data = json.loads(r.output) # JSON floats with no decimal part can parse as int — check the raw string. import re m = re.search(r'"duration_ms"\s*:\s*([0-9.e+\-]+)', r.output) assert m is not None, "duration_ms not found in output" # Should contain a decimal point (e.g. "12.3", not "12"). assert isinstance(data["duration_ms"], float)