"""Seven-tier tests for ``muse/cli/commands/test_cmd.py``. Tiers ----- Unit — TypedDict fields (_FullJson schema_version); _fatal human/JSON; _progress_cb icons; _history_to_json roundtrip; _gate_to_json; _ci_to_json; _run_result_to_record; _print_history; _print_pre_run; _print_dry_run human/JSON; _print_summary. Integration — -j alias parity; register() has -j; docstrings document schema_version/exit_code/duration_ms. End-to-end — --dry-run (no pytest); --history (no pytest); --flaky (no pytest); --json --dry-run; --json --history; invalid repo; -j --dry-run. Stress — 1 000 _history_to_json calls; 500 _gate_to_json calls; _print_history with 200 entries. Data integrity — JSON fields correct types; schema_version present on all modes; _FullJson required fields; _history_to_json preserves every field. Security — hostile node_id in history survives JSON; ANSI in messages; SQL injection in gate name; long stdout in gate result. Performance — 1 000 _gate_to_json under 0.5 s; duration_ms in --dry-run JSON. """ from __future__ import annotations from collections.abc import Mapping import json import os import pathlib import textwrap import threading import time from typing import get_type_hints import pytest from tests.cli_test_helper import CliRunner, InvokeResult runner = CliRunner() # ────────────────────────────────────────────────────────────────────────────── # Shared helpers — minimal typed-dict factories # ────────────────────────────────────────────────────────────────────────────── def _make_history_summary(**kw: str) -> Mapping[str, object]: from muse.core.test_history import HistorySummary base = dict( node_id="tests/test_foo.py::test_bar", total_runs=10, pass_count=8, fail_count=2, skip_count=0, flaky=True, avg_duration_ms=123.4, last_outcome="passed", last_run_timestamp="2026-01-01T00:00:00+00:00", fail_streak=0, ) base.update(kw) return HistorySummary(**base) def _make_gate(**kw: str) -> Mapping[str, object]: from muse.core.ci import GateResult base = dict( name="lint", command=["ruff", "check", "."], exit_code=0, duration_ms=120.0, stdout="All checks passed.", stderr="", required=True, passed=True, timed_out=False, ) base.update(kw) return GateResult(**base) def _make_ci_result(**kw: str) -> Mapping[str, object]: from muse.core.ci import CiRunResult base = dict( passed=True, gates=[_make_gate()], total_duration_ms=200.0, timestamp="2026-01-01T00:00:00+00:00", ) base.update(kw) return CiRunResult(**base) def _make_run_result(**kw: str) -> Mapping[str, object]: from muse.core.test_runner import RunResult base = dict( run_id="run-1", targets=[], exit_code=0, duration_ms=500.0, results=[], total=3, passed=3, failed=0, errored=0, skipped=0, timed_out=False, json_report_available=True, stdout="", stderr="", ) base.update(kw) return RunResult(**base) def _make_selection(**kw: str) -> Mapping[str, object]: from muse.core.test_selection import SelectionResult base = dict( changed_addresses=["src/foo.py::bar"], test_targets=[], covered_addresses=["src/foo.py::bar"], uncovered_addresses=[], coverage_fraction=1.0, fallback_used=False, ) base.update(kw) return SelectionResult(**base) def _commit(repo: pathlib.Path, files: Mapping[str, str], message: str) -> None: for name, content in files.items(): path = repo / name path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content, encoding="utf-8") saved = os.getcwd() try: os.chdir(repo) runner.invoke(None, ["code", "add", "."]) runner.invoke(None, ["commit", "-m", message]) finally: os.chdir(saved) def _invoke(repo: pathlib.Path, args: list[str]) -> InvokeResult: saved = os.getcwd() try: os.chdir(repo) return runner.invoke(None, args) finally: os.chdir(saved) @pytest.fixture() def test_repo(tmp_path: pathlib.Path) -> pathlib.Path: """Minimal repo with a real test file so history/dry-run modes work.""" saved = os.getcwd() try: os.chdir(tmp_path) runner.invoke(None, ["init"]) finally: os.chdir(saved) _commit(tmp_path, { "src/calc.py": textwrap.dedent("""\ def add(a, b): return a + b """), "tests/test_calc.py": textwrap.dedent("""\ from src.calc import add def test_add(): assert add(1, 2) == 3 """), }, "feat: add calc and test") return tmp_path # ────────────────────────────────────────────────────────────────────────────── # Unit — TypedDict / _FullJson schema_version # ────────────────────────────────────────────────────────────────────────────── class TestTypedDict: def test_full_json_has_schema_version(self) -> None: from muse.cli.commands.test_cmd import _FullJson assert "schema" in get_type_hints(_FullJson) def test_full_json_has_mode(self) -> None: from muse.cli.commands.test_cmd import _FullJson assert "mode" in get_type_hints(_FullJson) def test_selection_json_fields(self) -> None: from muse.cli.commands.test_cmd import _SelectionJson hints = get_type_hints(_SelectionJson) for f in ("changed_addresses", "covered_addresses", "uncovered_addresses", "coverage_fraction", "fallback_used", "targets"): assert f in hints, f"missing: {f}" def test_run_json_has_exit_code(self) -> None: from muse.cli.commands.test_cmd import _RunJson assert "exit_code" in get_type_hints(_RunJson) def test_run_json_has_duration_ms(self) -> None: from muse.cli.commands.test_cmd import _RunJson assert "duration_ms" in get_type_hints(_RunJson) def test_history_json_fields(self) -> None: from muse.cli.commands.test_cmd import _HistoryJson hints = get_type_hints(_HistoryJson) for f in ("node_id", "total_runs", "pass_count", "fail_count", "flaky", "avg_duration_ms", "fail_streak"): assert f in hints, f"missing: {f}" def test_ci_gate_json_fields(self) -> None: from muse.cli.commands.test_cmd import _CiGateJson hints = get_type_hints(_CiGateJson) for f in ("name", "command", "exit_code", "duration_ms", "required", "passed", "timed_out"): assert f in hints, f"missing: {f}" # ────────────────────────────────────────────────────────────────────────────── # Unit — _fatal # ────────────────────────────────────────────────────────────────────────────── class TestFatal: def test_human_mode_exits_1(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _fatal with pytest.raises(SystemExit) as exc_info: _fatal("something broke", json_out=False) assert exc_info.value.code == 1 def test_human_mode_prints_to_stderr(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _fatal with pytest.raises(SystemExit): _fatal("something broke", json_out=False) assert "something broke" in capsys.readouterr().err def test_json_mode_prints_error_key(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _fatal with pytest.raises(SystemExit): _fatal("bad config", json_out=True) d = json.loads(capsys.readouterr().out) assert d["error"] == "bad config" def test_json_mode_exits_1(self) -> None: from muse.cli.commands.test_cmd import _fatal with pytest.raises(SystemExit) as exc_info: _fatal("x", json_out=True) assert exc_info.value.code == 1 # ────────────────────────────────────────────────────────────────────────────── # Unit — _progress_cb # ────────────────────────────────────────────────────────────────────────────── class TestProgressCb: def _case(self, outcome: str) -> Mapping[str, object]: from muse.core.test_runner import CaseResult return CaseResult(node_id="t::t", outcome=outcome, duration_ms=1.0) def test_passed_prints_dot(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _progress_cb _progress_cb(self._case("passed")) assert capsys.readouterr().err == "." def test_failed_prints_f(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _progress_cb _progress_cb(self._case("failed")) assert capsys.readouterr().err == "F" def test_error_prints_e(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _progress_cb _progress_cb(self._case("error")) assert capsys.readouterr().err == "E" def test_skipped_prints_s(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _progress_cb _progress_cb(self._case("skipped")) assert capsys.readouterr().err == "s" def test_unknown_outcome_prints_q(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _progress_cb _progress_cb(self._case("weird")) assert capsys.readouterr().err == "?" # ────────────────────────────────────────────────────────────────────────────── # Unit — _history_to_json # ────────────────────────────────────────────────────────────────────────────── class TestHistoryToJson: def test_preserves_node_id(self) -> None: from muse.cli.commands.test_cmd import _history_to_json s = _make_history_summary(node_id="tests/test_foo.py::test_x") d = _history_to_json(s) assert d["node_id"] == "tests/test_foo.py::test_x" def test_preserves_counts(self) -> None: from muse.cli.commands.test_cmd import _history_to_json s = _make_history_summary(pass_count=7, fail_count=3, total_runs=10) d = _history_to_json(s) assert d["pass_count"] == 7 assert d["fail_count"] == 3 assert d["total_runs"] == 10 def test_preserves_flaky_flag(self) -> None: from muse.cli.commands.test_cmd import _history_to_json d = _history_to_json(_make_history_summary(flaky=True)) assert d["flaky"] is True def test_preserves_avg_duration_ms(self) -> None: from muse.cli.commands.test_cmd import _history_to_json d = _history_to_json(_make_history_summary(avg_duration_ms=99.9)) assert abs(d["avg_duration_ms"] - 99.9) < 0.001 def test_result_is_json_serialisable(self) -> None: from muse.cli.commands.test_cmd import _history_to_json d = _history_to_json(_make_history_summary()) json.dumps(d) # must not raise # ────────────────────────────────────────────────────────────────────────────── # Unit — _gate_to_json # ────────────────────────────────────────────────────────────────────────────── class TestGateToJson: def test_preserves_name(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json d = _gate_to_json(_make_gate(name="mygate")) assert d["name"] == "mygate" def test_preserves_exit_code(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json d = _gate_to_json(_make_gate(exit_code=1)) assert d["exit_code"] == 1 def test_preserves_passed(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json d = _gate_to_json(_make_gate(passed=False)) assert d["passed"] is False def test_warning_included_when_present(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json gate = _make_gate() gate["warning"] = "watch out" d = _gate_to_json(gate) assert d["warning"] == "watch out" def test_warning_absent_when_not_set(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json d = _gate_to_json(_make_gate()) assert "warning" not in d def test_result_is_json_serialisable(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json json.dumps(_gate_to_json(_make_gate())) # ────────────────────────────────────────────────────────────────────────────── # Unit — _ci_to_json # ────────────────────────────────────────────────────────────────────────────── class TestCiToJson: def test_preserves_passed(self) -> None: from muse.cli.commands.test_cmd import _ci_to_json d = _ci_to_json(_make_ci_result(passed=False)) assert d["passed"] is False def test_gates_list_length(self) -> None: from muse.cli.commands.test_cmd import _ci_to_json ci = _make_ci_result(gates=[_make_gate(), _make_gate(name="test")]) d = _ci_to_json(ci) assert len(d["gates"]) == 2 def test_result_is_json_serialisable(self) -> None: from muse.cli.commands.test_cmd import _ci_to_json json.dumps(_ci_to_json(_make_ci_result())) # ────────────────────────────────────────────────────────────────────────────── # Unit — _print_history # ────────────────────────────────────────────────────────────────────────────── class TestPrintHistory: def test_empty_history_prints_no_history(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_history _print_history({}, flaky_only=False) assert "No test history" in capsys.readouterr().out def test_empty_flaky_prints_no_flaky(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_history _print_history({}, flaky_only=True) assert "No flaky" in capsys.readouterr().out def test_non_empty_shows_node_id(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_history s = _make_history_summary(node_id="tests/test_x.py::test_y") _print_history({"tests/test_x.py::test_y": s}, flaky_only=False) assert "test_y" in capsys.readouterr().out def test_flaky_only_filters_non_flaky(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_history non_flaky = _make_history_summary(node_id="t::a", flaky=False) flaky = _make_history_summary(node_id="t::b", flaky=True) _print_history({"t::a": non_flaky, "t::b": flaky}, flaky_only=True) out = capsys.readouterr().out assert "t::b" in out assert "t::a" not in out # ────────────────────────────────────────────────────────────────────────────── # Unit — _print_pre_run # ────────────────────────────────────────────────────────────────────────────── class TestPrintPreRun: def test_with_selection_shows_changed_count(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_pre_run sel = _make_selection(changed_addresses=["a.py::f", "b.py::g"]) _print_pre_run(sel, targets=["tests/t.py::test_1", "tests/t.py::test_2"]) assert "Changed symbols: 2" in capsys.readouterr().out def test_without_selection_with_targets(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_pre_run _print_pre_run(None, targets=["tests/t.py::test_1"]) assert "1 specified" in capsys.readouterr().out def test_without_selection_without_targets(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_pre_run _print_pre_run(None, targets=[]) assert "full test suite" in capsys.readouterr().out def test_uncovered_symbols_shown(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_pre_run sel = _make_selection(uncovered_addresses=["a.py::fn"]) _print_pre_run(sel, targets=[]) assert "no covering test" in capsys.readouterr().out or "uncovered" in capsys.readouterr().out.lower() or "⚠️" in capsys.readouterr().out def test_fallback_note_shown(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_pre_run sel = _make_selection(fallback_used=True) _print_pre_run(sel, targets=[]) assert "heuristic" in capsys.readouterr().out.lower() or "fallback" in capsys.readouterr().out.lower() or "File-name" in capsys.readouterr().out # ────────────────────────────────────────────────────────────────────────────── # Unit — _print_dry_run # ────────────────────────────────────────────────────────────────────────────── class TestPrintDryRun: def test_human_with_targets_shows_would_run(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_dry_run _print_dry_run(None, targets=["tests/t.py::test_x"], json_out=False) assert "Would run" in capsys.readouterr().out def test_human_no_targets_shows_full_discovery(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_dry_run _print_dry_run(None, targets=[], json_out=False) assert "full discovery" in capsys.readouterr().out def test_json_mode_emits_mode_dry_run(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_dry_run _print_dry_run(None, targets=[], json_out=True) d = json.loads(capsys.readouterr().out) assert d["mode"] == "dry-run" def test_json_mode_with_selection(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_dry_run sel = _make_selection(changed_addresses=["a.py::f"]) _print_dry_run(sel, targets=["tests/t.py::test_x"], json_out=True) d = json.loads(capsys.readouterr().out) assert "selection" in d assert d["selection"]["targets"] == ["tests/t.py::test_x"] # ────────────────────────────────────────────────────────────────────────────── # Unit — _print_summary # ────────────────────────────────────────────────────────────────────────────── class TestPrintSummary: def test_passed_shows_checkmark(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_summary result = _make_run_result(exit_code=0, passed=5, failed=0) _print_summary(result, None) assert "✅" in capsys.readouterr().out def test_failed_shows_x(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_summary result = _make_run_result(exit_code=1, passed=2, failed=1) _print_summary(result, None) assert "❌" in capsys.readouterr().out def test_timed_out_shows_warning(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_summary result = _make_run_result(exit_code=1, timed_out=True) _print_summary(result, None) assert "timeout" in capsys.readouterr().out.lower() or "terminated" in capsys.readouterr().out.lower() def test_uncovered_addresses_shown(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_summary sel = _make_selection(uncovered_addresses=["a.py::fn"]) result = _make_run_result() _print_summary(result, sel) out = capsys.readouterr().out assert "a.py::fn" in out or "Coverage gap" in out or "changed symbol" in out # ────────────────────────────────────────────────────────────────────────────── # Integration — alias, docstrings, envelope # ────────────────────────────────────────────────────────────────────────────── class TestAliasRegistration: def test_j_alias_registered(self) -> None: from muse.cli.commands.test_cmd import register import argparse p = argparse.ArgumentParser() sub = p.add_subparsers() register(sub) ns = p.parse_args(["test", "-j"]) assert ns.json_out is True def test_json_long_form_works(self) -> None: from muse.cli.commands.test_cmd import register import argparse p = argparse.ArgumentParser() sub = p.add_subparsers() register(sub) ns = p.parse_args(["test", "--json"]) assert ns.json_out is True class TestDocstrings: def test_register_mentions_json_alias(self) -> None: from muse.cli.commands.test_cmd import register doc = register.__doc__ or "" assert "--json" in doc or "-j" in doc def test_run_mentions_schema_version(self) -> None: from muse.cli.commands.test_cmd import run assert "json" in (run.__doc__ or "").lower() or "exit_code" in (run.__doc__ or "") def test_run_mentions_exit_code(self) -> None: from muse.cli.commands.test_cmd import run assert "exit_code" in (run.__doc__ or "") def test_run_mentions_duration_ms(self) -> None: from muse.cli.commands.test_cmd import run assert "duration_ms" in (run.__doc__ or "") # ────────────────────────────────────────────────────────────────────────────── # End-to-end # ────────────────────────────────────────────────────────────────────────────── class TestEndToEnd: def test_history_exits_zero_empty(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--history"]) assert r.exit_code == 0 assert "No test history" in r.output def test_flaky_exits_zero_empty(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--flaky"]) assert r.exit_code == 0 assert "No flaky" in r.output def test_history_json_emits_mode_history(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--history", "--json"]) assert r.exit_code == 0 d = json.loads(r.output) assert d["mode"] == "history" def test_history_json_has_schema_version(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--history", "--json"]) assert r.exit_code == 0 assert "schema" in json.loads(r.output) def test_history_json_has_history_list(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--history", "--json"]) assert r.exit_code == 0 d = json.loads(r.output) assert isinstance(d["history"], list) def test_dry_run_exits_zero(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--dry-run", "--all"]) assert r.exit_code == 0 def test_dry_run_shows_would_run(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--dry-run", "--all"]) assert r.exit_code == 0 assert "Would run" in r.output or "dry" in r.output.lower() or "full discovery" in r.output def test_dry_run_json_emits_mode(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--dry-run", "--all", "--json"]) assert r.exit_code == 0 d = json.loads(r.output) assert d["mode"] == "dry-run" def test_dry_run_json_has_schema_version(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--dry-run", "--all", "--json"]) assert r.exit_code == 0 assert "schema" in json.loads(r.output) def test_j_alias_dry_run(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--dry-run", "--all", "-j"]) assert r.exit_code == 0 d = json.loads(r.output) assert d["mode"] == "dry-run" def test_flaky_json_has_schema_version(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--flaky", "--json"]) assert r.exit_code == 0 assert "schema" in json.loads(r.output) def test_no_changes_detected_json(self, test_repo: pathlib.Path) -> None: """Clean working tree with --json emits 'no changes detected' message.""" r = _invoke(test_repo, ["code", "test", "--json"]) assert r.exit_code == 0 d = json.loads(r.output) # Either no-changes or actually ran tests — both are valid assert "mode" in d or "message" in d # ────────────────────────────────────────────────────────────────────────────── # Stress # ────────────────────────────────────────────────────────────────────────────── class TestStress: def test_1000_history_to_json(self) -> None: from muse.cli.commands.test_cmd import _history_to_json s = _make_history_summary() for _ in range(1_000): d = _history_to_json(s) assert d["node_id"] == s["node_id"] def test_500_gate_to_json(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json g = _make_gate() for _ in range(500): d = _gate_to_json(g) assert d["name"] == g["name"] def test_print_history_200_entries(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _print_history summaries = { f"t::test_{i}": _make_history_summary(node_id=f"t::test_{i}") for i in range(200) } _print_history(summaries, flaky_only=False) out = capsys.readouterr().out assert "test_0" in out def test_concurrent_history_to_json(self) -> None: from muse.cli.commands.test_cmd import _history_to_json s = _make_history_summary() results: list[str] = [] lock = threading.Lock() def _run() -> None: d = _history_to_json(s) with lock: results.append(d["node_id"]) threads = [threading.Thread(target=_run) for _ in range(50)] for t in threads: t.start() for t in threads: t.join() assert len(results) == 50 assert all(r == s["node_id"] for r in results) # ────────────────────────────────────────────────────────────────────────────── # Data integrity # ────────────────────────────────────────────────────────────────────────────── class TestDataIntegrity: def test_schema_version_is_string(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--history", "--json"]) assert r.exit_code == 0 d = json.loads(r.output) assert isinstance(d.get("schema"), int) def test_schema_version_nonempty(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--history", "--json"]) assert r.exit_code == 0 assert json.loads(r.output).get("schema", 0) > 0 def test_mode_field_present_in_all_json_modes(self, test_repo: pathlib.Path) -> None: for extra in [["--history"], ["--flaky"], ["--dry-run", "--all"]]: r = _invoke(test_repo, ["code", "test", *extra, "--json"]) assert r.exit_code == 0, f"failed for {extra}: {r.output}" d = json.loads(r.output) assert "mode" in d, f"missing mode for {extra}" def test_history_to_json_all_fields(self) -> None: from muse.cli.commands.test_cmd import _history_to_json d = _history_to_json(_make_history_summary()) for field in ("node_id", "total_runs", "pass_count", "fail_count", "skip_count", "flaky", "avg_duration_ms", "last_outcome", "last_run_timestamp", "fail_streak"): assert field in d, f"missing: {field}" def test_gate_to_json_all_required_fields(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json d = _gate_to_json(_make_gate()) for field in ("name", "command", "exit_code", "duration_ms", "required", "passed", "timed_out", "stdout", "stderr"): assert field in d, f"missing: {field}" def test_ci_to_json_preserves_timestamp(self) -> None: from muse.cli.commands.test_cmd import _ci_to_json ts = "2026-04-19T10:00:00+00:00" d = _ci_to_json(_make_ci_result(timestamp=ts)) assert d["timestamp"] == ts def test_dry_run_json_serialisable(self, test_repo: pathlib.Path) -> None: r = _invoke(test_repo, ["code", "test", "--dry-run", "--all", "--json"]) assert r.exit_code == 0 json.loads(r.output) # must not raise # ────────────────────────────────────────────────────────────────────────────── # Security # ────────────────────────────────────────────────────────────────────────────── class TestSecurity: def test_hostile_node_id_survives_json(self) -> None: from muse.cli.commands.test_cmd import _history_to_json malicious = '"; DROP TABLE history; --' d = _history_to_json(_make_history_summary(node_id=malicious)) assert json.loads(json.dumps(d))["node_id"] == malicious def test_ansi_in_gate_stdout_survives_json(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json malicious_stdout = "\x1b[31merror\x1b[0m" d = _gate_to_json(_make_gate(stdout=malicious_stdout)) assert json.loads(json.dumps(d))["stdout"] == malicious_stdout def test_very_long_gate_name_does_not_crash(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json d = _gate_to_json(_make_gate(name="x" * 10_000)) assert len(d["name"]) == 10_000 def test_sql_injection_in_fatal_msg_does_not_crash(self, capsys: pytest.CaptureFixture[str]) -> None: from muse.cli.commands.test_cmd import _fatal malicious = "'; DROP TABLE commits; --" with pytest.raises(SystemExit): _fatal(malicious, json_out=True) d = json.loads(capsys.readouterr().out) assert d["error"] == malicious def test_unicode_in_history_node_id(self) -> None: from muse.cli.commands.test_cmd import _history_to_json d = _history_to_json(_make_history_summary(node_id="tests/音符.py::test_関数")) assert json.loads(json.dumps(d))["node_id"] == "tests/音符.py::test_関数" def test_null_byte_in_gate_stderr_does_not_crash(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json d = _gate_to_json(_make_gate(stderr="err\x00byte")) assert "err" in json.dumps(d) # ────────────────────────────────────────────────────────────────────────────── # Performance # ────────────────────────────────────────────────────────────────────────────── class TestPerformance: def test_1000_gate_to_json_under_500ms(self) -> None: from muse.cli.commands.test_cmd import _gate_to_json g = _make_gate() start = time.perf_counter() for _ in range(1_000): _gate_to_json(g) elapsed = time.perf_counter() - start assert elapsed < 0.5, f"1 000 _gate_to_json took {elapsed:.2f}s" def test_1000_history_to_json_under_500ms(self) -> None: from muse.cli.commands.test_cmd import _history_to_json s = _make_history_summary() start = time.perf_counter() for _ in range(1_000): _history_to_json(s) elapsed = time.perf_counter() - start assert elapsed < 0.5, f"1 000 _history_to_json took {elapsed:.2f}s" def test_dry_run_completes_quickly(self, test_repo: pathlib.Path) -> None: start = time.perf_counter() r = _invoke(test_repo, ["code", "test", "--dry-run", "--all", "--json"]) elapsed = time.perf_counter() - start assert r.exit_code == 0 assert elapsed < 10.0, f"--dry-run took {elapsed:.2f}s" class TestRegisterFlags: def _parse(self, *args: str) -> "argparse.Namespace": import argparse from muse.cli.commands.test_cmd import register p = argparse.ArgumentParser() sub = p.add_subparsers() register(sub) return p.parse_args(["test", *args]) def test_default_json_out_is_false(self) -> None: ns = self._parse() assert ns.json_out is False def test_json_flag_sets_json_out(self) -> None: ns = self._parse("--json") assert ns.json_out is True def test_j_shorthand_sets_json_out(self) -> None: ns = self._parse("-j") assert ns.json_out is True