test_project_status.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The generated project status page (issue #259).
  3. What is proved here, all offline (CI has no maintainer token and never calls
  4. GitHub):
  5. - each classification rule of the 2026-10-22 audit, one test per rule, so that
  6. reverting a rule fails a test: in flight, has merged PR, needs the maintainer,
  7. not started, the order between them, and what does not count;
  8. - the board gaps (missing issues and PRs, closed but not Done) and the
  9. 'board data may lag' line;
  10. - the committed page is exactly the render of the committed snapshot, says when
  11. it was generated, and fails --check when edited by hand or stale;
  12. - the fetch layer passes argument lists to gh and never a shell.
  13. """
  14. import copy
  15. import json
  16. import re
  17. import subprocess
  18. import sys
  19. from pathlib import Path
  20. import pytest
  21. ROOT = Path(__file__).resolve().parent.parent
  22. sys.path.insert(0, str(ROOT / "scripts"))
  23. import gen_project_status as gps
  24. REPO = "Example/Repo"
  25. STAMP = "2026-10-22T12:00:00Z"
  26. def issue(n, state="OPEN", labels=(), title=None):
  27. return {"number": n, "title": title or f"Issue {n}", "state": state, "labels": list(labels)}
  28. def pr(n, body="", state="OPEN", draft=False, ci="none", review=""):
  29. return {
  30. "number": n,
  31. "title": f"PR {n}",
  32. "state": state,
  33. "isDraft": draft,
  34. "body": body,
  35. "ci": ci,
  36. "reviewDecision": review,
  37. }
  38. def item(kind, n, repo=REPO, **fields):
  39. return {"type": kind, "number": n, "repo": repo, "fields": fields}
  40. def snap(issues=(), prs=(), board=(), total=None):
  41. return {
  42. "schema": gps.SCHEMA,
  43. "repo": REPO,
  44. "project": {"owner": "Example", "number": 4},
  45. "fetched_at": STAMP,
  46. "issues": list(issues),
  47. "prs": list(prs),
  48. "board": {"total": len(board) if total is None else total, "items": list(board)},
  49. }
  50. def cats(snapshot):
  51. result = gps.classify(snapshot)["categories"]
  52. return {k: [e["issue"]["number"] for e in v] for k, v in result.items()}
  53. # --- the link parser ------------------------------------------------------------
  54. @pytest.mark.parametrize(
  55. "word", ["Closes", "closes", "Fixes", "Resolves", "Refs", "refs", "Fixed", "Resolved", "Closed"]
  56. )
  57. def test_every_keyword_links(word):
  58. assert gps.pr_links(f"{word} #7", REPO) == {7: "refs" if word.lower() == "refs" else "closes"}
  59. def test_a_list_of_numbers_all_link():
  60. assert gps.pr_links("Closes #1, #2 and #3", REPO) == {1: "closes", 2: "closes", 3: "closes"}
  61. def test_a_closing_word_beats_refs_for_the_same_number():
  62. assert gps.pr_links("Refs #4\nCloses #4", REPO) == {4: "closes"}
  63. assert gps.pr_links("Closes #4\nRefs #4", REPO) == {4: "closes"}
  64. def test_a_bare_number_or_other_repo_does_not_link():
  65. assert gps.pr_links("see #5 and (#6)", REPO) == {}
  66. assert gps.pr_links("Closes Other/Thing#9", REPO) == {}
  67. assert gps.pr_links("Closes example/repo#9", REPO) == {9: "closes"}
  68. def test_reduce_body_keeps_only_the_links():
  69. body = "Long text with a secret-looking line\nCloses #3, #4\nmore text"
  70. reduced = gps.reduce_body(body, REPO)
  71. assert "secret" not in reduced and "more text" not in reduced
  72. assert gps.pr_links(reduced, REPO) == {3: "closes", 4: "closes"}
  73. # --- classification: one test per rule -----------------------------------------
  74. @pytest.mark.parametrize("body", ["Closes #1", "Fixes #1", "Resolves #1", "Refs #1"])
  75. def test_an_open_pr_makes_the_issue_in_flight(body):
  76. result = cats(snap([issue(1)], [pr(10, body)]))
  77. assert result[gps.IN_FLIGHT] == [1]
  78. assert result[gps.NOT_STARTED] == []
  79. def test_a_draft_pr_still_counts_as_in_flight():
  80. assert cats(snap([issue(1)], [pr(10, "Closes #1", draft=True)]))[gps.IN_FLIGHT] == [1]
  81. def test_a_merged_pr_makes_the_issue_a_review_for_close():
  82. result = cats(snap([issue(1)], [pr(10, "Closes #1", state="MERGED")]))
  83. assert result[gps.MERGED] == [1]
  84. assert result[gps.NOT_STARTED] == []
  85. def test_a_refs_only_merged_pr_still_lands_in_review_but_is_flagged():
  86. snapshot = snap([issue(1)], [pr(10, "Refs #1", state="MERGED")])
  87. assert cats(snapshot)[gps.MERGED] == [1]
  88. page = gps.render(snapshot)
  89. assert "refs only" in page
  90. assert "A `Refs` link is not proof the work is done" in page
  91. def test_a_closing_merged_pr_is_not_labeled_refs_only():
  92. page = gps.render(snap([issue(1)], [pr(10, "Closes #1", state="MERGED")]))
  93. row = next(line for line in page.splitlines() if line.startswith("| [#1]"))
  94. assert "(closes)" in row and "refs only" not in row
  95. def test_an_open_pr_beats_a_merged_pr():
  96. prs = [pr(10, "Closes #1", state="MERGED"), pr(11, "Refs #1")]
  97. assert cats(snap([issue(1)], prs))[gps.IN_FLIGHT] == [1]
  98. def test_the_needs_maintainer_label():
  99. result = cats(snap([issue(1, labels=["needs-maintainer"]), issue(2, labels=["bug"])]))
  100. assert result[gps.MAINTAINER] == [1]
  101. assert result[gps.NOT_STARTED] == [2]
  102. def test_a_pr_outranks_the_maintainer_label():
  103. open_pr = cats(snap([issue(1, labels=["needs-maintainer"])], [pr(10, "Refs #1")]))
  104. assert open_pr[gps.IN_FLIGHT] == [1]
  105. merged = cats(snap([issue(1, labels=["needs-maintainer"])], [pr(10, "Closes #1", state="MERGED")]))
  106. assert merged[gps.MERGED] == [1]
  107. def test_not_started_is_the_rest():
  108. assert cats(snap([issue(1)]))[gps.NOT_STARTED] == [1]
  109. def test_a_pr_closed_without_merging_counts_for_nothing():
  110. assert cats(snap([issue(1)], [pr(10, "Closes #1", state="CLOSED")]))[gps.NOT_STARTED] == [1]
  111. def test_closed_issues_are_not_classified():
  112. result = cats(snap([issue(1, state="CLOSED")], [pr(10, "Closes #1")]))
  113. assert all(v == [] for v in result.values())
  114. def test_a_pr_in_another_repo_does_not_make_an_issue_in_flight():
  115. assert cats(snap([issue(1)], [pr(10, "Closes Other/Thing#1")]))[gps.NOT_STARTED] == [1]
  116. # --- board gaps and the lag line -----------------------------------------------
  117. def test_issues_and_prs_missing_from_the_board():
  118. snapshot = snap(
  119. [issue(1), issue(2)],
  120. [pr(10), pr(11)],
  121. [item("Issue", 1, Status="Next"), item("PullRequest", 10)],
  122. )
  123. gaps = gps.board_gaps(snapshot)
  124. assert [i["number"] for i in gaps["missing_issues"]] == [2]
  125. assert [p["number"] for p in gaps["missing_prs"]] == [11]
  126. def test_a_board_item_from_another_repository_does_not_count():
  127. snapshot = snap([issue(1)], [], [item("Issue", 1, repo="Other/Thing", Status="Done")])
  128. assert [i["number"] for i in gps.board_gaps(snapshot)["missing_issues"]] == [1]
  129. def test_closed_issue_not_done_on_the_board():
  130. snapshot = snap(
  131. [issue(1, "CLOSED"), issue(2, "CLOSED"), issue(3, "OPEN"), issue(4, "CLOSED")],
  132. [],
  133. [
  134. item("Issue", 1, Status="Next"),
  135. item("Issue", 2, Status="Done"),
  136. item("Issue", 3, Status="Next"),
  137. item("Issue", 4),
  138. ],
  139. )
  140. got = [(i["number"], s) for i, s in gps.board_gaps(snapshot)["closed_not_done"]]
  141. assert got == [(1, "Next"), (4, None)]
  142. def test_a_closed_issue_missing_from_the_board_is_a_missing_issue_not_a_not_done_one():
  143. gaps = gps.board_gaps(snap([issue(1, "CLOSED")]))
  144. assert gaps["closed_not_done"] == []
  145. assert len(gaps["missing_issues"]) == 1
  146. def test_the_lag_line_when_the_board_holds_fewer_items_than_there_are_issues():
  147. snapshot = snap([issue(1), issue(2), issue(3)], [], [item("Issue", 1)])
  148. page = gps.render(snapshot)
  149. assert "Board data may lag" in page
  150. assert "2 issues are not visible on the board" in page
  151. def test_the_lag_line_uses_the_board_total_even_when_every_issue_is_listed():
  152. snapshot = snap([issue(1), issue(2)], [], [item("Issue", 1), item("Issue", 2)], total=1)
  153. assert "Board data may lag" in gps.render(snapshot)
  154. def test_no_lag_line_when_the_board_is_complete():
  155. snapshot = snap([issue(1)], [], [item("Issue", 1, Status="Next")])
  156. page = gps.render(snapshot)
  157. assert "Board data may lag" not in page
  158. assert "| Issues not visible on the board | 0 |" in page
  159. def test_prs_with_no_linked_issue():
  160. prs = [
  161. pr(10, "Closes #1"),
  162. pr(11, "no link here"),
  163. pr(12, "no link", state="MERGED"),
  164. pr(13, "no link", state="CLOSED"),
  165. pr(14, "Refs #1", state="MERGED"),
  166. ]
  167. page = gps.render(snap([issue(1)], prs))
  168. assert "## Pull requests with no linked issue (2)" in page
  169. section = page.split("## Pull requests with no linked issue")[1].split("## Reproduce")[0]
  170. assert "[#11]" in section and "[#12]" in section
  171. assert "[#10]" not in section and "[#13]" not in section and "[#14]" not in section
  172. # --- page content --------------------------------------------------------------
  173. def test_the_page_states_when_it_was_generated_and_the_commands():
  174. page = gps.render(snap([issue(1)]))
  175. assert f"**Generated at:** {STAMP} (UTC)" in page
  176. assert "gh issue list --repo Example/Repo --state all" in page
  177. assert "gen_project_status.py --refresh" in page
  178. def test_open_prs_show_ci_and_review_state():
  179. page = gps.render(snap([issue(1)], [pr(10, "Closes #1", ci="failing", review="CHANGES_REQUESTED")]))
  180. row = next(line for line in page.splitlines() if line.startswith("| [#10]"))
  181. assert "failing" in row and "changes requested" in row
  182. HOSTILE_TITLES = [
  183. "[click](https://evil.example)",
  184. "![x](https://evil.example/p.png)",
  185. "<script>alert(1)</script>",
  186. "a `b` | c `|` d",
  187. "a\\|b",
  188. "a\\\\|b",
  189. "ends with a backslash\\",
  190. "\\\nnext",
  191. "|",
  192. "||",
  193. "\\\\\\\\",
  194. "see https://evil.example and www.evil.example and bob@evil.example",
  195. "line one\nline two\r\n| injected | row |",
  196. "x" * 5000,
  197. "\\[escaped](https://evil.example)",
  198. "# heading > quote * star _ under ~ tilde",
  199. "x\n# Heading\n[a](https://evil.example)",
  200. ]
  201. CODE_SPAN = re.compile(r"`[^`]*`")
  202. LEGIT_LINK = re.compile(r"\[#\d+\]\(https://github\.com/Example/Repo/(?:issues|pull)/\d+\)")
  203. def split_row(row):
  204. """A minimal GFM table-row splitter, as the spec describes it.
  205. Cells are separated by unescaped pipes. A pipe preceded by a backslash is
  206. part of the cell, and this happens before any inline parsing, so it applies
  207. inside code spans too (GFM spec 0.29, extension "Tables", example 200:
  208. `| f\\|oo |` is one cell holding f|oo). A leading and a trailing pipe are
  209. delimiters, not cells.
  210. """
  211. cells, current, i = [], "", 0
  212. while i < len(row):
  213. ch = row[i]
  214. if ch == "\\" and row[i + 1 : i + 2] == "|":
  215. current += "|"
  216. i += 2
  217. continue
  218. if ch == "|":
  219. cells.append(current)
  220. current = ""
  221. else:
  222. current += ch
  223. i += 1
  224. cells.append(current)
  225. return [c.strip() for c in cells[1:-1]] if row.startswith("|") and row.rstrip().endswith("|") else None
  226. def test_the_splitter_follows_the_spec_example():
  227. # The spec's table example: an escaped pipe stays inside its cell.
  228. assert split_row("| f\\|oo |") == ["f|oo"]
  229. assert split_row("| a | b |") == ["a", "b"]
  230. assert split_row("| a\\\\| b |") == ["a\\| b"] # `\\|` is a backslash, then an escaped pipe
  231. def rows_for(page, number):
  232. rows = [line for line in page.splitlines() if line.startswith(f"| [#{number}]")]
  233. assert rows
  234. return rows
  235. def assert_inert(page, number):
  236. """Outside code spans a row holds only the one link this code builds."""
  237. for row in rows_for(page, number):
  238. bare = LEGIT_LINK.sub("#", CODE_SPAN.sub("", row))
  239. assert "](" not in bare and "![" not in bare and "<" not in bare and "http" not in bare, row
  240. assert row.count("`") % 2 == 0 and len(row) < 1200, row
  241. for line in page.splitlines():
  242. assert not line.startswith(("# Heading", "[a]("))
  243. assert_every_row_has_its_tables_columns(page)
  244. def assert_every_row_has_its_tables_columns(page):
  245. """Every table row splits into as many cells as its header row has."""
  246. lines = page.splitlines()
  247. width = None
  248. for i, line in enumerate(lines):
  249. if not line.startswith("|"):
  250. width = None
  251. continue
  252. if i + 1 < len(lines) and re.fullmatch(r"\|(---\|)+", lines[i + 1]):
  253. width = len(split_row(line))
  254. continue
  255. if re.fullmatch(r"\|(---\|)+", line):
  256. continue
  257. assert width is not None, line
  258. cells = split_row(line)
  259. assert cells is not None and len(cells) == width, line
  260. @pytest.mark.parametrize("title", HOSTILE_TITLES, ids=range(len(HOSTILE_TITLES)))
  261. @pytest.mark.parametrize("where", ["issue", "pr", "unlinked", "closed"])
  262. def test_a_hostile_title_stays_inert_everywhere(title, where):
  263. if where == "issue":
  264. snapshot, number = snap([issue(1, title=title)]), 1
  265. elif where == "pr":
  266. pull = pr(10, "Closes #1")
  267. pull["title"] = title
  268. snapshot, number = snap([issue(1)], [pull]), 10
  269. elif where == "unlinked":
  270. pull = pr(10, "nothing")
  271. pull["title"] = title
  272. snapshot, number = snap([], [pull]), 10
  273. else:
  274. snapshot, number = snap([issue(1, "CLOSED", title=title)], [], [item("Issue", 1, Status="Next")]), 1
  275. assert_inert(gps.render(snapshot), number)
  276. def test_titles_are_code_spans_with_look_alikes_and_backticks_removed():
  277. page = gps.render(snap([issue(1, title="a | b `x` <i>")]))
  278. assert "`a \u2223 b x <i>`" in rows_for(page, 1)[0]
  279. def test_no_cell_contains_a_pipe_or_backslash_at_all():
  280. page = gps.render(snap([issue(1, title="a\\|b \\ | || \\\\")], [pr(10, "Closes #1", ci="x|y\\")]))
  281. for row in rows_for(page, 1) + rows_for(page, 10):
  282. for cell_text in CODE_SPAN.findall(row):
  283. assert "|" not in cell_text and "\\" not in cell_text
  284. assert "\u2223" in page and "\u29f5" in page
  285. def test_the_page_says_special_characters_are_shown_as_look_alikes():
  286. assert "Special characters in titles are shown as look-alikes" in gps.render(snap([]))
  287. def test_a_long_title_is_cut():
  288. row = rows_for(gps.render(snap([issue(1, title="y" * 5000)])), 1)[0]
  289. assert "y" * 201 not in row and "..." in row
  290. def test_a_newline_in_a_title_cannot_start_a_new_line():
  291. page = gps.render(snap([issue(1, title="x\n# Heading\n| [#9](https://evil.example) |")]))
  292. assert "`x # Heading \u2223 [#9](https://evil.example) \u2223`" in page
  293. def test_board_values_and_ci_are_inert_too():
  294. snapshot = snap(
  295. [issue(1)],
  296. [pr(10, "Closes #1", ci="[a](https://evil.example)", review="![b](https://evil.example/p.png)")],
  297. [item("Issue", 1, Status="[s](https://evil.example)", Size="<b>", Sprint="x")],
  298. )
  299. page = gps.render(snapshot)
  300. assert_inert(page, 1)
  301. assert_inert(page, 10)
  302. def test_the_repo_name_must_be_a_plain_owner_slash_name():
  303. for bad in ("a/b](https://evil.example", "a b/c", "abc", "a/b/c"):
  304. broken = snap([issue(1)])
  305. broken["repo"] = bad
  306. assert gps.validate_snapshot(broken), bad
  307. broken = snap([issue(1)])
  308. broken["project"]["owner"] = "x](https://evil.example"
  309. assert gps.validate_snapshot(broken)
  310. def test_render_is_deterministic_and_does_not_mutate_its_input():
  311. snapshot = snap([issue(2), issue(1)], [pr(10, "Closes #1")])
  312. before = copy.deepcopy(snapshot)
  313. assert gps.render(snapshot) == gps.render(snapshot)
  314. assert snapshot == before
  315. @pytest.mark.parametrize(
  316. "rollup, want",
  317. [
  318. (None, "none"),
  319. ([], "none"),
  320. ([{"status": "COMPLETED", "conclusion": "SUCCESS"}, {"status": "COMPLETED", "conclusion": "SKIPPED"}], "passing"),
  321. ([{"status": "COMPLETED", "conclusion": "SUCCESS"}, {"status": "IN_PROGRESS", "conclusion": ""}], "pending"),
  322. ([{"status": "IN_PROGRESS"}, {"status": "COMPLETED", "conclusion": "FAILURE"}], "failing"),
  323. ([{"state": "FAILURE"}], "failing"),
  324. ([{"state": "PENDING"}], "pending"),
  325. ([{"state": "SUCCESS"}], "passing"),
  326. ],
  327. )
  328. def test_ci_state(rollup, want):
  329. assert gps.ci_state(rollup) == want
  330. # --- the committed page and snapshot -------------------------------------------
  331. def test_the_committed_page_matches_the_committed_snapshot():
  332. assert gps.check_page(ROOT) == []
  333. def test_the_committed_page_says_when_it_was_generated():
  334. page = (ROOT / gps.PAGE).read_text(encoding="utf-8")
  335. match = gps.STAMP_LINE_RE.search(page)
  336. assert match and gps.STAMP_RE.match(match.group(1))
  337. def test_the_committed_snapshot_is_valid():
  338. snapshot = json.loads((ROOT / gps.SNAPSHOT).read_text(encoding="utf-8"))
  339. assert gps.validate_snapshot(snapshot) == []
  340. def run_script(*args, root=None):
  341. cmd = [sys.executable, "-I", str(ROOT / "scripts" / "gen_project_status.py"), *args]
  342. if root is not None:
  343. cmd += ["--root", str(root)]
  344. return subprocess.run(cmd, capture_output=True, text=True, check=False)
  345. def make_root(tmp_path, snapshot=None):
  346. (tmp_path / "docs" / "wiki").mkdir(parents=True)
  347. snapshot = snapshot or snap([issue(1)], [pr(10, "Refs #1")], [item("Issue", 1, Status="Next")])
  348. (tmp_path / gps.SNAPSHOT).write_text(json.dumps(snapshot))
  349. return tmp_path
  350. def test_check_passes_after_a_render(tmp_path):
  351. root = make_root(tmp_path)
  352. assert run_script(root=root).returncode == 0
  353. assert run_script("--check", root=root).returncode == 0
  354. def test_check_fails_on_a_hand_edit_with_a_clear_message(tmp_path):
  355. root = make_root(tmp_path)
  356. run_script(root=root)
  357. page = root / gps.PAGE
  358. page.write_text(page.read_text() + "\nhand edit\n")
  359. result = run_script("--check", root=root)
  360. assert result.returncode == 1
  361. assert "does not match" in result.stderr and "--refresh" in result.stderr
  362. def test_check_fails_when_the_snapshot_changed_but_the_page_did_not(tmp_path):
  363. root = make_root(tmp_path)
  364. run_script(root=root)
  365. changed = json.loads((root / gps.SNAPSHOT).read_text())
  366. changed["issues"].append(issue(2))
  367. (root / gps.SNAPSHOT).write_text(json.dumps(changed))
  368. assert run_script("--check", root=root).returncode == 1
  369. def test_check_fails_when_the_stamp_is_missing_or_does_not_match(tmp_path):
  370. root = make_root(tmp_path)
  371. run_script(root=root)
  372. page = root / gps.PAGE
  373. good = page.read_text()
  374. page.write_text(good.replace("**Generated at:** ", "**Made at:** "))
  375. missing = run_script("--check", root=root)
  376. assert missing.returncode == 1 and "time stamp" in missing.stderr
  377. page.write_text(good.replace(STAMP, "2026-01-01T00:00:00Z"))
  378. other = run_script("--check", root=root)
  379. assert other.returncode == 1 and "snapshot was taken" in other.stderr
  380. def test_check_fails_for_a_missing_page_or_snapshot(tmp_path):
  381. root = make_root(tmp_path)
  382. assert run_script("--check", root=root).returncode == 1
  383. (root / gps.SNAPSHOT).unlink()
  384. assert run_script("--check", root=root).returncode == 1
  385. @pytest.mark.parametrize(
  386. "mutate",
  387. [
  388. lambda s: s.update(fetched_at="yesterday"),
  389. lambda s: s.update(schema=99),
  390. lambda s: s.pop("board"),
  391. lambda s: s["issues"].append({"number": "x"}),
  392. ],
  393. )
  394. def test_an_invalid_snapshot_fails_check(tmp_path, mutate):
  395. bad = snap([issue(1)])
  396. mutate(bad)
  397. root = make_root(tmp_path, bad)
  398. assert run_script("--check", root=root).returncode == 1
  399. # --- the fetch layer -----------------------------------------------------------
  400. def test_gh_is_called_with_an_argument_list_and_no_shell(monkeypatch):
  401. calls = []
  402. def fake_run(args, **kwargs):
  403. calls.append((args, kwargs))
  404. return subprocess.CompletedProcess(args, 0, stdout="[]", stderr="")
  405. monkeypatch.setattr(gps.subprocess, "run", fake_run)
  406. assert gps.run_gh(["issue", "list", "--repo", "a/b; rm -rf x"]) == "[]"
  407. args, kwargs = calls[0]
  408. assert isinstance(args, list) and args[0] == "gh"
  409. assert not kwargs.get("shell")
  410. def test_a_gateway_error_is_retried_and_other_errors_are_not(monkeypatch):
  411. monkeypatch.setattr(gps.time, "sleep", lambda s: None)
  412. outcomes = iter(
  413. [
  414. subprocess.CompletedProcess([], 1, "", "HTTP 504: gateway"),
  415. subprocess.CompletedProcess([], 0, "ok", ""),
  416. ]
  417. )
  418. monkeypatch.setattr(gps.subprocess, "run", lambda *a, **k: next(outcomes))
  419. assert gps.run_gh(["x"]) == "ok"
  420. count = []
  421. def hard(*a, **k):
  422. count.append(1)
  423. return subprocess.CompletedProcess([], 1, "", "HTTP 401: bad credentials")
  424. monkeypatch.setattr(gps.subprocess, "run", hard)
  425. with pytest.raises(RuntimeError):
  426. gps.run_gh(["x"])
  427. assert len(count) == 1
  428. def test_board_nodes_are_reduced_to_the_fields_the_page_uses():
  429. nodes = [
  430. {
  431. "content": {"__typename": "Issue", "number": 5, "repository": {"nameWithOwner": REPO}},
  432. "fieldValues": {
  433. "nodes": [
  434. {"__typename": "ProjectV2ItemFieldSingleSelectValue", "name": "Next", "field": {"name": "Status"}},
  435. {"__typename": "ProjectV2ItemFieldIterationValue", "title": "S1", "field": {"name": "Sprint"}},
  436. {"__typename": "ProjectV2ItemFieldTextValue", "text": "Claude", "field": {"name": "Agent"}},
  437. {"__typename": "ProjectV2ItemFieldSingleSelectValue", "name": "P1", "field": {"name": "Priority"}},
  438. {"__typename": "ProjectV2ItemFieldRepositoryValue"},
  439. ]
  440. },
  441. },
  442. {"content": {"__typename": "DraftIssue"}, "fieldValues": {"nodes": []}},
  443. {"content": None, "fieldValues": {"nodes": []}},
  444. ]
  445. assert gps.parse_board_nodes(nodes) == [
  446. {"type": "Issue", "number": 5, "repo": REPO, "fields": {"Status": "Next", "Sprint": "S1", "Agent": "Claude"}}
  447. ]
  448. def test_refresh_writes_the_snapshot_and_the_page(tmp_path, monkeypatch):
  449. (tmp_path / "docs" / "wiki").mkdir(parents=True)
  450. fresh = snap([issue(1)], [pr(10, "Closes #1")], [item("Issue", 1, Status="Next")])
  451. monkeypatch.setattr(gps, "fetch_snapshot", lambda repo, owner, project: fresh)
  452. assert gps.main(["--refresh", "--root", str(tmp_path)]) == 0
  453. assert json.loads((tmp_path / gps.SNAPSHOT).read_text()) == fresh
  454. assert gps.check_page(tmp_path) == []
  455. def test_a_failed_refresh_leaves_the_files_alone(tmp_path, monkeypatch, capsys):
  456. root = make_root(tmp_path)
  457. run_script(root=root)
  458. before = (root / gps.PAGE).read_text(), (root / gps.SNAPSHOT).read_text()
  459. def boom(repo, owner, project):
  460. raise RuntimeError("no network")
  461. monkeypatch.setattr(gps, "fetch_snapshot", boom)
  462. assert gps.main(["--refresh", "--root", str(root)]) == 1
  463. assert ((root / gps.PAGE).read_text(), (root / gps.SNAPSHOT).read_text()) == before
  464. assert "refresh failed" in capsys.readouterr().err