"""Supercharge tests for ``muse code coverage`` — agent-usability gaps. The existing TestCoverage suite in test_code_commands.py covers correctness, JSON schema, --exclude-dunder, --exclude-private, --min-callers, --exclude-self, --compare diff schema, --count, and --no-show-callers. 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: _CoveragePayload 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 argparse import json import os import pathlib import textwrap import pytest from tests.cli_test_helper import CliRunner, InvokeResult runner = CliRunner() _ADDR = "models.py::User" # --------------------------------------------------------------------------- # 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 — class with mixed covered/uncovered methods # --------------------------------------------------------------------------- @pytest.fixture() def coverage_repo( tmp_path: pathlib.Path, monkeypatch: pytest.MonkeyPatch ) -> pathlib.Path: """Repo with a User class where some methods are called, some are not. Layout:: models.py — class User with __init__, save, delete, to_dict api.py — calls User.__init__ and save (not delete or to_dict) Two commits so history analysis works correctly. """ monkeypatch.chdir(tmp_path) r = _run(tmp_path, "init", "--domain", "code") assert r.exit_code == 0, r.output # commit 1 — User class (tmp_path / "models.py").write_text(textwrap.dedent("""\ class User: def __init__(self, name): self.name = name def save(self): return True def delete(self): return False def to_dict(self): return {"name": self.name} """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "feat: add User class") assert r.exit_code == 0, r.output # commit 2 — callers (init + save used; delete + to_dict not used) (tmp_path / "api.py").write_text(textwrap.dedent("""\ from models import User def create_user(name): user = User(name) user.save() return user def update_user(name): user = User(name) user.save() return user """)) r = _run(tmp_path, "code", "add", ".") assert r.exit_code == 0, r.output r = _run(tmp_path, "commit", "-m", "feat: add api callers") 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, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert r.exit_code == 0, r.output def test_j_alias_valid_json(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) json.loads(r.output) # must not raise def test_j_alias_has_methods_key(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert "methods" in json.loads(r.output) def test_j_alias_has_percent_key(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert "percent" in json.loads(r.output) def test_j_alias_same_top_level_keys_as_json_flag( self, coverage_repo: pathlib.Path ) -> None: r1 = _run(coverage_repo, "code", "coverage", "--json", _ADDR) r2 = _run(coverage_repo, "code", "coverage", "-j", _ADDR) 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_method_count_matches_json_flag( self, coverage_repo: pathlib.Path ) -> None: r1 = _run(coverage_repo, "code", "coverage", "--json", _ADDR) r2 = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert len(json.loads(r1.output)["methods"]) == len(json.loads(r2.output)["methods"]) def test_j_alias_with_exclude_dunder(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", "--exclude-dunder", _ADDR) assert r.exit_code == 0, r.output assert json.loads(r.output)["filters"]["exclude_dunder"] is True def test_j_alias_address_reflected(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert json.loads(r.output)["address"] == _ADDR # --------------------------------------------------------------------------- # 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, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert "duration_ms" in json.loads(r.output) def test_json_duration_ms_nonnegative(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert json.loads(r.output)["duration_ms"] >= 0 def test_json_duration_ms_is_float(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert isinstance(json.loads(r.output)["duration_ms"], float) def test_j_alias_duration_ms_present(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert "duration_ms" in json.loads(r.output) def test_duration_ms_with_exclude_dunder(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", "--exclude-dunder", _ADDR) data = json.loads(r.output) assert "duration_ms" in data assert data["duration_ms"] >= 0 def test_duration_ms_with_compare(self, coverage_repo: pathlib.Path) -> None: """duration_ms present even when --compare diff analysis runs.""" r = _run(coverage_repo, "code", "coverage", "--json", "--compare", "HEAD", _ADDR) 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, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert "exit_code" in json.loads(r.output) def test_json_exit_code_zero(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_json_exit_code_is_int(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert isinstance(json.loads(r.output)["exit_code"], int) def test_j_alias_exit_code_present(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert "exit_code" in json.loads(r.output) def test_exit_code_mirrors_process_exit(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert json.loads(r.output)["exit_code"] == r.exit_code def test_exit_code_zero_with_exclude_dunder( self, coverage_repo: pathlib.Path ) -> None: r = _run(coverage_repo, "code", "coverage", "--json", "--exclude-dunder", _ADDR) assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 def test_exit_code_zero_with_compare(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", "--compare", "HEAD", _ADDR) assert r.exit_code == 0 assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # TestTypedDicts — _CoveragePayload carries the new fields # --------------------------------------------------------------------------- class TestTypedDicts: """_CoveragePayload must carry exit_code and duration_ms annotations.""" def test_coverage_payload_typeddict_exists(self) -> None: from muse.cli.commands.coverage import _CoveragePayload # noqa: F401 def test_has_exit_code_annotation(self) -> None: from muse.cli.commands.coverage import _CoveragePayload assert "exit_code" in _CoveragePayload.__annotations__ def test_has_duration_ms_annotation(self) -> None: from muse.cli.commands.coverage import _CoveragePayload assert "duration_ms" in _CoveragePayload.__annotations__ def test_retains_address_annotation(self) -> None: from muse.cli.commands.coverage import _CoveragePayload assert "address" in _CoveragePayload.__annotations__ def test_retains_methods_annotation(self) -> None: from muse.cli.commands.coverage import _CoveragePayload assert "methods" in _CoveragePayload.__annotations__ def test_retains_percent_annotation(self) -> None: from muse.cli.commands.coverage import _CoveragePayload assert "percent" in _CoveragePayload.__annotations__ def test_retains_filters_annotation(self) -> None: from muse.cli.commands.coverage import _CoveragePayload assert "filters" in _CoveragePayload.__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, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert "\x1b" not in r.output def test_j_alias_output_no_ansi(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert "\x1b" not in r.output def test_json_output_no_ansi_with_exclude_dunder( self, coverage_repo: pathlib.Path ) -> None: r = _run(coverage_repo, "code", "coverage", "--json", "--exclude-dunder", _ADDR) 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, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) assert json.loads(r.output)["duration_ms"] < 2000 def test_j_alias_duration_under_2000ms(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "-j", _ADDR) assert json.loads(r.output)["duration_ms"] < 2000 def test_duration_ms_is_float_not_int(self, coverage_repo: pathlib.Path) -> None: r = _run(coverage_repo, "code", "coverage", "--json", _ADDR) 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.coverage 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(['coverage', 'billing.py::Invoice']) assert ns.json_out is False def test_json_out_true_with_json_flag(self) -> None: p = self._make_parser() ns = p.parse_args(['coverage', 'billing.py::Invoice', '--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(['coverage', 'billing.py::Invoice', '-j']) assert ns.json_out is True