"""Supercharge tests for ``muse code dead`` — agent-usability gaps. The existing test_cmd_dead.py covers unit helpers (_module_is_imported, _matches_path_filter, _find_symbol_span, _delete_symbol_lines, _analyse_file, _is_test_file, _DeadCandidate), integration schema (--json, --kind, --count, --compare, --workers, --save-allowlist, --allowlist), security (--delete prompts), and stress (200-function file, 50-file codebase). 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 carries non-negative float (already present — verified here for completeness and regression guard) - TypedDicts: _DeadPayload gains exit_code annotation - Docstrings: run() docstring mentions exit_code and duration_ms - ANSI: JSON output never contains terminal escape sequences - Performance: duration_ms stays under 5000 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 — repo with an obvious dead-code candidate # --------------------------------------------------------------------------- @pytest.fixture() def dead_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with one referenced function and one dead (orphaned) function. Layout:: billing.py — Invoice class + process_order (referenced) utils.py — validate_amount (referenced by billing.py) orphaned_helper (never referenced, module not imported by anyone → HIGH confidence dead candidate) """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output (tmp_path / "billing.py").write_text(textwrap.dedent("""\ from utils import validate_amount class Invoice: def compute_total(self, items): return sum(items) def process_order(invoice, items): if not validate_amount(sum(items)): raise ValueError("bad amount") return invoice.compute_total(items) """)) (tmp_path / "utils.py").write_text(textwrap.dedent("""\ def validate_amount(amount): return amount > 0 def orphaned_helper(x): return x * 2 """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "initial") 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, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") json.loads(r.output) # must not raise def test_j_alias_has_results_key(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") assert "results" in json.loads(r.output) def test_j_alias_has_duration_ms_key(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") assert "duration_ms" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, dead_repo: pathlib.Path ) -> None: r1 = _run(dead_repo, "code", "dead", "--json") r2 = _run(dead_repo, "code", "dead", "-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, dead_repo: pathlib.Path ) -> None: r1 = _run(dead_repo, "code", "dead", "--json") r2 = _run(dead_repo, "code", "dead", "-j") assert len(json.loads(r1.output)["results"]) == len(json.loads(r2.output)["results"]) def test_j_alias_with_high_confidence_only(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j", "--high-confidence-only") assert r.exit_code == 0, r.output data = json.loads(r.output) for c in data["results"]: assert c["confidence"] == "high" def test_j_alias_with_kind_filter(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j", "--kind", "function") assert r.exit_code == 0, r.output data = json.loads(r.output) for c in data["results"]: assert c["kind"] == "function" # --------------------------------------------------------------------------- # TestDurationMs — JSON output must include duration_ms (regression guard) # --------------------------------------------------------------------------- class TestDurationMs: """duration_ms already exists — this class guards against regression.""" def test_json_has_duration_ms(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") assert "duration_ms" in json.loads(r.output) def test_duration_ms_with_high_confidence_filter( self, dead_repo: pathlib.Path ) -> None: r = _run(dead_repo, "code", "dead", "--json", "--high-confidence-only") data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_compare(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json", "--compare", "HEAD") data = json.loads(r.output) assert "duration_ms" in data assert isinstance(data["duration_ms"], float) # --------------------------------------------------------------------------- # 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, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_with_high_confidence_filter( self, dead_repo: pathlib.Path ) -> None: r = _run(dead_repo, "code", "dead", "--json", "--high-confidence-only") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_compare(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json", "--compare", "HEAD") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_kind_filter(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json", "--kind", "function") assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _DeadPayload carries exit_code annotation # --------------------------------------------------------------------------- class TestTypedDicts: """_DeadPayload must carry exit_code and duration_ms annotations.""" def test_dead_payload_typeddict_exists(self) -> None: from muse.cli.commands.dead import _DeadPayload # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.dead import _DeadPayload assert "exit_code" in _DeadPayload.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.dead import _DeadPayload assert "duration_ms" in _DeadPayload.__annotations__ def test_retains_results_annotation(self) -> None: from muse.cli.commands.dead import _DeadPayload assert "results" in _DeadPayload.__annotations__ def test_retains_high_confidence_count_annotation(self) -> None: from muse.cli.commands.dead import _DeadPayload assert "high_confidence_count" in _DeadPayload.__annotations__ def test_retains_source_annotation(self) -> None: from muse.cli.commands.dead import _DeadPayload assert "source" in _DeadPayload.__annotations__ def test_retains_total_files_scanned_annotation(self) -> None: from muse.cli.commands.dead import _DeadPayload assert "total_files_scanned" in _DeadPayload.__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, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") assert "\x1b" not in r.output def test_json_output_no_ansi_with_high_confidence( self, dead_repo: pathlib.Path ) -> None: r = _run(dead_repo, "code", "dead", "--json", "--high-confidence-only") assert "\x1b" not in r.output # --------------------------------------------------------------------------- # TestPerformance — duration_ms under 5000 ms for a small repo # --------------------------------------------------------------------------- class TestPerformance: """duration_ms must stay under 5000 ms for small repos. dead uses parallel AST workers so the budget is slightly higher than other commands (2000 ms is too tight for cold-start thread-pool overhead on CI runners). """ def test_json_duration_under_5000ms(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") assert json.loads(r.output)["duration_ms"] < 5000 def test_j_alias_duration_under_5000ms(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "-j") assert json.loads(r.output)["duration_ms"] < 5000 def test_duration_ms_is_float_not_int(self, dead_repo: pathlib.Path) -> None: r = _run(dead_repo, "code", "dead", "--json") 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.dead 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(['code', 'dead']) assert ns.json_out is False def test_json_out_true_with_json_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['code', 'dead', '--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(['code', 'dead', '-j']) assert ns.json_out is True