main
1import io
2import json
3import os
4import tempfile
5import unittest
6from contextlib import redirect_stdout
7from pathlib import Path
8from unittest.mock import MagicMock, patch
9
10import pr
11
12
13def node(number, title, ci_state=None, draft=False, repo="owner/repo"):
14 rollup = {"state": ci_state} if ci_state else None
15 return {
16 "number": number,
17 "title": title,
18 "url": f"https://github.com/{repo}/pull/{number}",
19 "isDraft": draft,
20 "repository": {"nameWithOwner": repo},
21 "author": {"login": "alice"},
22 "commits": {"nodes": [{"commit": {"statusCheckRollup": rollup}}]},
23 }
24
25
26PULLS = [node(1, "Fix login", "FAILURE"), node(2, "Add docs", draft=True)]
27
28
29def check_run(name, status, conclusion=None, workflow=None):
30 run = {"workflowRun": {"workflow": {"name": workflow}}} if workflow else None
31 return {
32 "__typename": "CheckRun",
33 "name": name,
34 "status": status,
35 "conclusion": conclusion,
36 "checkSuite": run,
37 }
38
39
40VIEW = {
41 "number": 7,
42 "title": "Add feature",
43 "url": "https://github.com/owner/repo/pull/7",
44 "state": "OPEN",
45 "isDraft": False,
46 "author": {"login": "alice"},
47 "repository": {"nameWithOwner": "owner/repo"},
48 "headRefName": "feature",
49 "baseRefName": "main",
50 "reviewDecision": "APPROVED",
51 "mergeable": "MERGEABLE",
52 "mergeStateStatus": "CLEAN",
53 "autoMergeRequest": {"mergeMethod": "SQUASH", "enabledBy": {"login": "bob"}},
54 "milestone": {"title": "v1.0"},
55 "assignees": {"nodes": [{"login": "alice"}]},
56 "labels": {"nodes": [{"name": "bug"}]},
57 "reviewRequests": {"nodes": [{"requestedReviewer": {"name": "core"}}]},
58 "latestReviews": {
59 "nodes": [
60 {"author": {"login": "bob"}, "state": "APPROVED"},
61 {"author": {"login": "carol"}, "state": "CHANGES_REQUESTED"},
62 ]
63 },
64 "reviewThreads": {"nodes": [{"isResolved": False}, {"isResolved": True}]},
65 "comments": {
66 "nodes": [
67 {
68 "author": {"login": "bob"},
69 "createdAt": "2026-01-01T00:00:00Z",
70 "body": "first",
71 },
72 {
73 "author": {"__typename": "Bot", "login": "codecov"},
74 "createdAt": "2026-01-01T01:00:00Z",
75 "body": "coverage",
76 },
77 {
78 "author": {"login": "ci-robot"},
79 "createdAt": "2026-01-01T01:30:00Z",
80 "body": "/approve",
81 },
82 {
83 "author": {"login": "carol"},
84 "createdAt": "2026-01-01T02:00:00Z",
85 "body": "second",
86 },
87 ]
88 },
89 "closingIssuesReferences": {
90 "nodes": [
91 {
92 "number": 3,
93 "title": "Broken",
94 "state": "OPEN",
95 "repository": {"nameWithOwner": "owner/repo"},
96 },
97 {
98 "number": 9,
99 "title": "Upstream",
100 "state": "CLOSED",
101 "repository": {"nameWithOwner": "other/lib"},
102 },
103 ]
104 },
105 "additions": 10,
106 "deletions": 2,
107 "changedFiles": 3,
108 "files": {
109 "totalCount": 3,
110 "nodes": [
111 {"path": "a.py", "additions": 8, "deletions": 0, "changeType": "ADDED"},
112 {"path": "b.py", "additions": 2, "deletions": 2, "changeType": "MODIFIED"},
113 ],
114 },
115 "createdAt": "2026-01-01T00:00:00Z",
116 "updatedAt": "2026-01-02T00:00:00Z",
117 "body": "Intro\r\n<!-- template hint -->\n\n\n\nDetails",
118 "commits": {
119 "totalCount": 2,
120 "nodes": [
121 {
122 "commit": {
123 "messageHeadline": "Add feature",
124 "statusCheckRollup": {
125 "contexts": {
126 "nodes": [
127 check_run("lint", "COMPLETED", "SUCCESS"),
128 check_run("e2e", "IN_PROGRESS", workflow="CI"),
129 {
130 "__typename": "StatusContext",
131 "context": "ci/legacy",
132 "state": "FAILURE",
133 },
134 ]
135 }
136 },
137 }
138 }
139 ],
140 },
141}
142
143
144class ParseQueryTests(unittest.TestCase):
145 def test_targets(self):
146 cases = {
147 "": ("myprs", ""),
148 "myprs fix": ("myprs", "fix"),
149 "review": ("review", ""),
150 "involved docs": ("involved", "docs"),
151 "raffi docs": ("myprs", "raffi docs"),
152 "owner/repo fix login": ("owner/repo", "fix login"),
153 "linoux fix": ("linus/linux", "fix"),
154 }
155 with patch.dict(os.environ, {"ALIAS_linoux": "linus/linux"}):
156 for query, expected in cases.items():
157 with self.subTest(query=query):
158 self.assertEqual(pr.parse_query(query), expected)
159
160 def test_repo_argument_makes_whole_query_a_filter(self):
161 self.assertEqual(
162 pr.parse_query(" a/b c ", "owner/repo"), ("owner/repo", "a/b c")
163 )
164
165
166class ListItemsTests(unittest.TestCase):
167 def list(self, query, response):
168 with patch.object(pr, "run_gh", return_value={"data": response}) as run_gh:
169 return pr.list_items(query), run_gh
170
171 def test_repository_pulls_are_filtered(self):
172 response = {"repository": {"pullRequests": {"nodes": PULLS}}}
173 items, run_gh = self.list("owner/repo failed", response)
174
175 self.assertIn("owner=owner", run_gh.call_args.args)
176 self.assertEqual(items[0]["arg"], "https://github.com/owner/repo/pulls")
177 self.assertEqual(
178 [item["title"] for item in items[1:]], ["PR #1: Fix login - alice"]
179 )
180 self.assertTrue(all("indent" not in item for item in items[1:]))
181 self.assertIn("\x1b[31mCI: Failed\x1b[0m \u00b7 Open", items[1]["subtitle"])
182 self.assertEqual(
183 items[1]["variables"],
184 {
185 "PR_URL": "https://github.com/owner/repo/pull/1",
186 "PR_REPO": "owner/repo",
187 "PR_NUMBER": "1",
188 "PR_BRANCH": "",
189 },
190 )
191
192 def test_own_pulls_show_repository_and_draft(self):
193 items, _ = self.list("docs", {"search": {"nodes": [*PULLS, {}]}})
194
195 self.assertEqual(items[0]["arg"], "https://github.com/pulls")
196 self.assertEqual(items[1]["title"], "PR #2: Add docs - owner/repo")
197 self.assertTrue(items[1]["subtitle"].startswith("Draft"))
198
199 def test_cross_repository_modes_group_pulls_by_owner(self):
200 pulls = [
201 node(1, "First", repo="alice/one"),
202 node(2, "Second", repo="org-b/two"),
203 node(3, "Third", repo="alice/three"),
204 ]
205 response = {"search": {"nodes": pulls}}
206 expected = [
207 ("alice", 0, False),
208 ("PR #1: First - alice/one", 1, None),
209 ("PR #3: Third - alice/three", 1, None),
210 ("org-b", 0, False),
211 ("PR #2: Second - org-b/two", 1, None),
212 ]
213
214 for mode in ("myprs", "review", "assigned", "involved"):
215 with self.subTest(mode=mode):
216 items, _ = self.list(mode, response)
217 self.assertEqual(
218 [
219 (item["title"], item.get("indent"), item.get("valid"))
220 for item in items[1:]
221 ],
222 expected,
223 )
224
225 def test_single_owner_cross_repository_results_stay_flat(self):
226 pulls = [
227 node(1, "First", repo="org/one"),
228 node(2, "Second", repo="org/two"),
229 ]
230 items, _ = self.list("myprs", {"search": {"nodes": pulls}})
231
232 self.assertEqual(
233 [item["title"] for item in items[1:]],
234 ["PR #1: First - org/one", "PR #2: Second - org/two"],
235 )
236 self.assertTrue(all("indent" not in item for item in items[1:]))
237
238 def test_filtering_precedes_owner_grouping(self):
239 pulls = [
240 node(1, "Needle one", repo="alice/one"),
241 node(2, "Other", repo="alice/two"),
242 node(3, "Needle three", repo="org-b/three"),
243 node(4, "Other", repo="org-c/four"),
244 ]
245 items, _ = self.list("myprs needle", {"search": {"nodes": pulls}})
246
247 self.assertEqual(
248 [
249 (item["title"], item.get("indent"), item.get("valid"))
250 for item in items[1:]
251 ],
252 [
253 ("alice", 0, False),
254 ("PR #1: Needle one - alice/one", 1, None),
255 ("org-b", 0, False),
256 ("PR #3: Needle three - org-b/three", 1, None),
257 ],
258 )
259
260 def test_modes_search_their_own_pull_requests(self):
261 items, run_gh = self.list("review", {"search": {"nodes": PULLS}})
262
263 self.assertIn("q=is:pr is:open review-requested:@me", run_gh.call_args.args)
264 self.assertEqual(items[0]["arg"], "https://github.com/pulls/review-requested")
265
266 def test_subtitle_shows_review_conflicts_threads_and_size(self):
267 pull = dict(
268 PULLS[0],
269 reviewDecision="CHANGES_REQUESTED",
270 mergeable="CONFLICTING",
271 reviewThreads={"nodes": [{"isResolved": False}]},
272 additions=5,
273 deletions=1,
274 )
275 subtitle = pr.ANSI.sub("", pr.build_item(pull, False)["subtitle"])
276
277 self.assertIn(
278 "Changes requested \u00b7 Conflicts \u00b7 \U0001f4ac 1 unresolved \u00b7 +5 -1",
279 subtitle,
280 )
281
282 def test_errors_become_items(self):
283 self.assertEqual(pr.list_items("owner/")[0]["title"], "Invalid repository")
284 with patch.object(pr, "run_gh", side_effect=pr.GhError("boom")):
285 self.assertEqual(pr.list_items("")[0]["subtitle"], "boom")
286
287
288class PreviewTests(unittest.TestCase):
289 def test_build_preview(self):
290 preview = pr.build_preview(VIEW)
291
292 self.assertEqual(preview["title"], "#7 Add feature")
293 self.assertEqual(preview["badge"], "Open")
294 metadata = dict(preview["metadata"])
295 self.assertEqual(metadata["Review"], "Approved")
296 self.assertEqual(metadata["Reviewers"], "\u2713 bob, \u2717 carol, \u23f3 core")
297 self.assertEqual(metadata["Merge"], "Ready, auto-merge (squash) by bob")
298 self.assertEqual(metadata["Threads"], "1 unresolved")
299 self.assertEqual(metadata["Commits"], "2 commits, last: Add feature")
300 self.assertEqual(metadata["Milestone"], "v1.0")
301 self.assertEqual(metadata["Changes"], "+10 -2 in 3 files")
302 checks, closes, description, *comments, files = preview["sections"]
303 self.assertEqual(checks["heading"], "Checks: 1 failed, 1 pending, 1 passed")
304 self.assertEqual(
305 pr.ANSI.sub("", checks["content"]).splitlines(),
306 ["\uf057 ci/legacy", "\uf017 CI / e2e", "\uf058 lint"],
307 )
308 self.assertEqual(
309 pr.ANSI.sub("", closes["content"]).splitlines(),
310 ["#3 [open] Broken", "other/lib#9 [closed] Upstream"],
311 )
312 self.assertEqual(description["content"], "Intro\n\nDetails")
313 self.assertEqual(
314 [c["content"] for c in comments], ["second", "first"], "bots skipped"
315 )
316 self.assertEqual(files["heading"], "Files (3)")
317 self.assertEqual(
318 pr.ANSI.sub("", files["content"]).splitlines(),
319 ["A a.py +8 -0", "M b.py +2 -2", "\u2026 and 1 more"],
320 )
321 self.assertEqual(preview["refresh"], pr.PREVIEW_REFRESH_SECONDS)
322
323 def test_merged_and_conflicting_states(self):
324 merged = dict(VIEW, state="MERGED", mergedAt=None)
325 conflicting = dict(VIEW, mergeable="CONFLICTING", autoMergeRequest=None)
326
327 self.assertEqual(pr.merge_state(merged), "Merged")
328 self.assertEqual(pr.merge_state(conflicting), "Conflicts")
329
330 def test_no_refresh_once_checks_are_done(self):
331 commit = VIEW["commits"]["nodes"][0]["commit"]
332 lint = commit["statusCheckRollup"]["contexts"]["nodes"][:1]
333 rollup = {"contexts": {"nodes": lint}}
334 commits = {
335 "totalCount": 1,
336 "nodes": [{"commit": dict(commit, statusCheckRollup=rollup)}],
337 }
338 done = dict(VIEW, isDraft=True, body="", commits=commits)
339 preview = pr.build_preview(done)
340
341 self.assertEqual(preview["badge"], "Draft")
342 self.assertEqual(preview["sections"][2]["content"], "(no description)")
343 self.assertNotIn("refresh", preview)
344
345 def test_main_prints_preview_when_raffi_asks(self):
346 stdout = io.StringIO()
347 env = {"RAFFI_PREVIEW": "1", "RAFFI_VALUE": VIEW["url"]}
348 with (
349 patch.dict(os.environ, env),
350 patch.object(
351 pr,
352 "run_gh",
353 return_value={"data": {"repository": {"pullRequest": VIEW}}},
354 ) as run_gh,
355 redirect_stdout(stdout),
356 ):
357 self.assertEqual(pr.main(["--repo", "owner/repo", "query"]), 0)
358
359 args = run_gh.call_args.args
360 self.assertEqual(args[:2], ("api", "graphql"))
361 self.assertIn("number=7", args)
362 self.assertNotIn("--cache", args)
363 self.assertEqual(json.loads(stdout.getvalue())["title"], "#7 Add feature")
364
365 def test_preview_error_is_shown_in_the_pane(self):
366 with patch.object(pr, "run_gh", side_effect=pr.GhError("offline")):
367 preview = pr.preview(VIEW["url"])
368
369 self.assertIn("offline", preview["text"])
370 self.assertEqual(pr.preview("nope")["text"], "Not a pull request URL.")
371 missing = {"data": {"repository": {"pullRequest": None}}}
372 with patch.object(pr, "run_gh", return_value=missing):
373 self.assertIn("not found", pr.preview(VIEW["url"])["text"])
374
375
376class MarkdownTests(unittest.TestCase):
377 def test_markdown_is_rendered_with_ansi(self):
378 body = """\
379## Summary
380- [x] done
381 - [ ] todo
382* **bold** `a*b*` _em_ snake_case [link](https://x) 
383> [!NOTE]
384> quoted
385<details><summary>More</summary>
386```
387**raw**
388```
389| a | b |
390|---|:-:|
391***"""
392 rendered = pr.render_markdown(body)
393
394 self.assertIn("\x1b[1;35mSummary", rendered)
395 self.assertIn("\x1b[1mbold\x1b[22m", rendered)
396 self.assertIn("\x1b[4;34mlink\x1b[24;39m", rendered)
397 self.assertEqual(
398 pr.ANSI.sub("", rendered).splitlines(),
399 [
400 "Summary",
401 "\u2611 done",
402 " \u2610 todo",
403 "\u2022 bold a*b* em snake_case link [image: shot]",
404 "\u2502 Note",
405 "\u2502 quoted",
406 "More",
407 " **raw**",
408 "| a | b |",
409 "\u2500" * 40,
410 ],
411 )
412
413
414class AvatarTests(unittest.TestCase):
415 def test_owner_avatar_is_cached_as_round_svg(self):
416 response = MagicMock()
417 response.__enter__.return_value = response
418 response.headers.get_content_type.return_value = "image/jpeg"
419 response.read.return_value = b"JPEG"
420 repository = {"owner": {"login": "octo", "avatarUrl": "https://avatars/u/1"}}
421
422 with (
423 tempfile.TemporaryDirectory() as tmp,
424 patch.object(pr, "AVATAR_DIR", Path(tmp)),
425 patch.object(
426 pr.urllib.request, "urlopen", return_value=response
427 ) as urlopen,
428 ):
429 path = pr.account_icon(repository["owner"])
430 self.assertEqual(pr.account_icon(repository["owner"]), path)
431 self.assertEqual(path, f"{tmp}/octo.svg")
432 svg = Path(path).read_text()
433 preview = pr.build_preview(
434 dict(VIEW, repository={"nameWithOwner": "octo/r"})
435 )
436
437 urlopen.assert_called_once()
438 self.assertIn("data:image/jpeg;base64,SlBFRw==", svg)
439 self.assertEqual(preview["icon"], path)
440
441 def test_no_avatar_falls_back_to_github_icon(self):
442 with patch.object(pr.urllib.request, "urlopen", side_effect=OSError("offline")):
443 self.assertIsNone(pr.account_icon({"login": "x", "avatarUrl": "u"}))
444 self.assertIsNone(pr.account_icon(None))
445
446 def test_single_repository_rows_show_author_avatars(self):
447 def pull(number, repo, author):
448 return dict(
449 node(number, "Fix", repo=repo),
450 author={"login": author, "avatarUrl": f"https://avatars/{author}"},
451 repository={
452 "nameWithOwner": repo,
453 "owner": {
454 "login": repo.split("/")[0],
455 "avatarUrl": "https://avatars/owner",
456 },
457 },
458 )
459
460 def icons(query, nodes, response_key):
461 response = (
462 {"search": {"nodes": nodes}}
463 if response_key == "search"
464 else {"repository": {"pullRequests": {"nodes": nodes}}}
465 )
466 with (
467 patch.object(pr, "run_gh", return_value={"data": response}),
468 patch.object(
469 pr, "account_icon", side_effect=lambda a: f"/{a['login']}.svg"
470 ),
471 ):
472 items = pr.list_items(query)
473 return [item["icon"]["path"] for item in items if "icon" in item]
474
475 same_repo = [pull(1, "org/one", "alice"), pull(2, "org/one", "bob")]
476 self.assertEqual(
477 icons("org/one", same_repo, "repository"), ["/alice.svg", "/bob.svg"]
478 )
479 self.assertEqual(
480 icons("review", same_repo, "search"), ["/alice.svg", "/bob.svg"]
481 )
482 mixed = [pull(1, "org/one", "alice"), pull(2, "org/two", "bob")]
483 self.assertEqual(icons("review", mixed, "search"), ["/org.svg", "/org.svg"])
484
485
486if __name__ == "__main__":
487 unittest.main()