forked from ShigureLab/gh-llm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
3211 lines (2868 loc) · 118 KB
/
Copy pathtest_cli.py
File metadata and controls
3211 lines (2868 loc) · 118 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import base64
import json
import math
import sys
from typing import TYPE_CHECKING, Any
from gh_llm import __version__, cli, github_api
from gh_llm.commands import pr as pr_commands
from gh_llm.models import ReviewThreadSummary
if TYPE_CHECKING:
from pathlib import Path
import pytest
class FakeCompletedProcess:
def __init__(self, stdout: str, returncode: int = 0, stderr: str = "") -> None:
self.stdout = stdout
self.returncode = returncode
self.stderr = stderr
class GhResponder:
def __init__(self) -> None:
self.calls: list[list[str]] = []
self.pending_review_id: str | None = None
def run(self, cmd: list[str], *, check: bool, capture_output: bool, text: bool) -> FakeCompletedProcess:
del check, capture_output, text
self.calls.append(cmd)
if cmd[:3] == ["gh", "pr", "view"]:
pr_number = self._extract_pr_number(cmd)
state = "OPEN"
changed_files = 1
if pr_number == 77827:
state = "CLOSED"
elif pr_number == 77960:
state = "MERGED"
elif pr_number == 78255:
changed_files = 3
merge_state_status = "CLEAN"
mergeable = "MERGEABLE"
if pr_number == 77971:
merge_state_status = "DIRTY"
mergeable = "CONFLICTING"
commits_payload: dict[str, Any] = {"nodes": []}
if pr_number == 77972:
commits_payload = {
"nodes": [
{
"messageHeadline": "Feature change",
"messageBody": "Improvements\n\nCo-authored-by: Alice Example <alice@example.com>",
},
{
"messageHeadline": "Follow-up",
"messageBody": "Co-authored-by: Bob Example <bob@example.com>",
},
]
}
return FakeCompletedProcess(
json.dumps(
{
"number": pr_number,
"title": "Timeline test",
"url": f"https://github.com/PaddlePaddle/Paddle/pull/{pr_number}",
"author": {"login": "ShigureNyako"},
"state": state,
"isDraft": False,
"body": "This is PR description",
"updatedAt": "2026-02-16T09:00:00Z",
"changedFiles": changed_files,
"mergeStateStatus": merge_state_status,
"mergeable": mergeable,
"commits": commits_payload,
"reactionGroups": [{"content": "ROCKET", "users": {"totalCount": 1}}],
}
)
)
if cmd[:3] == ["gh", "pr", "diff"]:
return FakeCompletedProcess(
"\n".join(
[
"diff --git a/python/test_file.py b/python/test_file.py",
"index 1111111..2222222 100644",
"--- a/python/test_file.py",
"+++ b/python/test_file.py",
"@@ -20,2 +20,2 @@ def demo():",
"-old_api_call()",
"+new_api_call()",
]
)
+ "\n"
)
if cmd[:3] == ["gh", "issue", "view"]:
return FakeCompletedProcess(
json.dumps(
{
"number": 77924,
"title": "Issue timeline test",
"url": "https://github.com/PaddlePaddle/Paddle/issues/77924",
"author": {"login": "ShigureNyako"},
"state": "OPEN",
"body": "This is issue description",
"updatedAt": "2026-02-16T09:00:00Z",
"reactionGroups": [{"content": "EYES", "users": {"totalCount": 1}}],
}
)
)
if cmd[:3] == ["gh", "api", "user"]:
return FakeCompletedProcess(json.dumps({"login": "ShigureNyako"}))
if cmd[:2] == ["gh", "api"] and len(cmd) >= 3 and "/pulls/" in cmd[2] and "/files?" in cmd[2]:
return FakeCompletedProcess(json.dumps(_pull_files_payload(cmd[2])))
if cmd[:2] == ["gh", "api"] and len(cmd) >= 3 and cmd[2].startswith("repos/") and "/contents" not in cmd[2]:
payload = _repository_api_payload(cmd[2])
if payload is None:
return FakeCompletedProcess("", returncode=1, stderr="HTTP 404: Not Found")
return FakeCompletedProcess(json.dumps(payload))
if cmd[:2] == ["gh", "api"] and len(cmd) >= 3 and "/contents" in cmd[2]:
payload = _repository_contents_payload(cmd[2])
if payload is None:
return FakeCompletedProcess("", returncode=1, stderr="HTTP 404: Not Found")
return FakeCompletedProcess(json.dumps(payload))
if cmd[:3] != ["gh", "api", "graphql"]:
return FakeCompletedProcess("", returncode=1, stderr="unexpected command")
query = _extract_form(cmd, "query")
first = _extract_field_int(cmd, "pageSize")
after = _extract_field(cmd, "after")
before = _extract_field(cmd, "before")
if "reviewThreads(first:100" in query:
payload = _review_threads_payload(after=after)
return FakeCompletedProcess(json.dumps(payload))
if "statusCheckRollup" in query:
return FakeCompletedProcess(json.dumps(_checks_payload()))
if "addPullRequestReviewThreadReply" in query:
return FakeCompletedProcess(
json.dumps({"data": {"addPullRequestReviewThreadReply": {"comment": {"id": "PRRC_reply_1"}}}})
)
if "addPullRequestReviewThread" in query:
self.pending_review_id = "PRR_pending_1"
return FakeCompletedProcess(
json.dumps(
{
"data": {
"addPullRequestReviewThread": {
"thread": {
"id": "PRRT_new_1",
"comments": {"nodes": [{"id": "PRRC_new_1"}]},
}
}
}
}
)
)
if "addPullRequestReview(input:" in query:
return FakeCompletedProcess(
json.dumps(
{
"data": {
"addPullRequestReview": {
"pullRequestReview": {
"id": "PRR_new_1",
"state": "PENDING",
}
}
}
}
)
)
if "reviews(last:50)" in query:
nodes: list[dict[str, Any]] = []
if self.pending_review_id is not None:
nodes.append(
{
"id": self.pending_review_id,
"state": "PENDING",
"author": {"login": "ShigureNyako"},
}
)
return FakeCompletedProcess(
json.dumps({"data": {"repository": {"pullRequest": {"reviews": {"nodes": nodes}}}}})
)
if "submitPullRequestReview(input:" in query:
review_id = self.pending_review_id or "PRR_pending_1"
self.pending_review_id = None
return FakeCompletedProcess(
json.dumps(
{
"data": {
"submitPullRequestReview": {
"pullRequestReview": {
"id": review_id,
"state": "COMMENTED",
}
}
}
}
)
)
if "pullRequest(number:$number){" in query and "id" in query and "timelineItems" not in query:
if "headRefName" in query and "headRepository" in query:
pr_number = _extract_field_int(cmd, "number")
repo_payload: dict[str, Any] = {
"mergeCommitAllowed": True,
"squashMergeAllowed": True,
"rebaseMergeAllowed": True,
}
if pr_number == 77827:
return FakeCompletedProcess(
json.dumps(
{
"data": {
"repository": {
**repo_payload,
"pullRequest": {
"id": "PR_kwDOA-qtos5closed",
"merged": False,
"headRefName": "feature/keep-branch",
"headRefOid": "1111111111111111111111111111111111111111",
"headRepository": {"nameWithOwner": "PaddlePaddle/Paddle"},
},
}
}
}
)
)
if pr_number == 77960:
return FakeCompletedProcess(
json.dumps(
{
"data": {
"repository": {
**repo_payload,
"pullRequest": {
"id": "PR_kwDOA-qtos5merged",
"merged": True,
"headRefName": "feature/deleted-branch",
"headRefOid": "2222222222222222222222222222222222222222",
"headRepository": {"nameWithOwner": "PaddlePaddle/Paddle"},
},
}
}
}
)
)
if pr_number == 77972:
repo_payload["rebaseMergeAllowed"] = False
return FakeCompletedProcess(
json.dumps(
{
"data": {
"repository": {
**repo_payload,
"pullRequest": {
"id": "PR_kwDOA-qtos5xxxx",
"merged": False,
"headRefName": "feature/open-branch",
"headRefOid": "3333333333333333333333333333333333333333",
"headRepository": {"nameWithOwner": "PaddlePaddle/Paddle"},
},
}
}
}
)
)
return FakeCompletedProcess(
json.dumps(
{
"data": {
"repository": {
"pullRequest": {
"id": "PR_kwDOA-qtos5xxxx",
}
}
}
}
)
)
if "node(id:$id)" in query and "PullRequestReviewComment" in query:
comment_id = _extract_field(cmd, "id")
if comment_id == "PRRC_self_1":
return FakeCompletedProcess(
json.dumps(
{
"data": {
"node": {
"__typename": "PullRequestReviewComment",
"id": "PRRC_self_1",
"createdAt": "2026-02-14T14:50:03Z",
"body": "self reply",
"outdated": True,
"isMinimized": False,
"minimizedReason": None,
"path": "python/test_file.py",
"line": 23,
"originalLine": 23,
"diffHunk": "@@ -23,1 +23,1 @@\n-old\n+new",
"author": {"login": "ShigureNyako"},
"reactionGroups": [],
"pullRequestReview": {"id": "PRR_mock"},
}
}
}
)
)
if comment_id == "c1":
return FakeCompletedProcess(
json.dumps(
{
"data": {
"node": {
"__typename": "IssueComment",
"id": "c1",
"createdAt": "2026-02-14T14:31:36Z",
"body": ("LONG_TEXT " * 220) + "END_MARKER",
"isMinimized": False,
"minimizedReason": None,
"author": {"login": "bot"},
"reactionGroups": [{"content": "THUMBS_UP", "users": {"totalCount": 2}}],
}
}
}
)
)
if comment_id == "ic1":
return FakeCompletedProcess(
json.dumps(
{
"data": {
"node": {
"__typename": "IssueComment",
"id": "ic1",
"createdAt": "2026-02-13T10:00:00Z",
"body": "ISSUE LONG BODY",
"isMinimized": True,
"minimizedReason": "OUTDATED",
"author": {"login": "bot"},
"reactionGroups": [{"content": "THUMBS_UP", "users": {"totalCount": 1}}],
}
}
}
)
)
return FakeCompletedProcess(json.dumps({"data": {"node": None}}))
if "ref(qualifiedName:$qualifiedName)" in query:
qualified = _extract_field(cmd, "qualifiedName")
if qualified == "refs/heads/feature/deleted-branch":
return FakeCompletedProcess(json.dumps({"data": {"repository": {"ref": None}}}))
return FakeCompletedProcess(json.dumps({"data": {"repository": {"ref": {"id": "REF_kwDOA-qtos5yyyy"}}}}))
if "updatePullRequestReviewComment" in query:
return FakeCompletedProcess(
json.dumps(
{"data": {"updatePullRequestReviewComment": {"pullRequestReviewComment": {"id": "PRRC_self_1"}}}}
)
)
if "updateIssueComment" in query:
return FakeCompletedProcess(json.dumps({"data": {"updateIssueComment": {"issueComment": {"id": "c3"}}}}))
if "unresolveReviewThread" in query:
return FakeCompletedProcess(
json.dumps({"data": {"unresolveReviewThread": {"thread": {"id": "PRRT_mock_2", "isResolved": False}}}})
)
if "resolveReviewThread" in query:
return FakeCompletedProcess(
json.dumps({"data": {"resolveReviewThread": {"thread": {"id": "PRRT_mock_1", "isResolved": True}}}})
)
if "timelineItems(first:" in query:
if "issue(number:$number)" in query:
payload = _issue_forward_page_payload(page_size=first, after=after)
return FakeCompletedProcess(json.dumps(payload))
payload = _forward_page_payload(page_size=first, after=after)
return FakeCompletedProcess(json.dumps(payload))
if "issue(number:$number)" in query:
payload = _issue_backward_page_payload(page_size=first, before=before)
return FakeCompletedProcess(json.dumps(payload))
payload = _backward_page_payload(page_size=first, before=before)
return FakeCompletedProcess(json.dumps(payload))
@staticmethod
def _extract_pr_number(cmd: list[str]) -> int:
for token in cmd[3:]:
if token.startswith("-"):
continue
if token.isdigit():
return int(token)
return 77928
def test_version() -> None:
assert __version__ == "0.1.11"
def test_parse_event_indexes_batch() -> None:
assert cli.parse_event_indexes(["5,11", "8-6"]) == [5, 6, 7, 8, 11]
def test_parse_review_ids_batch() -> None:
assert cli.parse_review_ids(["PRR_a,PRR_b", "PRR_b", "PRR_c"]) == ["PRR_a", "PRR_b", "PRR_c"]
def test_view_and_expand_use_real_cursor_pagination(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
code = cli.run(["pr", "view", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "## Description" in out
assert "This is PR description" in out
assert "Reactions: 🚀 x1" in out
assert "gh pr edit 77928 --repo PaddlePaddle/Paddle --body '<pr_description_markdown>'" in out
assert "Δ PR diff: `gh pr diff 77928 --repo PaddlePaddle/Paddle`" in out
assert "### Page 1/4" in out
assert "Reactions: 👍 x2" in out
assert "### Page 3/4" in out
assert "### Page 4/4" in out
assert "Hidden timeline page: 2" in out
assert "---" in out
assert "gh-llm pr timeline-expand 2 --pr 77928 --repo PaddlePaddle/Paddle" in out
assert "## Actions" in out
assert "## Checks" in out
assert "[IN_PROGRESS/NONE] unit-tests (check-run)" in out
assert "passed checks hidden." in out
assert "gh pr comment 77928 --repo PaddlePaddle/Paddle --body '<comment_body>'" in out
assert "gh pr close 77928 --repo PaddlePaddle/Paddle" in out
assert "gh pr edit 77928 --repo PaddlePaddle/Paddle --add-label '<label1>,<label2>'" in out
assert "gh pr edit 77928 --repo PaddlePaddle/Paddle --remove-label '<label1>,<label2>'" in out
assert "gh pr edit 77928 --repo PaddlePaddle/Paddle --add-reviewer '<reviewer1>,<reviewer2>'" in out
assert "gh pr edit 77928 --repo PaddlePaddle/Paddle --add-assignee '<assignee1>,<assignee2>'" in out
assert "link:" not in out
assert (
"Edit comment via gh-llm: `gh-llm pr comment-edit c3 --body '<comment_body>' --pr 77928 --repo PaddlePaddle/Paddle`"
in out
)
pre_expand_calls = len(responder.calls)
code = cli.run(["pr", "timeline-expand", "2", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "### Page 2/4" in out
assert "commit 2" in out
assert (
"Δ commit diff: `gh api repos/PaddlePaddle/Paddle/commits/oid-2 -H 'Accept: application/vnd.github.v3.diff'`"
in out
)
code = cli.run(["pr", "timeline-expand", "3", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "### Page 3/4" in out
assert "(review hidden: outdated)" in out
assert "Review comments (1/3 shown):" not in out
assert "Thread[1] PRRT_mock_1" not in out
assert "1 resolved review comments are collapsed;" not in out
assert "thread_id: PRRT_mock_1" not in out
assert "Reply via gh: `gh api graphql" not in out
assert "Resolve via gh: `gh api graphql" not in out
code = cli.run(
["pr", "review-expand", "PRR_mock", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"]
)
assert code == 0
out = capsys.readouterr().out
assert "## Timeline Event" in out
assert "lgtm" in out
assert "Review comments (3/3 shown):" in out
assert "PRRT_mock_1" in out
assert "The error message could be more helpful." in out
assert "Reactions: ❤️ x1" in out
assert "[outdated] python/test_file.py:L23" in out
assert "Suggested Change:" in out
assert "@@ python/test_file.py:L22 @@" in out
assert "+new_api_call()" in out
assert (
"Edit comment via gh-llm: `gh-llm pr comment-edit PRRC_self_1 --body '<comment_body>' --pr 77928 --repo PaddlePaddle/Paddle`"
in out
)
assert "Unresolve via gh-llm:" in out
code = cli.run(
[
"pr",
"review-expand",
"PRR_mock",
"--threads",
"1-1",
"--pr",
"77928",
"--repo",
"PaddlePaddle/Paddle",
"--page-size",
"2",
]
)
assert code == 0
out = capsys.readouterr().out
assert "## Review PRR_mock" in out
assert "Review comments (2/2 shown):" in out
assert "Thread[1] PRRT_mock_1" in out
assert "PRRT_mock_2" not in out
code = cli.run(["pr", "checks", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--all"])
assert code == 0
out = capsys.readouterr().out
assert "## Checks" in out
assert "[COMPLETED/SUCCESS] lint (check-run)" in out
assert "gh run view 101 --log --repo PaddlePaddle/Paddle" in out
assert "gh run view 202 --job 303 --log --repo PaddlePaddle/Paddle" in out
code = cli.run(
[
"pr",
"thread-reply",
"PRRT_mock_1",
"--body",
"please update",
"--pr",
"77928",
"--repo",
"PaddlePaddle/Paddle",
]
)
assert code == 0
out = capsys.readouterr().out
assert "thread: PRRT_mock_1" in out
assert "reply_comment_id: PRRC_reply_1" in out
assert "status: replied" in out
code = cli.run(
[
"pr",
"thread-resolve",
"PRRT_mock_1",
"--pr",
"77928",
"--repo",
"PaddlePaddle/Paddle",
]
)
assert code == 0
out = capsys.readouterr().out
assert "thread: PRRT_mock_1" in out
assert "status: resolved" in out
code = cli.run(
[
"pr",
"comment-edit",
"c3",
"--body",
"updated body",
"--pr",
"77928",
"--repo",
"PaddlePaddle/Paddle",
]
)
assert code == 0
out = capsys.readouterr().out
assert "comment: c3" in out
assert "status: edited" in out
code = cli.run(
[
"pr",
"thread-unresolve",
"PRRT_mock_2",
"--pr",
"77928",
"--repo",
"PaddlePaddle/Paddle",
]
)
assert code == 0
out = capsys.readouterr().out
assert "thread: PRRT_mock_2" in out
assert "status: unresolved" in out
expand_calls = responder.calls[pre_expand_calls:]
assert any(call[:3] == ["gh", "pr", "view"] for call in expand_calls)
assert any(call[:3] == ["gh", "api", "graphql"] for call in expand_calls)
code = cli.run(["pr", "comment-expand", "c1", "--pr", "77928", "--repo", "PaddlePaddle/Paddle"])
assert code == 0
out = capsys.readouterr().out
assert "## Comment c1" in out
assert "- Type: IssueComment" in out
assert "END_MARKER" in out
def test_pr_view_show_meta_skips_timeline_bootstrap(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
code = cli.run(["pr", "view", "77928", "--repo", "PaddlePaddle/Paddle", "--show", "meta"])
assert code == 0
out = capsys.readouterr().out
assert "pr: 77928" in out
assert "timeline_events:" not in out
assert "## Timeline" not in out
assert "## Checks" not in out
graphql_queries = [_extract_form(call, "query") for call in responder.calls if call[:3] == ["gh", "api", "graphql"]]
assert any("headRefName" in query and "timelineItems" not in query for query in graphql_queries)
assert not any("timelineItems(" in query for query in graphql_queries)
assert not any("reviewThreads(first:100" in query for query in graphql_queries)
assert not any("statusCheckRollup" in query for query in graphql_queries)
def test_pr_view_show_checks_fetches_checks_without_timeline_bootstrap(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
code = cli.run(["pr", "view", "77928", "--repo", "PaddlePaddle/Paddle", "--show", "checks"])
assert code == 0
out = capsys.readouterr().out
assert "## Checks" in out
assert "[IN_PROGRESS/NONE] unit-tests (check-run)" in out
assert "## Timeline" not in out
graphql_queries = [_extract_form(call, "query") for call in responder.calls if call[:3] == ["gh", "api", "graphql"]]
assert any("statusCheckRollup" in query for query in graphql_queries)
assert not any("timelineItems(" in query for query in graphql_queries)
assert not any("reviewThreads(first:100" in query for query in graphql_queries)
def test_pr_checks_command_skips_timeline_bootstrap(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
code = cli.run(["pr", "checks", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--all"])
assert code == 0
out = capsys.readouterr().out
assert "## Checks" in out
assert "[COMPLETED/SUCCESS] lint (check-run)" in out
graphql_queries = [_extract_form(call, "query") for call in responder.calls if call[:3] == ["gh", "api", "graphql"]]
assert any("statusCheckRollup" in query for query in graphql_queries)
assert not any("timelineItems(" in query for query in graphql_queries)
assert not any("reviewThreads(first:100" in query for query in graphql_queries)
def test_pr_view_show_mergeability_fetches_status_without_timeline_bootstrap(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
code = cli.run(["pr", "view", "77971", "--repo", "PaddlePaddle/Paddle", "--show", "mergeability"])
assert code == 0
out = capsys.readouterr().out
assert "## Mergeability" in out
assert "Status: Merging is blocked" in out
assert "## Timeline" not in out
graphql_queries = [_extract_form(call, "query") for call in responder.calls if call[:3] == ["gh", "api", "graphql"]]
assert any("statusCheckRollup" in query for query in graphql_queries)
assert not any("timelineItems(" in query for query in graphql_queries)
assert not any("reviewThreads(first:100" in query for query in graphql_queries)
def test_web_like_extra_timeline_events_are_rendered(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
monkeypatch.setattr(sys.modules[__name__], "_events", _events_with_web_like_extras)
code = cli.run(["pr", "timeline-expand", "4", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "reference" in out
assert 'PR #77887 "Test referenced PR" by @alice' in out
assert "gh-llm pr view 77887 --repo PaddlePaddle/Paddle" in out
code = cli.run(["pr", "timeline-expand", "5", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "cross-reference" in out
assert "cross-reference by @triager (Tri Ager)" in out
assert 'issue #12345 "Test issue" by @bob (Bob)' in out
assert "gh-llm issue view 12345 --repo PaddlePaddle/Paddle" in out
code = cli.run(["pr", "timeline-expand", "6", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "label/remove" in out
assert "push/force" in out
def test_title_renamed_event_is_rendered(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
monkeypatch.setattr(sys.modules[__name__], "_events", _events_with_web_like_extras)
code = cli.run(["pr", "timeline-expand", "7", "--pr", "77928", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "pr/title-edited" in out
assert "title changed" in out
assert "from: Old title" in out
assert "to: New title" in out
def test_issue_view_and_expand_use_real_cursor_pagination(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
code = cli.run(["issue", "view", "77924", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"])
assert code == 0
out = capsys.readouterr().out
assert "issue: 77924" in out
assert "## Description" in out
assert "This is issue description" in out
assert "Reactions: 👀 x1" in out
assert "gh issue edit 77924 --repo PaddlePaddle/Paddle --body '<issue_description_markdown>'" in out
assert "## Diff Actions" not in out
assert "### Page 1/3" in out
assert "### Page 2/3" in out
assert "### Page 3/3" in out
assert "Hidden timeline page" not in out
assert "(comment hidden: outdated)" in out
assert "run `gh-llm issue comment-expand ic1 --issue 77924 --repo PaddlePaddle/Paddle` for full comment" in out
assert "## Actions" in out
assert "gh issue comment 77924 --repo PaddlePaddle/Paddle --body '<comment_body>'" in out
assert "gh issue close 77924 --repo PaddlePaddle/Paddle" in out
assert "gh issue edit 77924 --repo PaddlePaddle/Paddle --add-label '<label1>,<label2>'" in out
assert "gh issue edit 77924 --repo PaddlePaddle/Paddle --remove-label '<label1>,<label2>'" in out
assert "gh issue edit 77924 --repo PaddlePaddle/Paddle --add-assignee '<assignee1>,<assignee2>'" in out
assert (
"Edit comment via gh-llm: `gh-llm issue comment-edit ic2 --body '<comment_body>' --issue 77924 --repo PaddlePaddle/Paddle`"
in out
)
assert "cross-reference by @alice (Alice)" in out
assert "gh-llm pr view 77900 --repo PaddlePaddle/Paddle" in out
assert "issue/closed by @ShigureNyako" in out
assert "issue/marked-as-duplicate by @SigureMo (Nyakku Shigure)" in out
assert (
'marked issue #77925 "Duplicate issue" by @alice (Alice) (PaddlePaddle/Paddle) as duplicate of this issue'
in out
)
assert "gh-llm issue view 77925 --repo PaddlePaddle/Paddle" in out
code = cli.run(
["issue", "timeline-expand", "2", "--issue", "77924", "--repo", "PaddlePaddle/Paddle", "--page-size", "2"]
)
assert code == 0
out = capsys.readouterr().out
assert "### Page 2/3" in out
code = cli.run(["issue", "comment-expand", "ic1", "--issue", "77924", "--repo", "PaddlePaddle/Paddle"])
assert code == 0
out = capsys.readouterr().out
assert "## Comment ic1" in out
assert "- Type: IssueComment" in out
def test_extract_diff_hunks_prefers_first_added_line_for_right_side() -> None:
diff = "\n".join(
[
"diff --git a/paddle/phi/kernels/funcs/abs.h b/paddle/phi/kernels/funcs/abs.h",
"index 1111111..2222222 100644",
"--- a/paddle/phi/kernels/funcs/abs.h",
"+++ b/paddle/phi/kernels/funcs/abs.h",
"@@ -22,6 +22,12 @@",
' #include "paddle/phi/common/amp_type_traits.h"',
' #include "paddle/phi/core/dense_tensor.h"',
'+#include "paddle/phi/core/kernel_utils.h"',
'+#include "paddle/phi/core/tensor_utils.h"',
" template <typename T, typename Context>",
"+inline void CheckInput(const DenseTensor& x) {}",
]
)
hunks = pr_commands._extract_diff_hunks(diff) # pyright: ignore[reportPrivateUsage]
assert len(hunks) == 1
assert hunks[0].path == "paddle/phi/kernels/funcs/abs.h"
assert hunks[0].anchor_line == 24
def test_extract_diff_hunks_uses_real_new_file_line_numbers_on_right_side() -> None:
diff = "\n".join(
[
"diff --git a/src/gh_llm/commands/pr.py b/src/gh_llm/commands/pr.py",
"index 1111111..2222222 100644",
"--- a/src/gh_llm/commands/pr.py",
"+++ b/src/gh_llm/commands/pr.py",
"@@ -642,7 +642,7 @@ def cmd_pr_review_start(args: Any) -> int:",
'- print(f"Suggested anchor line (RIGHT): {hunk.anchor_line}")',
'+ print(f"Suggested anchor line (RIGHT, first added line when available): {hunk.anchor_line}")',
" comment_cmd = display_command_with(",
" f\"pr review-comment --path '{hunk.path}' --line {hunk.anchor_line} --side RIGHT --body '<review_comment>' --pr {meta.ref.number} --repo {repo}\"",
" )",
" suggest_cmd = display_command_with(",
" f\"pr review-suggest --path '{hunk.path}' --line {hunk.anchor_line} --side RIGHT --body '<reason>' --suggestion '<replacement>' --pr {meta.ref.number} --repo {repo}\"",
" )",
]
)
hunks = pr_commands._extract_diff_hunks(diff) # pyright: ignore[reportPrivateUsage]
assert len(hunks) == 1
assert hunks[0].path == "src/gh_llm/commands/pr.py"
assert hunks[0].anchor_line == 642
assert 642 in hunks[0].right_commentable_lines
assert min(hunks[0].right_commentable_lines) == 642
def test_render_numbered_hunk_lines_preserves_real_right_side_line_numbers() -> None:
hunk = pr_commands._DiffHunk( # pyright: ignore[reportPrivateUsage]
path="src/gh_llm/commands/pr.py",
header="@@ -890,6 +890,7 @@ def _extract_diff_hunks(diff: str) -> list[_DiffHunk]:",
anchor_line=893,
lines=[
"@@ -890,6 +890,7 @@ def _extract_diff_hunks(diff: str) -> list[_DiffHunk]:",
" current_hunk_lines: list[str] = []",
" current_old_line = 0",
" current_new_line = 0",
"+ current_right_display_line = 0",
" current_anchor = 0",
" current_fallback_anchor = 0",
" current_left_commentable_lines: set[int] = set()",
],
left_commentable_lines={890, 891, 892, 893, 894, 895},
right_commentable_lines={890, 891, 892, 893, 894, 895, 896},
match_paths={"src/gh_llm/commands/pr.py"},
)
rendered = pr_commands._render_numbered_hunk_lines(hunk) # pyright: ignore[reportPrivateUsage]
assert "L 890 R 890 | current_hunk_lines: list[str] = []" in rendered
assert "L 891 R 891 | current_old_line = 0" in rendered
assert "L 892 R 892 | current_new_line = 0" in rendered
assert "L R 893 | + current_right_display_line = 0" in rendered
def test_inline_review_thread_blocks_do_not_fallback_from_current_right_anchor_to_original_left_line() -> None:
current_hunk = pr_commands._DiffHunk( # pyright: ignore[reportPrivateUsage]
path="paddle/phi/api/include/compat/ATen/ops/from_blob.h",
header="@@ -18,3 +80,4 @@",
anchor_line=81,
lines=[
"@@ -18,3 +80,4 @@",
" context_before()",
'+ PD_CHECK(storage_offset_.value() == 0, "storage_offset` should be zero.");',
" context_after()",
],
left_commentable_lines={18, 19},
right_commentable_lines={80, 81, 82},
match_paths={"paddle/phi/api/include/compat/ATen/ops/from_blob.h"},
)
stale_hunk = pr_commands._DiffHunk( # pyright: ignore[reportPrivateUsage]
path="paddle/phi/api/include/compat/ATen/ops/from_blob.h",
header="@@ -80,4 +210,1 @@",
anchor_line=210,
lines=[
"@@ -80,4 +210,1 @@",
"- sizes._PD_ToPaddleIntArray(),",
"- compat::_PD_AtenScalarTypeToPhiDataType(options.dtype()),",
"- phi::DataLayout::NCHW,",
"- options._PD_GetPlace());",
"+ return for_blob(data, sizes).options(options).make_tensor();",
],
left_commentable_lines={80, 81, 82, 83},
right_commentable_lines={210},
match_paths={"paddle/phi/api/include/compat/ATen/ops/from_blob.h"},
)
summary = ReviewThreadSummary(
thread_id="PRRT_mock_current",
path="paddle/phi/api/include/compat/ATen/ops/from_blob.h",
is_resolved=False,
comment_count=1,
is_outdated=False,
anchor_side="RIGHT",
anchor_line=81,
right_lines=(81,),
left_lines=(81,),
display_ref="R81",
comments=(),
)
blocks_by_hunk = pr_commands._build_inline_review_thread_blocks_for_file( # pyright: ignore[reportPrivateUsage]
hunks=[current_hunk, stale_hunk],
summaries=[summary],
extra_contexts=[None, None],
)
assert ("RIGHT", 81) in blocks_by_hunk[0]
assert "💬 thread PRRT_mock_current at R81 (1 comment)" in blocks_by_hunk[0][("RIGHT", 81)]
assert blocks_by_hunk[1] == {}
def test_pr_review_actions_for_llm_flow(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
responder = GhResponder()
monkeypatch.setattr(github_api.subprocess, "run", responder.run)
code = cli.run(["pr", "review-start", "--pr", "77928", "--repo", "PaddlePaddle/Paddle"])
assert code == 0
out = capsys.readouterr().out
assert "## Review Start" in out
assert "Head snapshot: 3333333333333333333333333333333333333333" in out
assert "Files changed: 1" in out
assert "File page: 1/1 (1-1 of 1)" in out
assert "Hunks on this page: 1" in out
assert "gh pr diff 77928 --repo PaddlePaddle/Paddle" in out
assert (
"gh-llm pr review-comment --path '<path>' --line <line> --side RIGHT --body '<review_comment>' --head 3333333333333333333333333333333333333333 --pr 77928 --repo PaddlePaddle/Paddle"
in out
)
assert (
"gh-llm pr review-suggest --path '<path>' --line <line> --side RIGHT --body '<reason>' --suggestion '<replacement>' --head 3333333333333333333333333333333333333333 --pr 77928 --repo PaddlePaddle/Paddle"
in out
)
assert (
"gh-llm pr review-comment --path '<path>' --start-line <start_line> --line <line> --side RIGHT --body '<review_comment>' --head 3333333333333333333333333333333333333333 --pr 77928 --repo PaddlePaddle/Paddle"
in out
)
assert "gh-llm pr thread-expand <thread_id> --pr 77928 --repo PaddlePaddle/Paddle" in out
assert "### File 1/1: python/test_file.py" in out
assert "Status: modified (+1 -1, 2 changes)" in out
assert "Existing review threads in this file: 2 (1 active, 1 resolved)" in out
assert "LEFT commentable span(s): 20" in out
assert "RIGHT commentable span(s): 20" in out
assert "Related review threads in this hunk:" not in out
assert "Use the L#### / R#### labels from the numbered diff below as --line values." in out
assert "For a continuous multi-line range on the same side, add --start-line <start_line>." in out
assert "@@ -20,2 +20,2 @@ def demo():" in out
assert "L 20 R | -old_api_call()" in out
assert "L R 20 | +new_api_call()" in out
assert "Suggested anchor line" not in out
code = cli.run(
[
"pr",
"review-comment",
"--path",
"python/test_file.py",
"--line",