Files
OBLITERATUS/tests/test_cli.py
T
Joseph Magly 2a3e545283 fix(cli): decide the distributed preflight guard by argparse dispatch; convert all manifest parse errors
Muse BT6 audit of ab3be34 for #662: the guard runs a dry parse_known_args on a
copy of argv and refuses when the parse lands on distributed without the
literal "distributed preflight" shape, or when both words are left unparsed,
so a leading "--" can no longer bypass it while positional values of other
commands are accepted. RunArchive._load converts any ValueError from reading
or parsing a manifest (including the integer digit limit) into
InvalidArchiveRequest.
2026-11-25 03:21:50 -05:00

769 lines
28 KiB
Python

"""CLI dispatch tests for obliteratus.cli.main().
These tests verify argument parsing and subcommand routing without
downloading real models or running any pipeline. They use
``unittest.mock.patch`` to capture stdout/stderr and
``pytest.raises(SystemExit)`` for argparse exits.
"""
from __future__ import annotations
import json
from io import StringIO
from types import SimpleNamespace
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from obliteratus.cli import main
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _capture_exit(argv: list[str] | None, *, expect_code: int | None = None):
"""Call main(argv), expecting SystemExit; return captured stderr text."""
buf = StringIO()
with pytest.raises(SystemExit) as exc_info, patch("sys.stderr", buf):
main(argv)
if expect_code is not None:
assert exc_info.value.code == expect_code
return buf.getvalue()
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestCLIDispatch:
"""Test suite for CLI argument parsing and subcommand dispatch."""
def test_verification_help_explains_invalid_denominator(self, capsys):
with pytest.raises(SystemExit) as exc_info:
main(["obliterate", "--help"])
assert exc_info.value.code == 0
help_text = " ".join(capsys.readouterr().out.split())
assert "Invalid completions are excluded from the rate and reported separately." in help_text
# 1. No args -> prints help / exits with error
def test_main_no_args_prints_help(self):
"""Calling main() with no args should exit (subcommand is required)."""
stderr_text = _capture_exit([], expect_code=2)
# argparse prints usage info to stderr on error
assert "usage" in stderr_text.lower() or "required" in stderr_text.lower()
# 2. models command lists models without error
def test_models_command(self):
"""Calling main(['models']) should list models without raising."""
with patch("obliteratus.cli.console") as mock_console:
main(["models"])
# console.print is called at least once to render the table
assert mock_console.print.call_count >= 1
# 3. obliterate without model arg -> error
def test_obliterate_requires_model(self):
"""Calling main(['obliterate']) without a model arg should error."""
stderr_text = _capture_exit(["obliterate"], expect_code=2)
assert "model" in stderr_text.lower() or "required" in stderr_text.lower()
# 4. obliterate --method accepts valid methods
def test_obliterate_valid_methods(self):
"""Test that --method accepts all 9 pipeline methods."""
valid_methods = [
"basic", "advanced", "aggressive", "spectral_cascade",
"informed", "surgical", "optimized", "inverted", "nuclear",
]
for method in valid_methods:
# Patch the actual pipeline execution so nothing runs
with patch("obliteratus.cli._cmd_abliterate") as mock_cmd:
main(["obliterate", "fake/model", "--method", method])
mock_cmd.assert_called_once()
args_passed = mock_cmd.call_args[0][0]
assert args_passed.method == method
# 4b. invalid methods are rejected
def test_obliterate_rejects_invalid_method(self):
"""The CLI --method flag rejects unknown method names."""
stderr_text = _capture_exit(
["obliterate", "fake/model", "--method", "nonexistent"],
expect_code=2,
)
assert "invalid choice" in stderr_text.lower()
# 5. run requires config path
def test_run_requires_config(self):
"""Calling main(['run']) without a config path should error."""
stderr_text = _capture_exit(["run"], expect_code=2)
assert "config" in stderr_text.lower() or "required" in stderr_text.lower()
# 6. aggregate with nonexistent dir handles gracefully
def test_aggregate_command_missing_dir(self):
"""Calling main(['aggregate']) with nonexistent dir should handle gracefully."""
with patch("obliteratus.cli.console") as mock_console:
main(["aggregate", "--dir", "/nonexistent/path/to/nowhere"])
# The command prints a message about no contributions found and returns
printed_text = " ".join(
str(call) for call in mock_console.print.call_args_list
)
assert "no contributions found" in printed_text.lower() or mock_console.print.called
def test_aggregate_accepts_format_metric_min_runs(self):
"""aggregate accepts --format, --metric and --min-runs flags."""
with patch("obliteratus.cli._cmd_aggregate") as mock_cmd:
main([
"aggregate",
"--format", "latex",
"--metric", "refusal_rate",
"--min-runs", "3",
])
mock_cmd.assert_called_once()
args_passed = mock_cmd.call_args[0][0]
assert args_passed.format == "latex"
assert args_passed.metric == "refusal_rate"
assert args_passed.min_runs == 3
def test_aggregate_rejects_invalid_format(self):
"""aggregate rejects unknown --format choices."""
stderr_text = _capture_exit(
["aggregate", "--format", "invalid"],
expect_code=2,
)
assert "invalid choice" in stderr_text.lower()
# 7. --help flag prints help
def test_help_flag(self):
"""Calling main(['--help']) should print help and exit 0."""
buf = StringIO()
with pytest.raises(SystemExit) as exc_info, patch("sys.stdout", buf):
main(["--help"])
assert exc_info.value.code == 0
output = buf.getvalue()
assert "obliteratus" in output.lower() or "usage" in output.lower()
# 8. interactive subcommand is registered
def test_interactive_command_exists(self):
"""Verify 'interactive' subcommand is registered and dispatches."""
with patch("obliteratus.cli._cmd_interactive") as mock_cmd:
main(["interactive"])
mock_cmd.assert_called_once()
def test_distributed_preflight_is_an_explicit_separate_command(self, tmp_path):
profile = tmp_path / "profile.json"
profile.write_text("{}", encoding="utf-8")
with patch("obliteratus.cli._cmd_distributed") as mock_cmd:
main(["distributed", "preflight", str(profile), "--json"])
args_passed = mock_cmd.call_args.args[0]
assert args_passed.command == "distributed"
assert args_passed.distributed_command == "preflight"
assert args_passed.profile == profile
def test_ordinary_command_never_infers_distributed_mode(self, monkeypatch):
monkeypatch.setenv("WORLD_SIZE", "2")
monkeypatch.setenv("RANK", "0")
monkeypatch.setenv("MASTER_ADDR", "10.10.0.10")
with (
patch("obliteratus.cli._cmd_abliterate") as ordinary,
patch("obliteratus.cli._cmd_distributed") as distributed,
):
main(["obliterate", "fake/model"])
ordinary.assert_called_once()
distributed.assert_not_called()
@pytest.mark.parametrize("option", ["--token", "--password", "--api-key", "--remote"])
def test_distributed_preflight_rejects_unknown_options_without_echoing_value(
self, option, capsys
):
secret = "hf_private_value_that_must_not_appear"
with pytest.raises(SystemExit) as error:
main(["distributed", "preflight", "profile.json", option, secret])
assert error.value.code == 2
captured = capsys.readouterr()
assert secret not in captured.out
assert secret not in captured.err
@pytest.mark.parametrize(
"argv",
[
["--token", "{secret}", "distributed", "preflight", "profile.json"],
["distributed", "preflight", "profile.json", "--token={secret}"],
],
)
def test_distributed_preflight_secret_prescan_cannot_be_bypassed(
self, argv, capsys
):
secret = "hf_private_value_that_must_not_appear"
with pytest.raises(SystemExit) as error:
main([item.replace("{secret}", secret) for item in argv])
assert error.value.code == 2
captured = capsys.readouterr()
assert secret not in captured.out
assert secret not in captured.err
# 9. --contribute and --contribute-notes are accepted on obliterate
def test_contribute_flags_on_obliterate(self):
"""Verify --contribute and --contribute-notes are accepted args."""
with patch("obliteratus.cli._cmd_abliterate") as mock_cmd:
main([
"obliterate", "fake/model",
"--contribute",
"--contribute-notes", "Testing contribution system",
])
mock_cmd.assert_called_once()
args_passed = mock_cmd.call_args[0][0]
assert args_passed.contribute is True
assert args_passed.contribute_notes == "Testing contribution system"
@pytest.mark.parametrize("flag", ["--prompt-pairs-file", "--prompt-pair-file"])
@pytest.mark.parametrize("command", ["obliterate", "abliterate"])
def test_prompt_pairs_file_flag_is_available_on_obliterate_and_alias(
self,
command,
flag,
tmp_path,
):
"""Explicit prompt-pair files are parsed for both commands and flag spellings."""
path = tmp_path / "pairs.json"
path.write_text("{}", encoding="utf-8")
with patch("obliteratus.cli._cmd_abliterate") as mock_cmd:
main([command, "fake/model", flag, str(path)])
args_passed = mock_cmd.call_args[0][0]
assert args_passed.prompt_pairs_file == str(path)
@pytest.mark.parametrize("flag", ["--prompt-pairs-file", "--prompt-pair-file"])
@pytest.mark.parametrize("command", ["obliterate", "abliterate"])
def test_prompt_pairs_file_is_mutually_exclusive_with_residue_files(
self,
command,
flag,
tmp_path,
):
"""Explicit prompt-pair files and mined residue construction cannot be mixed."""
path = tmp_path / "pairs.json"
path.write_text("{}", encoding="utf-8")
stderr_text = _capture_exit(
[
command,
"fake/model",
flag,
str(path),
"--residue-file",
"audit.json",
],
expect_code=2,
)
assert "not allowed with argument" in stderr_text.lower()
@pytest.mark.parametrize(
("option", "value"),
[
("--dataset", "custom"),
("--residue-weight", "7"),
("--residue-max", "3"),
],
)
@pytest.mark.parametrize("flag", ["--prompt-pairs-file", "--prompt-pair-file"])
@pytest.mark.parametrize("command", ["obliterate", "abliterate"])
def test_prompt_pairs_file_rejects_residue_only_options(
self,
command,
flag,
option,
value,
tmp_path,
):
"""Explicit prompt-pair files cannot be mixed with residue-only options."""
path = tmp_path / "pairs.json"
path.write_text("{}", encoding="utf-8")
stderr_text = _capture_exit(
[command, "fake/model", flag, str(path), option, value],
expect_code=2,
)
assert option in stderr_text
assert "can only be used with --residue-file" in stderr_text
def test_cmd_abliterate_wires_prompt_pairs_file_into_pipeline(tmp_path):
"""Loaded prompt-pair files are passed directly to AbliterationPipeline."""
path = tmp_path / "pairs.json"
path.write_text(
json.dumps(
{
"harmful": [f"harm {index}" for index in range(5)],
"harmless": [f"safe {index}" for index in range(5)],
}
),
encoding="utf-8",
)
result_path = tmp_path / "result"
result_path.mkdir()
pipeline = MagicMock()
pipeline.run.return_value = str(result_path)
class FakeLive:
def __init__(self, *_args, **_kwargs):
self.update = MagicMock()
def __enter__(self):
return self
def __exit__(self, *_args):
return False
args = SimpleNamespace(
model="org/model",
output_dir=str(tmp_path / "out"),
device="cpu",
dtype="float32",
method="basic",
n_directions=1,
direction_method=None,
regularization=None,
refinement_passes=1,
min_layer_fraction=None,
max_layer_fraction=None,
harmless_pc_count=None,
shield_concept_count=None,
shield_ridge=None,
shield_residualize=None,
shield_layer_penalty=None,
projection_target=None,
projection_row_fraction=None,
quantization=None,
gpu_memory_utilization=None,
large_model=False,
verify_sample_size=1,
refusal_max_tokens=1,
residue_file=[],
dataset="builtin",
residue_weight=5,
residue_max=None,
prompt_pairs_file=str(path),
contribute=False,
contribute_notes="",
)
with (
patch("rich.live.Live", FakeLive),
patch("obliteratus.abliterate.AbliterationPipeline", return_value=pipeline) as factory,
patch("obliteratus.telemetry.maybe_send_pipeline_report"),
):
from obliteratus import cli
cli._cmd_abliterate(args)
assert factory.call_args.kwargs["harmful_prompts"] == [f"harm {index}" for index in range(5)]
assert factory.call_args.kwargs["harmless_prompts"] == [f"safe {index}" for index in range(5)]
args.prompt_pairs_file = None
pipeline.reset_mock()
pipeline.run.return_value = str(result_path)
with (
patch("rich.live.Live", FakeLive),
patch("obliteratus.abliterate.AbliterationPipeline", return_value=pipeline) as factory,
patch("obliteratus.telemetry.maybe_send_pipeline_report"),
):
from obliteratus import cli
cli._cmd_abliterate(args)
assert "harmful_prompts" not in factory.call_args.kwargs
assert "harmless_prompts" not in factory.call_args.kwargs
def test_cmd_abliterate_reports_invalid_prompt_pairs_file(tmp_path):
from obliteratus import cli
args = SimpleNamespace(
model="org/model",
output_dir=str(tmp_path / "out"),
device="cpu",
dtype="float32",
method="basic",
n_directions=1,
direction_method=None,
regularization=None,
refinement_passes=1,
min_layer_fraction=None,
max_layer_fraction=None,
harmless_pc_count=None,
shield_concept_count=None,
shield_ridge=None,
shield_residualize=None,
shield_layer_penalty=None,
projection_target=None,
projection_row_fraction=None,
quantization=None,
gpu_memory_utilization=None,
large_model=False,
verify_sample_size=1,
refusal_max_tokens=1,
residue_file=[],
dataset="builtin",
residue_weight=5,
residue_max=None,
prompt_pairs_file=str(tmp_path / "missing.json"),
contribute=False,
contribute_notes="",
)
with pytest.raises(SystemExit) as exc:
cli._cmd_abliterate(args)
assert exc.value.code == 2
class _EncodingOnlyStdout:
"""Minimal stream stand-in for encoding-selection tests."""
def __init__(self, encoding: str | None) -> None:
self.encoding = encoding
class TestConsoleEncoding:
"""The CLI must remain renderable on legacy Windows code pages."""
@pytest.mark.parametrize("encoding", ["cp1252", "ascii", "not-a-codec"])
def test_console_text_falls_back_when_text_is_not_encodable(self, encoding):
from obliteratus.cli import _console_text
with patch("sys.stdout", _EncodingOnlyStdout(encoding)):
assert _console_text("█→", "FALLBACK") == "FALLBACK"
@pytest.mark.parametrize("encoding", ["utf-8", None])
def test_console_text_keeps_unicode_on_utf8_compatible_streams(self, encoding):
from obliteratus.cli import _console_text
with patch("sys.stdout", _EncodingOnlyStdout(encoding)):
assert _console_text("█→", "FALLBACK") == "█→"
def test_banner_degrades_to_ascii_on_cp1252(self):
from obliteratus.cli import _banner_for_console
with patch("sys.stdout", _EncodingOnlyStdout("cp1252")):
banner = _banner_for_console()
assert "OBLITERATUS" in banner
assert banner.isascii()
def test_main_renders_selected_banner(self):
with (
patch("sys.stdout", _EncodingOnlyStdout("cp1252")),
patch("obliteratus.cli.console") as mock_console,
):
main(["models"])
assert mock_console.print.call_args_list[0].args[0].isascii()
# ---------------------------------------------------------------------------
# report replay (#604, #606, #607)
# ---------------------------------------------------------------------------
def _replay(results_path, output_dir, monkeypatch):
from obliteratus import cli
from obliteratus.reporting.report import AblationReport
plotted = []
original = AblationReport.plot_impact
def spy(self, metric=None, output_path=None, **kwargs):
plotted.append(metric)
return original(self, metric=metric, output_path=output_path, **kwargs)
monkeypatch.setattr(AblationReport, "plot_impact", spy)
buf = StringIO()
monkeypatch.setattr(cli, "console", cli.Console(file=buf, width=400))
cli._cmd_report(SimpleNamespace(results_json=str(results_path), output_dir=str(output_dir)))
return plotted, buf.getvalue()
def _saved_report(tmp_path, baseline, measured, primary_metric=None):
from obliteratus.reporting.report import AblationReport, AblationResult
kwargs = {} if primary_metric is None else {"primary_metric": primary_metric}
report = AblationReport("classifier", **kwargs)
report.add_baseline(baseline)
report.add_result(AblationResult("layer_removal", "layer_0", "d", measured))
path = tmp_path / "results.json"
report.save_json(path)
return path
def test_report_replay_preserves_study_impact_metric(tmp_path, monkeypatch):
path = _saved_report(
tmp_path, {"f1": 1.0, "accuracy": 1.0}, {"f1": 0.73, "accuracy": 0.75}, primary_metric="f1",
)
plotted, _ = _replay(path, tmp_path / "replay", monkeypatch)
assert plotted == ["f1"]
def test_report_replay_of_file_without_primary_metric_uses_first_metric(tmp_path, monkeypatch):
path = _saved_report(tmp_path, {"f1": 1.0, "accuracy": 1.0}, {"f1": 0.73, "accuracy": 0.75})
data = json.loads(path.read_text())
assert "primary_metric" not in data
plotted, output = _replay(path, tmp_path / "replay", monkeypatch)
assert plotted == ["accuracy"]
assert (tmp_path / "replay" / "heatmap.png").is_file()
assert "impact.png" in output and "heatmap.png" in output
def test_report_replay_writes_heatmap_when_first_metric_unavailable(tmp_path, monkeypatch):
path = _saved_report(tmp_path, {"accuracy": 0.75, "f1": 0.8}, {"accuracy": None, "f1": 0.6})
plotted, output = _replay(path, tmp_path / "replay", monkeypatch)
assert sorted(p.name for p in (tmp_path / "replay").iterdir()) == ["heatmap.png", "impact.png"]
assert plotted == ["f1"]
assert "Could not generate plots" not in output
def test_report_replay_message_lists_only_written_plots(tmp_path, monkeypatch):
out = tmp_path / "replay"
out.mkdir()
(out / "heatmap.png").write_bytes(b"previous run")
path = _saved_report(tmp_path, {"accuracy": 0.0}, {"accuracy": 0.5})
_, output = _replay(path, out, monkeypatch)
assert sorted(p.name for p in out.iterdir()) == ["heatmap.png", "impact.png"]
assert (out / "heatmap.png").read_bytes() == b"previous run"
assert "Plots saved to" not in output
assert "Saved impact.png" in output
assert "percent change is undefined" in output
assert "heatmap.png" in output and "earlier run" in output
# ---------------------------------------------------------------------------
# Durable ``runs`` commands emit machine-readable JSON only (#611)
# ---------------------------------------------------------------------------
class _FakeRunArchive:
"""Stand-in archive returning fixed JSON payloads for every subcommand."""
def __init__(self, root=None):
self.root = root
def launch(self, arguments, *, notes=""):
return "run-" + "a" * 32
def status(self, run_id):
return {"run_id": run_id, "status": "running"}
def cancel(self, run_id):
return {"run_id": run_id, "status": "cancelling"}
def result(self, run_id):
return {"run_id": run_id, "status": "succeeded"}
def prune_checkpoint(self, run_id, *, reason):
return {"run_id": run_id, "status": "succeeded", "pruned": reason}
def list(self):
return [{"run_id": "run-" + "b" * 32, "status": "succeeded"}]
_RUN_ID = "run-" + "c" * 32
@pytest.mark.parametrize(
"subcommand",
[
["launch", "--", "gpt2"],
["status", _RUN_ID],
["cancel", _RUN_ID],
["result", _RUN_ID],
["prune-checkpoint", _RUN_ID, "--reason", "disk"],
["list"],
],
ids=lambda argv: argv[0],
)
def test_runs_subcommands_print_only_json_to_stdout(tmp_path, capsys, subcommand):
with patch("obliteratus.run_archive.RunArchive", _FakeRunArchive):
main(["runs", "--archive-root", str(tmp_path), *subcommand])
stdout = capsys.readouterr().out
assert "OBLITERATUS" not in stdout
payload = json.loads(stdout)
assert payload
def test_runs_list_on_real_empty_archive_is_clean_json(tmp_path, capsys):
main(["runs", "--archive-root", str(tmp_path), "list"])
assert json.loads(capsys.readouterr().out) == []
# ---------------------------------------------------------------------------
# ``runs`` failures keep stdout empty: diagnostic on stderr, nonzero exit
# ---------------------------------------------------------------------------
def test_runs_launch_secret_guard_keeps_stdout_empty(tmp_path, capsys):
with pytest.raises(SystemExit) as exc_info:
main(["runs", "--archive-root", str(tmp_path), "launch", "--", "gpt2", "--token=hunter2"])
captured = capsys.readouterr()
assert exc_info.value.code == 2
assert captured.out == ""
assert "Secret-bearing command-line inputs are forbidden." in captured.err
assert "hunter2" not in captured.err
@pytest.mark.parametrize(
"argv",
[
["runs", "distributed", "preflight"],
["preflight", "distributed", "profile.json"],
["distributed", "--json", "preflight", "profile.json"],
["--", "distributed", "preflight", "profile.json"],
["--", "distributed", "--", "preflight", "profile.json"],
["distributed", "--", "preflight", "profile.json"],
["--", "distributed", "preflight"],
],
ids=[
"runs-position", "swapped", "option-between", "leading-separator",
"double-separator", "inner-separator", "leading-separator-incomplete",
],
)
def test_distributed_preflight_shape_guard_keeps_stdout_empty(capsys, argv):
# The words sit in the command position but not as ``distributed preflight``.
with (
patch("obliteratus.cli._cmd_distributed") as distributed,
patch("obliteratus.cli._cmd_runs") as runs,
pytest.raises(SystemExit) as exc_info,
):
main(argv)
captured = capsys.readouterr()
assert exc_info.value.code == 2
assert captured.out == ""
assert "Distributed preflight command shape is invalid." in captured.err
distributed.assert_not_called()
runs.assert_not_called()
@pytest.mark.parametrize(
"tail",
[
["launch", "--", "distributed", "preflight"],
["launch", "--notes", "distributed", "--", "org/model", "--revision", "preflight"],
["launch", "--", "org/model", "--dataset", "distributed", "--method", "preflight"],
],
ids=["launched-command-line", "option-values", "launched-option-values"],
)
def test_unrelated_argv_with_both_words_is_not_a_distributed_command(tmp_path, capsys, tail):
# Both words appear only as launched arguments or option values (#632).
launched = []
class _RecordingArchive(_FakeRunArchive):
def launch(self, arguments, *, notes=""):
launched.append((list(arguments), notes))
return super().launch(arguments, notes=notes)
with (
patch("obliteratus.run_archive.RunArchive", _RecordingArchive),
patch("obliteratus.cli._cmd_distributed") as distributed,
):
main(["runs", "--archive-root", str(tmp_path), *tail])
captured = capsys.readouterr()
assert "command shape is invalid" not in captured.err
assert json.loads(captured.out)["status"] == "running"
assert len(launched) == 1
distributed.assert_not_called()
@pytest.mark.parametrize(
("argv", "handler"),
[
(["concepts", "compare", "distributed", "preflight"], "obliteratus.concepts.cli.run"),
(["concepts", "pack", "distributed", "preflight"], "obliteratus.concepts.cli.run"),
(["experiments", "compare", "distributed", "preflight"], "obliteratus.experiments.cli.run"),
],
ids=["concepts-compare", "concepts-pack", "experiments-compare"],
)
def test_positional_values_named_distributed_preflight_are_accepted(capsys, argv, handler):
# Directory names that happen to be ``distributed`` and ``preflight`` are
# ordinary positional values of a non-distributed command (#632).
with patch(handler) as dispatch, patch("obliteratus.cli._cmd_distributed") as distributed:
main(argv)
assert "command shape is invalid" not in capsys.readouterr().err
dispatch.assert_called_once()
distributed.assert_not_called()
def test_runs_unexpected_internal_error_is_not_masked(tmp_path, capsys):
# A bug inside the archive layer (not an archive-raised error) must keep
# its type and traceback instead of becoming a one-line message (#638).
class _BrokenArchive(_FakeRunArchive):
def status(self, run_id):
raise ValueError("internal bug: unexpected manifest shape")
with (
patch("obliteratus.run_archive.RunArchive", _BrokenArchive),
pytest.raises(ValueError, match="internal bug") as exc_info,
):
main(["runs", "--archive-root", str(tmp_path), "status", _RUN_ID])
assert exc_info.traceback[-1].name == "status"
assert capsys.readouterr().out == ""
@pytest.mark.parametrize(
"content",
[b"{not json", b"\xff\xfe", b'{"run_id": ' + b"9" * 5000 + b"}"],
ids=["syntax", "encoding", "int-digit-limit"],
)
def test_runs_status_corrupt_manifest_reports_archive_error_on_stderr_only(
tmp_path, capsys, content
):
run_dir = tmp_path / _RUN_ID
run_dir.mkdir()
(run_dir / "manifest.json").write_bytes(content)
with pytest.raises(SystemExit) as exc_info:
main(["runs", "--archive-root", str(tmp_path), "status", _RUN_ID])
captured = capsys.readouterr()
assert exc_info.value.code == 1
assert captured.out == ""
assert captured.err == f"obliteratus runs status: invalid manifest for {_RUN_ID}\n"
def test_runs_status_unknown_run_id_reports_on_stderr_only(tmp_path, capsys):
with pytest.raises(SystemExit) as exc_info:
main(["runs", "--archive-root", str(tmp_path), "status", _RUN_ID])
captured = capsys.readouterr()
assert exc_info.value.code == 1
assert captured.out == ""
assert captured.err == f"obliteratus runs status: unknown run ID: {_RUN_ID}\n"
def test_runs_result_of_unfinished_run_reports_on_stderr_only(tmp_path, capsys):
run_dir = tmp_path / _RUN_ID
run_dir.mkdir()
(run_dir / "manifest.json").write_text(
json.dumps({"run_id": _RUN_ID, "status": "running"}), encoding="utf-8"
)
with pytest.raises(SystemExit) as exc_info:
main(["runs", "--archive-root", str(tmp_path), "result", _RUN_ID])
captured = capsys.readouterr()
assert exc_info.value.code == 1
assert captured.out == ""
assert captured.err == f"obliteratus runs result: run {_RUN_ID} is not complete\n"
def test_runs_status_invalid_run_id_reports_on_stderr_only(tmp_path, capsys):
with pytest.raises(SystemExit) as exc_info:
main(["runs", "--archive-root", str(tmp_path), "status", "not-a-run-id"])
captured = capsys.readouterr()
assert exc_info.value.code == 1
assert captured.out == ""
assert captured.err == "obliteratus runs status: invalid run ID\n"