import json import shutil import unittest from pathlib import Path from unittest import mock from docs_review import drafter, local from tests import test_cli, test_cli_monthly from tests.test_cli import BRANCH, git FAKE_PI = Path(__file__).resolve().parent / "fake_pi.py" KEY = "local-model-key-value-123456" URL = "http://model-host:8888/v1" def up(model="org/model-a"): return mock.patch.object(local, "probe", return_value=local.Probe(model, None, True)) def down(note): return mock.patch.object(local, "probe", return_value=local.Probe(None, note, True)) class LocalSetup: def local_setup(self): tmp = Path(self._tmp.name) self.fake_pi = tmp / "bin" / "fake_pi.py" shutil.copy(FAKE_PI, self.fake_pi) self.fake_pi.chmod(0o755) self.env.update({"INPUT_DRAFTER": "local", "INPUT_LOCAL_URL": URL, "LOCAL_MODEL_API_KEY": KEY, "DOCS_REVIEW_PI_BIN": str(self.fake_pi)}) self.argv_file = tmp / "pi-argv" def pi(self, **config): config = {"sentinel": str(self.sentinel), "env_file": str(self.env_file), "argv_file": str(self.argv_file), **config} self.fake_pi.with_name("fake_pi.json").write_text(json.dumps(config), encoding="utf-8") class LocalPrTests(LocalSetup, test_cli.CliCase): def setUp(self): super().setUp() self.local_setup() def test_local_drafts_with_the_resident_model(self): self.pi(edit="docs/README.md") with up() as probe: self.assertEqual(self.run_pr(self.feature_commit()), 0) probe.assert_called_once_with(URL, KEY) self.assertEqual(len(self.fake.prs), 1) self.assertIn("Edited by the local drafter.", git(self.remote, "show", f"{BRANCH}:docs/README.md")) argv = json.loads(self.argv_file.read_text()) self.assertEqual(argv[argv.index("--model") + 1], "org/model-a") self.assertNotIn(KEY, " ".join(argv)) self.assertIn("Drafted by pi with org/model-a: 2 turns.", self.fake.prs[0]["body"].splitlines()[-1]) def test_only_the_local_key_reaches_pi(self): self.env["CLAUDE_CODE_OAUTH_TOKEN"] = "oauth-token-value-123456" self.pi(edit="docs/README.md") with up(): self.assertEqual(self.run_pr(self.feature_commit()), 0) names = self.env_file.read_text().split() self.assertIn("LOCAL_MODEL_API_KEY", names) for name in ("ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "DOCS_REVIEW_BOT_TOKEN"): self.assertNotIn(name, names) def test_unreachable_server_fails_soft(self): self.pi(edit="docs/README.md") with down(local.UNREACHABLE_NOTE): self.assertEqual(self.run_pr(self.feature_commit()), 0) bodies = self.comment_bodies() self.assertEqual(len(bodies), 1) self.assertIn("local drafter unavailable: model server unreachable", bodies[0]) self.assertIn("Touched", bodies[0]) self.assertFalse(self.sentinel.exists()) self.assertEqual(self.fake.prs, []) def test_no_model_loaded_fails_soft(self): self.pi() with down(local.NO_MODEL_NOTE): self.assertEqual(self.run_pr(self.feature_commit()), 0) self.assertIn("local drafter unavailable: no model loaded", self.comment_bodies()[0]) self.assertFalse(self.sentinel.exists()) def test_rejected_key_fails_hard(self): self.pi() with mock.patch.object(local, "probe", return_value=local.Probe(None, local.REJECTED_NOTE, False)): self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assertIn(local.REJECTED_NOTE, self.comment_bodies()[0]) def test_root_without_a_drafter_user_fails_hard(self): self.pi() self.env.pop("DOCS_REVIEW_DRAFTER_USER", None) with up(), mock.patch.object(local.os, "geteuid", return_value=0): self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assertIn("DOCS_REVIEW_DRAFTER_USER", self.comment_bodies()[0]) self.assertFalse(self.sentinel.exists()) def test_missing_key_fails_before_probing(self): self.pi() self.env["LOCAL_MODEL_API_KEY"] = "" with up() as probe: self.assertEqual(self.run_pr(self.feature_commit()), 1) probe.assert_not_called() self.assertIn("LOCAL_MODEL_API_KEY is not set", self.comment_bodies()[0]) def test_tokens_and_turns_reach_the_step_summary(self): summary = Path(self._tmp.name) / "step-summary.md" self.pi(edit="docs/README.md") with up(): self.assertEqual(self.run_pr(self.feature_commit(), GITHUB_STEP_SUMMARY=str(summary)), 0) text = summary.read_text() self.assertIn("num_turns: 2", text) self.assertIn("output_tokens: 40", text) self.assertIn("max_input_tokens: 100", text) self.assertNotIn("total_cost_usd", text) def test_project_pi_config_is_removed_from_the_sandbox(self): self.write(self.seed, ".pi/settings.json", '{"defaultModel": "other"}\n') self.write(self.seed, ".pi/extensions/x.ts", "export default () => {}\n") self.write(self.seed, ".pi.json", "{}\n") listing = Path(self._tmp.name) / "listing" self.pi(edit="docs/README.md", list_file=str(listing)) with up(): self.assertEqual(self.run_pr(self.feature_commit()), 0) names = listing.read_text().split() self.assertNotIn(".pi", names) self.assertNotIn(".pi.json", names) self.assertIn("docs", names) self.assertEqual(len(self.fake.prs), 1) self.assertNotIn(".pi/settings.json", git(self.remote, "show", "--stat", "--format=", BRANCH)) def test_recreating_pi_config_is_refused(self): self.env["INPUT_DOCS"] = "docs/*.md\n**/*.md" self.pi(edit=".pi/notes.md") with up(): self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assertTrue(any(".pi/notes.md" in b for b in self.comment_bodies())) self.assertEqual(self.fake.prs, []) def test_drafter_that_ran_and_failed_is_exit_1(self): self.pi(fail=True) with up(): self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assertIn("drafter failed: pi reported an error", self.comment_bodies()[0]) def test_outside_docs_is_refused_as_for_claude(self): self.pi(edit="R/a.R") with up(): self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assertTrue(any("R/a.R" in b for b in self.comment_bodies())) self.assertEqual(self.fake.prs, []) def test_missing_local_url_is_a_usage_error(self): self.env["INPUT_LOCAL_URL"] = "" self.assertEqual(self.run_pr(self.feature_commit()), 2) class LocalMonthlyTests(LocalSetup, test_cli_monthly.MonthlyCase): def setUp(self): super().setUp() self.local_setup() def test_unreachable_server_posts_issue_and_exits_0(self): self.pi(edit="docs/README.md") with down(local.UNREACHABLE_NOTE): self.assertEqual(self.run_monthly("2026-12"), 0) self.assertEqual(len(self.fake.issues), 1) self.assertIn("model server unreachable", self.fake.issues[0]["body"]) self.assertFalse(self.sentinel.exists()) def test_monthly_pr(self): self.pi(edit="docs/README.md") with up(): self.assertEqual(self.run_monthly("2026-12"), 0) self.assertEqual(len(self.fake.prs), 1) class GitMetadataTests(LocalSetup, test_cli.CliCase): """The drafter writes straight into the checkout's .git, which the sandbox does not cover; the run must stop before any further git command.""" def setUp(self): super().setUp() self.local_setup() self.hook = self.work / ".git" / "hooks" / "post-commit" def assert_stopped(self): self.assertIn(drafter.GIT_METADATA_NOTE, self.comment_bodies()[0]) self.assertEqual(self.fake.prs, []) self.assertNotIn(BRANCH, " ".join(self.remote_branches())) def test_claude_writing_a_hook_fails_the_run(self): self.env["INPUT_DRAFTER"] = "claude" self.claude(edit=str(self.hook)) sha = self.feature_commit() calls = [] real = drafter.subprocess.run def record(argv, **kw): calls.append(list(argv)) return real(argv, **kw) with mock.patch.object(drafter.subprocess, "run", side_effect=record): self.assertEqual(self.run_pr(sha), 1) self.assert_stopped() ran = [i for i, a in enumerate(calls) if a[0] == str(self.fake_claude)] self.assertEqual(len(ran), 1) self.assertEqual([a for a in calls[ran[0] + 1:] if a[0] == "git"], []) def test_local_writing_a_hook_fails_the_run(self): self.pi(edit=str(self.hook)) with up(): self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assert_stopped() def test_changing_git_config_fails_the_run(self): self.pi(edit=str(self.work / ".git" / "config"), write="[core]\n\thooksPath = /tmp") with up(): self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assert_stopped() def test_metadata_check_passes_an_untouched_checkout(self): self.pi(edit="docs/README.md") with up(): self.assertEqual(self.run_pr(self.feature_commit()), 0) self.assertEqual(len(self.fake.prs), 1) if __name__ == "__main__": unittest.main()