Files
skills/tests/fixtures/test_build_review.py
T
kiskaadee 8c5172eeaf feat(code-review): upgrade to GitHub PR reviews with build_review.py
- Add stdlib-only executable skills/code-review/scripts/build_review.py with diff-hunk validation (LEFT/RIGHT), unanchored body fallback, monotonic CR-XX numbering across paginated reviews/comments, cr-review-meta stamping, collapsible RV-* blocks, triage summaries, duplicate (head_sha, verdict) skip (exit 2), and 3-rework-cycle cap (exit 1)
- Add tests/fixtures/test_build_review.py unittest suite covering pagination flattening, diff anchoring, unanchored fallback, monotonic rollover, RV-*/triage rendering, duplicate/rework-cap guards, and invalid input handling
- Update skills/code-review/SKILL.md (78 lines) for GitHub PR publishing via build_review.py + gh api, no-PR local fallback notice, split rework routing to implement/verify, and removal of Accepted Trade-off and delegation skip rules
- Update skills/code-review/references/axes.md with code-hygiene checks (docstrings, stale comments, lint/format, affected local markdown) and GitHub/verify terminology
- Update skills/code-review/references/finding-schema.md with the build_review.py input schema, gh api --paginate --slurp publishing workflow, 3 GitHub-native triage exits, and cr-review-meta contract
2026-11-25 14:59:19 -05:00

388 lines
14 KiB
Python

#!/usr/bin/env python3
"""
Unit tests for skills/code-review/scripts/build_review.py.
Covers:
1. --paginate --slurp JSON flattening ([[...]] and [...]) for --reviews and --comments
2. Unified diff hunk parsing and validation (LEFT deleted, RIGHT added/modified/context)
3. Out-of-hunk, missing-file, and cross-file findings routed to review body
4. Monotonic max_id extraction from cr-review-meta and ### CR-NN headings across reviews/comments
5. Collapsible RV-* block from rv_checks[] and Triage Summary from triage_closures[]
6. Duplicate (head_sha, verdict) exits 2; ready superseding needs_rework on same head_sha exits 0
7. 3-rework-cycle cap exits 1 on 4th needs_rework, allows ready
8. Invalid JSON, invalid verdict, and missing required fields exit 1
"""
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
SCRIPT = REPO_ROOT / "skills" / "code-review" / "scripts" / "build_review.py"
SAMPLE_DIFF = """diff --git a/src/app.py b/src/app.py
index 1111111..2222222 100644
--- a/src/app.py
+++ b/src/app.py
@@ -10,4 +10,5 @@ def process(data):
x = 1
- old_call(data)
+ new_call(data)
+ extra_check(data)
return x
diff --git a/src/removed.py b/src/removed.py
deleted file mode 100644
index 3333333..0000000
--- a/src/removed.py
+++ /dev/null
@@ -1,2 +0,0 @@
-def legacy():
- return 0
"""
class TestBuildReview(unittest.TestCase):
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.tmp = Path(self._tmp.name)
def tearDown(self):
self._tmp.cleanup()
def _write_file(self, name, content):
path = self.tmp / name
if isinstance(content, str):
path.write_text(content, encoding="utf-8")
else:
path.write_text(json.dumps(content), encoding="utf-8")
return path
def _run(self, input_data, diff_text=SAMPLE_DIFF, reviews=None, comments=None,
head_sha="abc1234def5678", verdict="needs_rework"):
input_path = self._write_file("input.json", input_data)
diff_path = self._write_file("pr.diff", diff_text)
reviews_path = self._write_file("reviews.json", [] if reviews is None else reviews)
comments_path = self._write_file("comments.json", [] if comments is None else comments)
return subprocess.run(
[
sys.executable,
str(SCRIPT),
"--input", str(input_path),
"--diff", str(diff_path),
"--reviews", str(reviews_path),
"--comments", str(comments_path),
"--head-sha", head_sha,
"--verdict", verdict,
],
capture_output=True,
text=True,
)
def test_valid_anchored_left_and_right_findings_emit_inline_comments(self):
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "LEFT",
"severity": "High",
"axis": "Defensive Invariants",
"title": "Deleted validation call",
"body": "Removing old_call drops input validation.",
},
{
"path": "src/app.py",
"line": 12,
"side": "RIGHT",
"severity": "Medium",
"title": "Unbounded check",
"body": "extra_check lacks timeout.",
},
{
"path": "src/app.py",
"line": 10,
"side": "RIGHT",
"severity": "Low",
"title": "Context line anchor",
"body": "Context line inside hunk is valid on RIGHT.",
},
{
"path": "src/removed.py",
"line": 1,
"side": "LEFT",
"severity": "Medium",
"title": "Deleted file line anchor",
"body": "Deleted file line 1 is valid on LEFT.",
},
]
}
res = self._run(payload_in, head_sha="deadbeef0011", verdict="needs_rework")
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(out["commit_id"], "deadbeef0011")
self.assertEqual(out["event"], "COMMENT")
self.assertEqual(len(out["comments"]), 4)
self.assertEqual(out["comments"][0]["path"], "src/app.py")
self.assertEqual(out["comments"][0]["line"], 11)
self.assertEqual(out["comments"][0]["side"], "LEFT")
self.assertTrue(out["comments"][0]["body"].startswith("### CR-01:"))
self.assertEqual(out["comments"][1]["side"], "RIGHT")
self.assertTrue(out["comments"][1]["body"].startswith("### CR-02:"))
self.assertTrue(out["comments"][2]["body"].startswith("### CR-03:"))
self.assertEqual(out["comments"][3]["path"], "src/removed.py")
self.assertEqual(out["comments"][3]["side"], "LEFT")
self.assertTrue(out["comments"][3]["body"].startswith("### CR-04:"))
self.assertNotIn("### Findings (Unanchored / Cross-File)", out["body"])
self.assertIn(
"<!-- cr-review-meta: max_id=04 head_sha=deadbeef0011 verdict=needs_rework -->",
out["body"],
)
def test_unanchored_out_of_hunk_missing_file_and_cross_file_move_to_body(self):
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 99,
"side": "RIGHT",
"severity": "Medium",
"title": "Out of hunk line",
"body": "Line 99 is not in diff hunk.",
},
{
"path": "src/app.py",
"line": 10,
"side": "LEFT",
"severity": "Low",
"title": "Context line on LEFT rejected",
"body": "Context line is not a deleted line on LEFT.",
},
{
"path": "src/nonexistent.py",
"line": 5,
"side": "RIGHT",
"severity": "High",
"title": "Missing file",
"body": "File is not in diff.",
},
{
"path": None,
"line": None,
"side": None,
"severity": "High",
"title": "Cross-file architectural drift",
"body": "Multiple modules violate layering.",
},
]
}
res = self._run(payload_in, head_sha="aaaa1111", verdict="needs_rework")
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(out["comments"], [])
self.assertIn("### Findings (Unanchored / Cross-File)", out["body"])
for idx in ("### CR-01:", "### CR-02:", "### CR-03:", "### CR-04:"):
self.assertIn(idx, out["body"])
self.assertIn("<!-- cr-review-meta: max_id=04 head_sha=aaaa1111 verdict=needs_rework -->", out["body"])
def test_slurp_and_flat_pagination_monotonic_max_id_and_three_digit_rollover(self):
# Slurped nested pages for reviews: [[...], [...]]
slurped_reviews = [
[
{
"body": "Prior review\n<!-- cr-review-meta: max_id=05 head_sha=oldsha1 verdict=needs_rework -->"
}
],
[
{
"body": "### Findings (Unanchored / Cross-File)\n### CR-98: Old unanchored\nBody"
}
],
]
# Flat list for comments with CR-99
flat_comments = [
{"body": "### CR-99: Inline finding\nDetails"}
]
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "RIGHT",
"severity": "Medium",
"title": "Hundredth finding",
"body": "Should roll over to CR-100.",
}
]
}
res = self._run(
payload_in,
reviews=slurped_reviews,
comments=flat_comments,
head_sha="newsha99",
verdict="needs_rework",
)
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(len(out["comments"]), 1)
self.assertTrue(out["comments"][0]["body"].startswith("### CR-100:"))
self.assertIn(
"<!-- cr-review-meta: max_id=100 head_sha=newsha99 verdict=needs_rework -->",
out["body"],
)
def test_slurped_comments_also_flattened(self):
slurped_comments = [
[{"body": "### CR-03: First\nDetails"}],
[{"body": "### CR-07: Seventh\nDetails"}],
]
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "RIGHT",
"severity": "Low",
"title": "Next finding",
"body": "Should be CR-08.",
}
]
}
res = self._run(
payload_in,
reviews=[[]],
comments=slurped_comments,
head_sha="sha0008",
verdict="needs_rework",
)
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertTrue(out["comments"][0]["body"].startswith("### CR-08:"))
def test_rv_checks_collapsible_block_and_triage_closures_summary(self):
payload_in = {
"findings": [],
"rv_checks": [
{
"id": "RV-01",
"purpose": "Concurrent submission returns 409",
"scope": "local",
"pass_condition": "HTTP 409 returned",
"fail_signal": "FAIL if HTTP 200 or 500",
"command": "./scripts/check_conflict.sh",
}
],
"triage_closures": [
{"id": "CR-01", "exit": "B", "resolution": "Promoted to #45"},
{"id": "CR-02", "exit": "C", "resolution": "Dismissed: false positive on fixture"},
],
}
prior_reviews = [
{
"body": "Prior\n<!-- cr-review-meta: max_id=02 head_sha=sha_same verdict=needs_rework -->"
}
]
# ready superseding needs_rework on same head_sha must exit 0
res = self._run(
payload_in,
reviews=prior_reviews,
head_sha="sha_same",
verdict="ready",
)
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(out["comments"], [])
self.assertIn("<details>", out["body"])
self.assertIn("RV-01", out["body"])
self.assertIn("./scripts/check_conflict.sh", out["body"])
self.assertIn("FAIL if HTTP 200 or 500", out["body"])
self.assertIn("### Triage Summary", out["body"])
self.assertIn("CR-01", out["body"])
self.assertIn("Promoted to #45", out["body"])
self.assertIn("Dismissed: false positive on fixture", out["body"])
self.assertIn(
"<!-- cr-review-meta: max_id=02 head_sha=sha_same verdict=ready -->",
out["body"],
)
def test_duplicate_head_sha_and_verdict_exits_2_with_empty_stdout(self):
prior_reviews = [
[
{
"body": "Already reviewed\n<!-- cr-review-meta: max_id=01 head_sha=dup1234 verdict=ready -->"
}
]
]
res = self._run({"findings": []}, reviews=prior_reviews, head_sha="dup1234", verdict="ready")
self.assertEqual(res.returncode, 2)
self.assertEqual(res.stdout.strip(), "")
self.assertIn("duplicate", res.stderr.lower())
def test_three_rework_cycle_cap_blocks_fourth_needs_rework_but_allows_ready(self):
prior_reviews = [
{"body": "<!-- cr-review-meta: max_id=01 head_sha=sha1 verdict=needs_rework -->"},
{"body": "<!-- cr-review-meta: max_id=02 head_sha=sha2 verdict=needs_rework -->"},
{"body": "<!-- cr-review-meta: max_id=03 head_sha=sha3 verdict=needs_rework -->"},
]
res_blocked = self._run(
{"findings": []},
reviews=prior_reviews,
head_sha="sha4",
verdict="needs_rework",
)
self.assertEqual(res_blocked.returncode, 1)
self.assertEqual(res_blocked.stdout.strip(), "")
self.assertIn("3-rework-cycle cap", res_blocked.stderr.lower())
res_ready = self._run(
{"findings": []},
reviews=prior_reviews,
head_sha="sha4",
verdict="ready",
)
self.assertEqual(res_ready.returncode, 0, res_ready.stderr)
out = json.loads(res_ready.stdout)
self.assertIn("<!-- cr-review-meta: max_id=03 head_sha=sha4 verdict=ready -->", out["body"])
def test_invalid_inputs_exit_1(self):
# Invalid JSON
res_bad_json = self._run("{not valid json")
self.assertEqual(res_bad_json.returncode, 1)
# Invalid verdict
res_bad_verdict = self._run({"findings": []}, verdict="approved")
self.assertEqual(res_bad_verdict.returncode, 1)
# Missing required findings key
res_no_findings = self._run({"rv_checks": []})
self.assertEqual(res_no_findings.returncode, 1)
# Finding missing required field (title)
res_missing_field = self._run(
{"findings": [{"severity": "High", "body": "Missing title"}]}
)
self.assertEqual(res_missing_field.returncode, 1)
# Invalid side value
res_bad_side = self._run(
{
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "CENTER",
"severity": "Low",
"title": "Bad side",
"body": "Invalid side enum.",
}
]
}
)
self.assertEqual(res_bad_side.returncode, 1)
if __name__ == "__main__":
unittest.main()