"""CLI tests for the residual-diff subcommand (#23 follow-on #5).""" from __future__ import annotations import datetime as dt from security_scanner.cli import main from security_scanner.storage.base import RefState NOW = dt.datetime(2026, 6, 16, tzinfo=dt.UTC) class FakeTwoBranchStore: """main @ Smain and feat @ Sfeat with overlapping + distinct findings.""" def list_ref_states(self, repo_id: str) -> list[RefState]: return [ RefState(repo_id=repo_id, repo_url="https://e/r", ref_name="refs/heads/main", last_seen_sha="Smain", updated_at=NOW), RefState(repo_id=repo_id, repo_url="https://e/r", ref_name="refs/heads/feat", last_seen_sha="Sfeat", updated_at=NOW), ] def read_observations_for_repo( self, repo_id: str, *, include_legacy: bool = False ) -> list[dict]: return [ {"branch": "main", "commit": "Smain", "findingId": "f_shared"}, {"branch": "main", "commit": "Smain", "findingId": "f_base_only"}, {"branch": "feat", "commit": "Sfeat", "findingId": "f_shared"}, {"branch": "feat", "commit": "Sfeat", "findingId": "f_added"}, ] def _patch(monkeypatch, store): monkeypatch.setattr( "security_scanner.cli._store.create_finding_store", lambda backend, **kwargs: store, ) def test_residual_diff_reports_added_removed_unchanged(monkeypatch, capsys): _patch(monkeypatch, FakeTwoBranchStore()) exit_code = main([ "residual-diff", "--repo", "repo_x", "--base", "main", "--head", "feat", "--storage-backend", "dynamodb", ]) out = capsys.readouterr().out assert exit_code == 0 assert "repo: repo_x" in out assert "base: main @ Smain" in out assert "head: feat @ Sfeat" in out assert "added (1):" in out and "- f_added" in out assert "removed (1):" in out and "- f_base_only" in out assert "unchanged: 1" in out def test_residual_diff_missing_branch_fails_closed(monkeypatch, capsys): _patch(monkeypatch, FakeTwoBranchStore()) exit_code = main([ "residual-diff", "--repo", "repo_x", "--base", "main", "--head", "nope", "--storage-backend", "dynamodb", ]) err = capsys.readouterr().err assert exit_code == 2 assert "nope" in err and "no residual for branch" in err def test_residual_diff_rejects_jsonl_backend(capsys): exit_code = main([ "residual-diff", "--repo", "repo_x", "--base", "main", "--head", "feat", "--storage-backend", "jsonl", ]) assert exit_code == 2 assert "dynamodb only" in capsys.readouterr().err