"""Supercharge tests for ``muse maintenance``. Coverage tiers -------------- - JSON envelope: status, error, exit_code, duration_ms always present on run/status/schedule - Error payload: exactly {status, error, exit_code} — no prose to stdout in --json mode - OID integrity: verify-objects failure list uses sha256:-prefixed IDs - schedule --json: new mode; emits {status, enabled, period_hours, exit_code} - TypedDicts: _MaintenanceRunJson, _MaintenanceStatusJson, _MaintenanceScheduleJson, _MaintenanceErrorJson exist and are annotated - Docstring: covers status, error, exit_code, duration_ms for all subcommands - No-prose pollution: valid JSON on stdout, no emoji in JSON mode """ from __future__ import annotations import datetime import argparse import json import pathlib from typing import get_type_hints from muse.core.object_store import object_path, write_object from muse.core.ids import hash_commit as compute_commit_id, hash_snapshot as compute_snapshot_id from muse.core.store import SnapshotRecord, write_snapshot from muse.core.types import Manifest, blob_id from muse.core.paths import muse_dir from tests.cli_test_helper import CliRunner, InvokeResult runner = CliRunner() _REPO_ID = "maintenance-sg" # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- def _init_repo(path: pathlib.Path) -> pathlib.Path: dot_muse = muse_dir(path) for d in ("commits", "snapshots", "objects", "refs/heads", "code"): (dot_muse / d).mkdir(parents=True, exist_ok=True) (dot_muse / "HEAD").write_text("ref: refs/heads/main", encoding="utf-8") (dot_muse / "repo.json").write_text( json.dumps({"repo_id": _REPO_ID, "domain": "code"}), encoding="utf-8" ) return path def _write_obj(repo: pathlib.Path, content: bytes) -> str: oid = blob_id(content) write_object(repo, oid, content) return oid def _invoke(repo: pathlib.Path, *args: str) -> InvokeResult: from muse.cli.app import main as cli return runner.invoke(cli, list(args), env={"MUSE_REPO_ROOT": str(repo)}) # --------------------------------------------------------------------------- # run --json envelope # --------------------------------------------------------------------------- class TestRunJsonEnvelope: """``maintenance run --json`` envelope has all required fields.""" _REQUIRED = {"status", "error", "tasks_run", "results", "dry_run", "duration_ms", "exit_code"} def test_all_required_keys_present(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") assert r.exit_code == 0 d = json.loads(r.output) missing = self._REQUIRED - d.keys() assert not missing, f"Missing keys: {missing}" def test_status_ok_on_success(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") assert json.loads(r.output)["status"] == "ok" def test_error_empty_on_success(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") assert json.loads(r.output)["error"] == "" def test_exit_code_zero_on_success(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") assert json.loads(r.output)["exit_code"] == 0 def test_duration_ms_is_nonneg_float(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") d = json.loads(r.output) assert isinstance(d["duration_ms"], float) assert d["duration_ms"] >= 0.0 def test_no_elapsed_ms_key(self, tmp_path: pathlib.Path) -> None: """Deprecated elapsed_ms replaced by duration_ms for consistency.""" repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") d = json.loads(r.output) assert "elapsed_ms" not in d def test_dry_run_flag_reflected(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--dry-run", "--json") d = json.loads(r.output) assert d["dry_run"] is True def test_tasks_run_is_list(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--task", "gc", "--json") d = json.loads(r.output) assert isinstance(d["tasks_run"], list) assert "gc" in d["tasks_run"] # --------------------------------------------------------------------------- # status --json envelope # --------------------------------------------------------------------------- class TestStatusJsonEnvelope: """``maintenance status --json`` envelope has all required fields.""" _REQUIRED = {"status", "error", "enabled", "period_hours", "tasks", "last_run", "exit_code"} def test_all_required_keys_present(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "status", "--json") assert r.exit_code == 0 d = json.loads(r.output) missing = self._REQUIRED - d.keys() assert not missing, f"Missing keys: {missing}" def test_status_ok_on_success(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "status", "--json") assert json.loads(r.output)["status"] == "ok" def test_error_empty_on_success(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "status", "--json") assert json.loads(r.output)["error"] == "" def test_exit_code_zero_on_success(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "status", "--json") assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # schedule --json # --------------------------------------------------------------------------- class TestScheduleJson: """``maintenance schedule --json`` emits a structured result.""" _REQUIRED = {"status", "error", "enabled", "period_hours", "exit_code"} def test_schedule_json_flag_accepted(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--period-hours", "48", "--json") assert r.exit_code == 0 def test_schedule_json_all_required_keys(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--json") assert r.exit_code == 0 d = json.loads(r.output) missing = self._REQUIRED - d.keys() assert not missing, f"Missing keys: {missing}" def test_schedule_json_status_ok(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--json") assert json.loads(r.output)["status"] == "ok" def test_schedule_json_reflects_period_hours(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--period-hours", "72", "--json") d = json.loads(r.output) assert d["period_hours"] == 72 def test_schedule_json_reflects_enabled_true(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--enable", "--json") d = json.loads(r.output) assert d["enabled"] is True def test_schedule_json_reflects_enabled_false(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--disable", "--json") d = json.loads(r.output) assert d["enabled"] is False def test_schedule_json_exit_code_zero(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--json") assert json.loads(r.output)["exit_code"] == 0 # --------------------------------------------------------------------------- # OID integrity — verify-objects failures list # --------------------------------------------------------------------------- class TestVerifyObjectsOidIntegrity: """Failure OIDs in verify-objects results carry the sha256: prefix.""" def test_failures_list_uses_sha256_prefix(self, tmp_path: pathlib.Path) -> None: """When an object is corrupt, its ID in the failures list is sha256:-prefixed.""" repo = _init_repo(tmp_path) oid = _write_obj(repo, b"original content") obj_path = object_path(repo, oid) obj_path.chmod(0o644) obj_path.write_bytes(b"corrupted data") r = _invoke(repo, "maintenance", "run", "--task", "verify-objects", "--json") d = json.loads(r.output) failures = d["results"]["verify-objects"]["failures"] assert failures, "Expected at least one failure entry" for fid in failures: assert fid.startswith("sha256:"), f"Failure OID not prefixed: {fid!r}" def test_clean_store_failures_list_empty(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) for i in range(3): _write_obj(repo, f"clean-{i}".encode()) r = _invoke(repo, "maintenance", "run", "--task", "verify-objects", "--json") d = json.loads(r.output) assert d["results"]["verify-objects"]["failures"] == [] # --------------------------------------------------------------------------- # No-prose pollution # --------------------------------------------------------------------------- class TestNoProsePollution: def test_run_json_stdout_is_valid_json(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") json.loads(r.output) # must not raise def test_status_json_stdout_is_valid_json(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "status", "--json") json.loads(r.output) # must not raise def test_schedule_json_stdout_is_valid_json(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "schedule", "--json") json.loads(r.output) # must not raise def test_no_emoji_in_run_json_stdout(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") assert "❌" not in r.output assert "✅" not in r.output def test_no_traceback_in_run_json(self, tmp_path: pathlib.Path) -> None: repo = _init_repo(tmp_path) r = _invoke(repo, "maintenance", "run", "--json") assert "Traceback" not in r.output # --------------------------------------------------------------------------- # TypedDicts # --------------------------------------------------------------------------- class TestTypedDicts: def test_maintenance_run_json_exists(self) -> None: from muse.cli.commands.maintenance import _MaintenanceRunJson assert _MaintenanceRunJson is not None def test_maintenance_status_json_exists(self) -> None: from muse.cli.commands.maintenance import _MaintenanceStatusJson assert _MaintenanceStatusJson is not None def test_maintenance_schedule_json_exists(self) -> None: from muse.cli.commands.maintenance import _MaintenanceScheduleJson assert _MaintenanceScheduleJson is not None def test_maintenance_error_json_exists(self) -> None: from muse.cli.commands.maintenance import _MaintenanceErrorJson assert _MaintenanceErrorJson is not None def test_run_json_has_required_annotations(self) -> None: from muse.cli.commands.maintenance import _MaintenanceRunJson hints = get_type_hints(_MaintenanceRunJson) for field in ("status", "error", "duration_ms", "exit_code"): assert field in hints, f"Missing annotation: {field!r}" def test_status_json_has_required_annotations(self) -> None: from muse.cli.commands.maintenance import _MaintenanceStatusJson hints = get_type_hints(_MaintenanceStatusJson) for field in ("status", "error", "exit_code"): assert field in hints, f"Missing annotation: {field!r}" def test_schedule_json_has_required_annotations(self) -> None: from muse.cli.commands.maintenance import _MaintenanceScheduleJson hints = get_type_hints(_MaintenanceScheduleJson) for field in ("status", "error", "enabled", "period_hours", "exit_code"): assert field in hints, f"Missing annotation: {field!r}" # --------------------------------------------------------------------------- # Docstring coverage # --------------------------------------------------------------------------- class TestDocstring: def _doc(self) -> str: import muse.cli.commands.maintenance as mod return mod.__doc__ or "" def test_docstring_documents_status(self) -> None: assert "status" in self._doc() def test_docstring_documents_error(self) -> None: assert "error" in self._doc() def test_docstring_documents_exit_code(self) -> None: assert "exit_code" in self._doc() def test_docstring_documents_duration_ms(self) -> None: assert "duration_ms" in self._doc() def test_docstring_documents_error_schema(self) -> None: doc = self._doc() assert "error" in doc and "exit_code" in doc # --------------------------------------------------------------------------- # TestRegisterFlags — argparse-level verification # --------------------------------------------------------------------------- class TestRegisterFlags: """Verify that register() wires --json / -j correctly.""" def _make_parser(self) -> "argparse.ArgumentParser": import argparse from muse.cli.commands.maintenance import register ap = argparse.ArgumentParser() subs = ap.add_subparsers() register(subs) return ap def test_json_flag_long(self) -> None: ns = self._make_parser().parse_args(["maintenance", "run", "--json"]) assert ns.json_out is True def test_j_alias(self) -> None: ns = self._make_parser().parse_args(["maintenance", "run", "-j"]) assert ns.json_out is True def test_default_is_text(self) -> None: ns = self._make_parser().parse_args(["maintenance", "run"]) assert ns.json_out is False def test_dest_is_json_out(self) -> None: ns = self._make_parser().parse_args(["maintenance", "run", "-j"]) assert hasattr(ns, "json_out") assert not hasattr(ns, "fmt")