tests / unittest (push) Successful in 23s
review_only names listed documents the drafter may read but not edit. They stay in stage 1, are listed separately in the prompt, and a change to one fails the run like a change outside docs. Each entry must match a docs pattern. The monthly prompt now makes checking every list and count in the top-level documents against the repository the drafter's main job. Mode-specific text moves to prompts/mode-pr.md and prompts/mode-monthly.md; the pr text is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
250 lines
11 KiB
Python
250 lines
11 KiB
Python
import json
|
|
import unittest
|
|
|
|
from docs_review.draft import (
|
|
DIFF_CAP_BYTES,
|
|
LAST_HEAD,
|
|
DraftResult,
|
|
Summary,
|
|
build_prompt,
|
|
claude_argv,
|
|
diff_payload,
|
|
load_template,
|
|
outside_docs,
|
|
parse_claude_output,
|
|
parse_last_head,
|
|
parse_summary,
|
|
render_pr_body,
|
|
should_skip,
|
|
)
|
|
from docs_review.flags import Flag
|
|
from docs_review.git import Commit
|
|
|
|
BOT = "docs-review-bot@civilytics.org"
|
|
|
|
|
|
class PayloadTest(unittest.TestCase):
|
|
def test_diff_over_cap_becomes_file_list(self):
|
|
p = diff_payload("x" * 200_001, "10\t2\tR/a.R\n")
|
|
self.assertIn("R/a.R", p)
|
|
self.assertNotIn("xxxx", p)
|
|
self.assertIn("file list", p)
|
|
self.assertIn("200,000", p)
|
|
self.assertEqual(diff_payload("small", "1\t0\tR/a.R\n"), "small")
|
|
self.assertEqual(DIFF_CAP_BYTES, 200_000)
|
|
|
|
def test_cap_counts_bytes(self):
|
|
self.assertIn("file list", diff_payload("é" * 100_001, "1\t0\ta\n"))
|
|
self.assertEqual(diff_payload("x" * 200_000, "1\t0\ta\n"), "x" * 200_000)
|
|
|
|
|
|
class PromptTest(unittest.TestCase):
|
|
def _build(self, **kw):
|
|
args = dict(mode="pr", pr=12, flags_json="{}", payload="p",
|
|
docs=("a.md", "b.md"), top_level=("README.md",), guide_path=None)
|
|
args.update(kw)
|
|
return build_prompt("{mode}|{pr}|{flags_json}|{payload}|{docs}|{top_level}|{guide_note}",
|
|
**args)
|
|
|
|
def test_fields_and_literal_braces_in_payload(self):
|
|
out = self._build(payload="function() { return {a: 1} }", flags_json='{"k": 1}')
|
|
self.assertIn("function() { return {a: 1} }", out)
|
|
self.assertIn('{"k": 1}', out)
|
|
self.assertIn("a.md\nb.md", out)
|
|
self.assertTrue(out.startswith("pr|12|"))
|
|
|
|
def test_guide_note_and_monthly_pr(self):
|
|
self.assertIn("No guide is set", self._build())
|
|
out = self._build(guide_path="docs/README.md", mode="monthly", pr=None)
|
|
self.assertIn("The guide appended to your system prompt, docs/README.md,", out)
|
|
self.assertIn("monthly|none|", out)
|
|
|
|
def test_shipped_template_renders(self):
|
|
out = build_prompt(load_template("pr"), mode="pr", pr=7, flags_json="{}", payload="{x}",
|
|
docs=("a.md",), top_level=("README.md",), guide_path=None)
|
|
self.assertIn("```json", out)
|
|
self.assertIn("{x}", out)
|
|
self.assertNotIn("{mode}", out)
|
|
|
|
def test_review_only_section(self):
|
|
t = "{docs}|{review_only}"
|
|
none = build_prompt(t, mode="pr", pr=1, flags_json="{}", payload="",
|
|
docs=("a.md",), top_level=(), guide_path=None)
|
|
self.assertEqual(none, "a.md|")
|
|
out = build_prompt(t, mode="pr", pr=1, flags_json="{}", payload="",
|
|
docs=("a.md",), top_level=(), guide_path=None,
|
|
review_only=("v.md", "w.md"))
|
|
self.assertIn("Documents you may read but not edit:\n\nv.md\nw.md", out)
|
|
self.assertIn("declined", out)
|
|
|
|
|
|
class TemplateModeTest(unittest.TestCase):
|
|
def _render(self, mode, review_only=()):
|
|
return build_prompt(load_template(mode), mode=mode, pr=None if mode == "monthly" else 7,
|
|
flags_json="{}", payload="p", docs=("README.md", "docs/a.md"),
|
|
top_level=("README.md",), guide_path=None,
|
|
review_only=review_only)
|
|
|
|
def test_monthly_asks_for_enumeration_check_and_lists_review_only(self):
|
|
out = self._render("monthly", ("docs/vision.md",))
|
|
self.assertIn("check every enumeration", out)
|
|
self.assertIn("Glob", out)
|
|
self.assertIn("A list presented as complete must be complete", out)
|
|
self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", out)
|
|
self.assertIn("README.md", out)
|
|
for field in ("{top_level}", "{mode_text}", "{review_only}", "{docs}"):
|
|
self.assertNotIn(field, out)
|
|
|
|
def test_pr_has_no_enumeration_check(self):
|
|
out = self._render("pr", ("docs/vision.md",))
|
|
self.assertNotIn("enumeration", out)
|
|
self.assertIn("find what this pull request makes stale", out)
|
|
self.assertIn("Documents you may read but not edit:\n\ndocs/vision.md", out)
|
|
|
|
def test_review_only_section_absent_when_empty(self):
|
|
for mode in ("pr", "monthly"):
|
|
self.assertNotIn("read but not edit", self._render(mode))
|
|
|
|
def test_unknown_mode_raises(self):
|
|
with self.assertRaises(ValueError):
|
|
load_template("weekly")
|
|
|
|
|
|
class ArgvTest(unittest.TestCase):
|
|
def test_argv_matches_spec(self):
|
|
a = claude_argv("claude", "claude-sonnet-5-5", "docs/README.md")
|
|
for flag in ("-p", "--no-session-persistence", "--max-turns", "--disallowedTools", "--setting-sources"):
|
|
self.assertIn(flag, a)
|
|
self.assertEqual(a[0], "claude")
|
|
self.assertEqual(a[a.index("--tools") + 1], "Read,Glob,Grep,Edit,Write")
|
|
i = a.index("--allowedTools")
|
|
self.assertEqual(a[i + 1:i + 6], ["Read(./**)", "Glob(./**)", "Grep(./**)",
|
|
"Edit(./**)", "Write(./**)"])
|
|
self.assertEqual(a[i + 6], "--disallowedTools")
|
|
self.assertEqual(a[a.index("--disallowedTools") + 1], "Bash")
|
|
self.assertEqual(a[a.index("--max-turns") + 1], "25")
|
|
self.assertEqual(a[a.index("--max-budget-usd") + 1], "2.00")
|
|
self.assertEqual(a[a.index("--permission-mode") + 1], "dontAsk")
|
|
self.assertEqual(a[a.index("--model") + 1], "claude-sonnet-5-5")
|
|
self.assertEqual(a[a.index("--output-format") + 1], "json")
|
|
self.assertEqual(a[a.index("--append-system-prompt-file") + 1], "docs/README.md")
|
|
self.assertNotIn("--bare", a)
|
|
self.assertNotIn("--append-system-prompt-file", claude_argv("claude", "m", None))
|
|
|
|
|
|
class ResultTest(unittest.TestCase):
|
|
def test_success(self):
|
|
out = json.dumps({"result": "hi", "is_error": False, "num_turns": 3,
|
|
"total_cost_usd": 0.5, "subtype": "success"})
|
|
r = parse_claude_output(out, 0)
|
|
self.assertTrue(r.ok)
|
|
self.assertEqual((r.text, r.turns, r.cost_usd, r.error), ("hi", 3, 0.5, None))
|
|
|
|
def test_failed_claude_is_not_ok(self):
|
|
r = parse_claude_output('{"is_error": true, "result": "Invalid API key"}', 1)
|
|
self.assertFalse(r.ok)
|
|
self.assertIn("Invalid API key", r.error)
|
|
self.assertFalse(parse_claude_output("not json", 0).ok)
|
|
self.assertIn("not JSON", parse_claude_output("not json", 0).error)
|
|
self.assertIn("exit code 2", parse_claude_output("{}", 2).error)
|
|
|
|
def test_non_success_subtype_is_not_ok(self):
|
|
for sub in ("error_max_turns", "error_max_budget_usd"):
|
|
r = parse_claude_output(json.dumps({"subtype": sub, "result": "x"}), 0)
|
|
self.assertFalse(r.ok)
|
|
self.assertIn(sub, r.error)
|
|
self.assertTrue(parse_claude_output('{"subtype": "success"}', 0).ok)
|
|
|
|
def test_missing_keys_and_non_object(self):
|
|
r = parse_claude_output("{}", 0)
|
|
self.assertTrue(r.ok)
|
|
self.assertIsNone(r.cost_usd)
|
|
self.assertIsNone(r.turns)
|
|
self.assertEqual(r.text, "")
|
|
self.assertFalse(parse_claude_output("[1]", 0).ok)
|
|
|
|
|
|
class SummaryTest(unittest.TestCase):
|
|
def test_last_json_block_wins(self):
|
|
first = '```json\n{"edits": [{"path": "old", "why": "x"}], "declined": []}\n```'
|
|
last = ('```json\n{"edits": [{"path": "docs/a.md", "why": "renamed"}], '
|
|
'"declined": [{"flag": "dead: R/x.R", "reason": "kept"}]}\n```')
|
|
s = parse_summary(f"intro\n{first}\nmore\n{last}\n")
|
|
self.assertEqual(s.edits, (("docs/a.md", "renamed"),))
|
|
self.assertEqual(s.declined, (("dead: R/x.R", "kept"),))
|
|
|
|
def test_none_when_absent_or_wrong_shape(self):
|
|
self.assertIsNone(parse_summary("no block"))
|
|
self.assertIsNone(parse_summary('```json\n{"other": 1}\n```'))
|
|
self.assertIsNone(parse_summary("```json\n{broken\n```"))
|
|
|
|
|
|
class OutsideDocsTest(unittest.TestCase):
|
|
def test_outside_docs(self):
|
|
self.assertEqual(
|
|
outside_docs(["README.md", "docs/book/08-new.qmd", "R/a.R"],
|
|
("README.md", "docs/book/*.qmd")), ["R/a.R"])
|
|
|
|
def test_double_star_zero_directories(self):
|
|
self.assertEqual(outside_docs(["docs/c.md"], ("docs/**/*.md",)), [])
|
|
|
|
|
|
class SkipTest(unittest.TestCase):
|
|
merge = Commit("m", "jared@x", 2,
|
|
"Merge pull request 'docs: proposed edits for #12' (#40) "
|
|
"from docs-review/pr-12 into feat/x")
|
|
|
|
def test_skip_only_when_every_new_commit_is_docs_review(self):
|
|
self.assertTrue(should_skip(
|
|
[self.merge, Commit("c", BOT, 1, "docs(docs): proposed edits (#12)")], BOT, 12))
|
|
self.assertFalse(should_skip([self.merge, Commit("d", "jared@x", 1, "fix: thing")], BOT, 12))
|
|
self.assertFalse(should_skip([], BOT, 12))
|
|
|
|
def test_pr_number_is_exact(self):
|
|
self.assertFalse(should_skip([self.merge], BOT, 1))
|
|
self.assertFalse(should_skip([self.merge], BOT, 120))
|
|
m120 = Commit("m", "j@x", 2, "Merge pull request from docs-review/pr-120 into x")
|
|
self.assertFalse(should_skip([m120], BOT, 12))
|
|
self.assertTrue(should_skip([m120], BOT, 120))
|
|
|
|
def test_non_merge_human_commit_naming_branch_is_not_skipped(self):
|
|
self.assertFalse(should_skip([Commit("x", "j@x", 1, "see docs-review/pr-12")], BOT, 12))
|
|
|
|
|
|
SHA = "0123456789abcdef0123456789abcdef01234567"
|
|
|
|
|
|
class BodyTest(unittest.TestCase):
|
|
flags = (Flag("dead", "docs/a.md", "R/x.R", "removed"),)
|
|
result = DraftResult(True, 0.4321, 9, "t", None)
|
|
|
|
def test_head_round_trip(self):
|
|
self.assertEqual(LAST_HEAD.format(sha="abc"), "<!-- docs-review:last-head=abc -->")
|
|
self.assertEqual(parse_last_head("x\n" + LAST_HEAD.format(sha=SHA) + "\ny"), SHA)
|
|
self.assertIsNone(parse_last_head("nothing"))
|
|
|
|
def test_last_head_must_be_a_full_sha(self):
|
|
for bad in ("--output=/x", "abc123", SHA.upper(), SHA + "0", "g" * 40):
|
|
self.assertIsNone(parse_last_head(LAST_HEAD.format(sha=bad)), bad)
|
|
|
|
def test_body_with_summary(self):
|
|
s = Summary((("docs/a.md", "R/x.R was removed"),), (("touched: R/y.R", "no change needed"),))
|
|
body = render_pr_body(s, self.result, self.flags, "deadbeef", ["R/x.R"])
|
|
self.assertEqual(body.splitlines()[0], LAST_HEAD.format(sha="deadbeef"))
|
|
self.assertIn("- `docs/a.md`: R/x.R was removed", body)
|
|
self.assertIn("touched: R/y.R: no change needed", body)
|
|
self.assertIn("### Flags from stage 1", body)
|
|
self.assertIn("- `docs/a.md`: `R/x.R` (removed)", body)
|
|
self.assertIn("Drafted by Claude Code: 9 turns, $0.43 estimated.", body.splitlines()[-1])
|
|
|
|
def test_body_without_summary(self):
|
|
body = render_pr_body(None, DraftResult(True, None, None, "", None), self.flags,
|
|
"abc", ["docs/a.md", "docs/b.md"])
|
|
self.assertIn("no summary", body)
|
|
self.assertIn("`docs/b.md`", body)
|
|
self.assertIn("unknown turns, $unknown estimated.", body)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|