Repository navigation
Expand file tree
/
Copy pathtest_pr_review.py
More file actions
executable file
·8323 lines (7384 loc) · 416 KB
/
Copy pathtest_pr_review.py
File metadata and controls
executable file
·8323 lines (7384 loc) · 416 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
#!/usr/bin/env python3
"""Drive pr_review's digest and wait loop against responses they must read correctly.
The script exists to collapse a poll cycle into one invocation. Its failure mode is therefore a wrong
answer rather than a crash:
- a review attributed to the wrong login
- a review counted against a stale head
- a wait that returns success while nothing landed
Each case below feeds a crafted
GraphQL payload and asserts the reading, with `gql` replaced so no case reaches the network.
Run under `uv run --no-project --with-requirements tests/requirements.txt`, as
`python tests/test_pr_review.py` or `python -m unittest discover -s tests`.
"""
from __future__ import annotations
import argparse
import ast
import contextlib
import inspect
import io
import itertools
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
from collections.abc import Iterator
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import ClassVar
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
import pr_review
import pr_review_answers
import pr_review_check_lines
import pr_review_checks
import pr_review_rounds
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "spec"))
from git_env import without_git_location
from import_probe import import_delta
DEFAULT_POLICY = pr_review.review_policy.load_default()
_POLICY_PATCH = mock.patch.object(
pr_review.review_policy, "policy_for", return_value=pr_review.review_policy.load_default()
)
def setUpModule() -> None:
"""Have every case read the hub default policy unless it patches its own.
So no case reaches for a contents API read it never staged. The default states the behavior
the gate had before policies.
"""
_POLICY_PATCH.start()
def tearDownModule() -> None:
_POLICY_PATCH.stop()
REPO = Path(__file__).resolve().parent.parent
# The gate and the reader modules it imports, which every whole-source guard below reads together.
GATE_SOURCES = (
"pr_review.py",
"pr_review_checks.py",
"pr_review_check_lines.py",
"pr_review_rounds.py",
"pr_review_digest.py",
"pr_review_answers.py",
"pr_review_payload.py",
)
WRITE_SCANNED = (*GATE_SOURCES, "pr_review_side.py", "pr_review_policy.py")
# What a reader may import: the stdlib it parses with, the reviewer adapter, and the other readers.
READER_IMPORTS = frozenset(
{
"__future__",
"collections",
"datetime",
"hashlib",
"re",
"typing",
"pr_review_answers",
"pr_review_copilot",
"pr_review_checks",
"pr_review_check_lines",
"pr_review_payload",
"pr_review_rounds",
}
)
# One import each reader module is known to make, the floor under the allowlist above.
READER_FLOORS = {
"pr_review_checks": "datetime",
"pr_review_check_lines": "pr_review_checks",
"pr_review_rounds": "pr_review_copilot",
"pr_review_digest": "pr_review_answers",
"pr_review_answers": "pr_review_rounds",
"pr_review_payload": "typing",
}
# What a reader must never load, directly or through the adapter.
REACHING_OUT = ("pr_review", "gh_graphql", "subprocess")
RUNBOOK = REPO / ".github" / "copilot-instructions.md"
GOVERNANCE = REPO / "GOVERNANCE.md"
CODE_REVIEW_SKILL = REPO / ".github" / "skills" / "fleet-code-review" / "SKILL.md"
REVIEWER_REFERENCE = REPO / "docs" / "pr-reviewer-reference.md"
def flowed_text(text: str) -> str:
"""Collapse every whitespace run in `text` to one space, stripping the ends.
A hard-wrapped body rewraps when a word is added earlier in the paragraph. A sentence
pinned against its raw text therefore fails on an edit making no claim about it. Collapsing pins the
words rather than the line breaks. An assertion whose subject is the layout itself reads
raw instead, since collapsing would let a differently wrapped or indented line match.
"""
return " ".join(text.split())
def comment_flowed_text(text: str) -> str:
"""Strip each line's leading `#` marker, then collapse as `flowed_text` does.
A `#` comment that rewraps gains a marker on its new line as well as a newline.
Collapsing whitespace alone therefore leaves the marker between two words of a pinned phrase.
"""
return flowed_text(" ".join(line.lstrip().removeprefix("#") for line in text.splitlines()))
HEAD = "a" * 40
OLD = "b" * 40
EARLY = "2026-08-02T10:00:00Z"
LATE = "2026-08-02T11:00:00Z"
# The version marker Copilot's current overview format opens its body with, which identifies it.
CCR_MARKER = "<!-- ccr-overview-v2 -->"
# A round in that format with no verdict, no count, and no statement of what it read.
OVERVIEW = f"{CCR_MARKER}\n\nThe change is narrow.\n"
# The machine-readable statement of a round that read every changed file.
COVERED = "<!-- fleet-review: reviewed=3 changed=3 findings=0 -->"
# The wall-clock ceiling the backtracking cases read, stated once so they cannot drift apart.
# Each case sizes its own input so that a regression finishes and trips this rather than running long enough to hang the suite.
# Three seconds against readings of microseconds and milliseconds, which is the margin that makes a loaded runner a non-issue rather than the clock being trusted.
BACKTRACK_BOUND = 3.0
def review(
login: str = pr_review_rounds.REVIEWER,
oid: str | None = HEAD,
body: str = OVERVIEW + "\n<!-- fleet-review: reviewed=1 changed=1 findings=0 -->",
at: str = EARLY,
rid: str = "PRR_one",
) -> dict:
return {
"id": rid,
"author": {"login": login},
"state": "COMMENTED",
"commit": {"oid": oid},
"body": body,
"submittedAt": at,
}
def request_state(pending: bool = False, events: tuple[str, ...] = ()) -> dict:
"""What a review request leaves on a pull request, in the shape `REQUEST_STATE` reads it.
`events` are the ids of review-request events naming the reviewer, oldest first. The request
set carries the reviewer where `pending` is true.
"""
bot = {"__typename": "Bot", "login": pr_review_rounds.REVIEWER}
return {
"reviewRequests": {"nodes": [{"requestedReviewer": bot}] if pending else []},
"timelineItems": {"nodes": [{"id": e, "requestedReviewer": bot} for e in events]},
}
RECORDED = (request_state(events=("RRE_1",)), request_state(True, ("RRE_1", "RRE_2")))
def answer_request(query: str, variables: dict, states: tuple[dict, dict]) -> dict | None:
"""The pre-request read and the mutation, answered from `states`, or None for any other document."""
if "requestReviews" in query:
return {"requestReviews": {"pullRequest": {"id": variables.get("pr"), **states[1]}}}
if "REVIEW_REQUESTED_EVENT" in query:
return {"repository": {"pullRequest": {"id": "PR_test", **states[0]}}}
return None
def hist_review(number: int, body: str, at: str = LATE) -> dict:
"""One `pullRequests.nodes` entry in the shape `copilot_history` reads it: a pull request
number paired with one reviewer review, for the repo-wide reading `wire_history` drives.
`body` has no default, unlike `review()`'s, since every caller of this one cares which
wording it carries. The whole point of the repo-wide reading is telling a quota refusal
from a genuine round.
"""
return {
"number": number,
"reviews": {
"nodes": [
{
"author": {
"__typename": "Bot",
"login": pr_review_rounds.REVIEWER,
"id": "BOT_1",
},
"state": "COMMENTED",
"body": body,
"submittedAt": at,
}
]
},
"comments": {"nodes": []},
}
def comment(
login: str = pr_review_rounds.REVIEWER,
at: str = LATE,
body: str = "I have reached my quota limit and cannot review this now.",
) -> dict:
return {"author": {"login": login}, "createdAt": at, "body": body}
def unplaced(finding: str = "The retry bound is off by one.") -> str:
"""A marked overview carrying a collapsed section the vocabulary has no spelling for."""
return (
f"{OVERVIEW}\n<details>\n<summary>Confidence notes (1)</summary>\n\n{finding}\n"
f"</details>\n\n{COVERED}"
)
def ack(fp: str, association: str, text: str | None = None) -> dict:
"""A conversation comment acknowledging the unplaced set under `fp`, by `association`."""
written = f"Fixed in abc1234: the bound.\n\n{pr_review_rounds.ACK_MARKER.format(fp)}"
return {
"author": {"login": "maintainer"},
"authorAssociation": association,
"createdAt": LATE,
"body": written if text is None else text,
}
def overview_v2(
open_count: str = "2 open findings",
covers: str = "<!-- fleet-review: reviewed=1 changed=1 findings=2 -->",
effort: str = "<sub>Review effort: Lite</sub>",
entries: int = 2,
verdict: str = "### Changes recommended",
paths: tuple[str, ...] = ("a.py",),
) -> str:
"""A body in Copilot's current overview format, built from its own markers.
Each open entry links its thread's first comment, as `#discussion_r<id>`, the ids running
`400000000<n>`. The titles and paths are constructed rather than lifted from a live review,
per GOVERNANCE.md "Representative Data in Agent-Authored Text".
"""
listed = "\n".join(
f"- [Finding {i}](#discussion_r400000000{i}) New" for i in range(1, entries + 1)
)
rows = "\n".join(f"| `{p}` | Narrows the reader. |" for p in paths)
return (
f"{CCR_MARKER}\n\n{verdict}\n\nThe change is narrow.\n\n"
f"<details open>\n<summary><strong>{open_count}</strong></summary>\n\n"
f"{listed}\n</details>\n\n"
"<details>\n<summary><strong>What changed in this PR</strong></summary>\n\n"
"This pull request narrows one reader.\n\n**Changes:**\n- Narrow the reader.\n\n"
f"| File | Description |\n| ---- | ----------- |\n{rows}\n\n"
f"{covers}\n</details>\n\n{effort}\n"
)
def summarized(paths: list[str], covers: str = COVERED) -> str:
"""A round with no verdict or open section, carrying `covers` and a file table naming `paths`."""
rows = "\n".join(f"| `{p}` | Prose about the change. |" for p in paths)
return (
f"{OVERVIEW}\n{covers}\n\n<details>\n<summary><strong>What changed in this PR</strong>"
f"</summary>\n\n| File | Description |\n| ---- | ----------- |\n{rows}\n\n</details>\n"
)
REFUSED = (
"Copilot wasn't able to review this pull request because it exceeds the maximum "
"number of files (300). Try reducing the number of changed files and requesting a "
"review from Copilot again."
)
EXCLUDED_REFUSED = (
"Copilot wasn't able to review any files in this pull request. Check if the **Files "
"changed** in this pull request are included in [default exclusions]"
"(https://docs.example.test/review-excluded-files)."
)
ERROR_REFUSED = (
"Copilot encountered an error and was unable to review this pull request. You can try again "
"by re-requesting a review."
)
RATE_LIMIT_LOG = (
"2026-08-02T10:59:00.0000000Z Error creating PR review request: SessionModelError: You've "
"reached your weekly rate limit. Please wait for your limit to reset on August 9, 2026 at "
"12:00 AM or switch to auto model to continue. Learn More (https://docs.example.test).\n"
"2026-08-02T10:59:00.0000000Z errorType: 'rate_limit',\n"
)
TRANSIENT_LOG = (
"2026-08-02T10:59:00.0000000Z HttpError: The request could not be processed because too "
"many files changed - https://docs.example.test/pulls: Failed to fetch PR metadata for o/r#7\n"
)
TRANSIENT_LINE = TRANSIENT_LOG.strip()
SENT_AFTER = {
"reviewRequests": {"nodes": []},
"timelineItems": {
"nodes": [
{
"id": "RRE_1",
"createdAt": "2026-08-02T10:30:00Z",
"requestedReviewer": {"__typename": "Bot", "login": pr_review_rounds.REVIEWER},
}
]
},
}
# Quoted from the corpus rather than invented: the body a refused review carried, byte for byte.
QUOTA_REFUSED = (
"Copilot was unable to review this pull request because the user who requested the "
"review has reached their quota limit."
)
# Quoted from the corpus rather than invented: CodeRabbit's own comment, trimmed to the marker and its opening line.
# The rest is CodeRabbit's ordinary walkthrough prose.
RATE_LIMITED_COMMENT = (
"<!-- This is an auto-generated comment: rate limited by coderabbit.ai -->\n\n"
"> [!WARNING]\n> ## Review limit reached\n"
)
RATE_LIMITED_REPLY_COMMENT = (
"<!-- This is an auto-generated reply by CodeRabbit -->\n"
"<!-- CodeRabbit review command invocation: v2:0123abcd -->\n"
"<details>\n<summary>\u26a0\ufe0f Action not completed</summary>\n\n"
"Review rate limited.\n</details>\n"
)
def thread(
tid: str,
resolved: bool = False,
login: str = pr_review_rounds.REVIEWER,
body: str = "A finding.",
path: str = "a.py",
line: int = 1,
rid: str | None = None,
cid: str | None = None,
) -> dict:
"""One `reviewThreads` node. `rid` is the review that opened it, which the manifest counts.
`cid` is its first comment's database id, which an overview entry's `#discussion_r` anchor
links. A `cid` of None leaves the thread carrying none, as every case not reading those entries wants.
None leaves the thread naming no round. That is the shape the reader has to survive rather
than a claim about when GitHub returns it. It is also what every case not exercising the
manifest wants. A thread belonging to a different round is the realistic exclusion, and a case
covers that one separately.
"""
return {
"id": tid,
"isResolved": resolved,
"comments": {
"nodes": [
{
"author": {"login": login},
"path": path,
"line": line,
"body": body,
"pullRequestReview": {"id": rid} if rid else None,
**({"fullDatabaseId": cid} if cid else {}),
}
]
},
}
# A fixed clock, so a case holds a check at a known age instead of at whatever the suite runs at.
NOW = datetime(2026, 8, 6, 17, 0, 0, tzinfo=UTC)
def ago(seconds: int) -> str:
"""A timestamp `seconds` before NOW, in the spelling GraphQL returns.
For the cases that pass NOW in as the clock. A `wait` case cannot use this, since `main` reads
the real clock. An age measured from a fixed point against a moving one is also not the age the
case means. That age grows on every later run and goes negative on any machine whose clock sits
before NOW. Those cases take `real_ago` instead.
"""
return (NOW - timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
def real_ago(seconds: int) -> str:
"""A timestamp `seconds` before the real clock, for the `wait` path, which reads that clock."""
return (datetime.now(UTC) - timedelta(seconds=seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")
def check(
name: str = "Check pull request workflow status job",
status: str = "COMPLETED",
conclusion: str = "SUCCESS",
started: str | None = None,
suite: int = 1,
workflow: int | None = None,
slug: str = "github-actions",
app_id: int = 15368,
suite_status: str | None = None,
run: int | None = None,
) -> dict:
"""One CheckRun rollup node, in the shape the live rollup returns.
The run's `databaseId` is carried only where a case names one. A case may name the suite's
status. Otherwise the suite is in progress beside a running job and completed beside any other.
That is because a running job in a completed suite is the stale record `STALE_RECORD` names.
The starved case this exists for was read off run 31118675530 in this repository. An aggregator
job was dispatched the instant its dependency finished. It was left `QUEUED` with an empty runner name and
a `startedAt` stamped equal to its creation, and it sat fifteen minutes and never ran. Its
healthy sibling on the next run wore `IN_PROGRESS` with a runner inside two minutes.
"""
if suite_status is None:
suite_status = "IN_PROGRESS" if status == "IN_PROGRESS" else "COMPLETED"
workflow_run: dict | None = None
if workflow is not None:
workflow_run = {"workflow": {"databaseId": workflow}}
if run is not None:
workflow_run["databaseId"] = run
check_suite: dict = {
"databaseId": suite,
"app": {"slug": slug, "databaseId": app_id},
"workflowRun": workflow_run,
"status": suite_status,
}
return {
"__typename": "CheckRun",
"name": name,
"status": status,
"conclusion": conclusion,
"startedAt": ago(60) if started is None else started,
"checkSuite": check_suite,
}
def status_context(
context: str = "ci/external", state: str = "SUCCESS", created: str | None = None
) -> dict:
"""One StatusContext rollup node, which spells every field differently from a CheckRun."""
return {
"__typename": "StatusContext",
"context": context,
"state": state,
"createdAt": ago(60) if created is None else created,
}
def payload(
reviews: list[dict],
threads: list[dict] | None = None,
merge: str = "CLEAN",
comments: list[dict] | None = None,
older: bool = False,
older_reviews: bool = False,
pending: bool = False,
checks: list[dict] | None = None,
rollup_oid: str | None = None,
files: list[str] | None = None,
more_files: bool = False,
more_threads: bool = False,
lineless: list[str] | None = None,
) -> dict:
requested = (
[{"requestedReviewer": {"__typename": "Bot", "login": pr_review_rounds.REVIEWER}}]
if pending
else []
)
return {
"id": "PR_test",
"headRefOid": HEAD,
"baseRefName": "develop",
"mergeable": "MERGEABLE",
"mergeStateStatus": merge,
# The diff's own file list, which the round's file table is compared against.
# A case naming none gets the empty connection a pull request of no files carries.
"files": {
"nodes": [
{"path": p, "additions": 1, "deletions": 0, "changeType": "MODIFIED"}
for p in files or []
]
+ [
{"path": p, "additions": 0, "deletions": 0, "changeType": "ADDED"}
for p in lineless or []
],
"pageInfo": {"hasNextPage": more_files},
},
"reviews": {"nodes": reviews, "pageInfo": {"hasPreviousPage": older_reviews}},
"reviewThreads": {
"nodes": threads or [],
"pageInfo": {"hasNextPage": more_threads},
},
"comments": {"nodes": comments or [], "pageInfo": {"hasPreviousPage": older}},
"reviewRequests": {"nodes": requested},
"commits": {
"nodes": [
{
"commit": {
"oid": rollup_oid or HEAD,
# Compared against None, so an existing rollup carrying nothing is expressible.
# Reading `if checks` collapsed that onto a null rollup, and the two differ.
# An empty rollup is a pull request whose checks have not registered yet.
# A null one is a pull request that has none at all.
"statusCheckRollup": {"state": "PENDING", "contexts": {"nodes": checks}}
if checks is not None
else None,
}
}
]
},
}
class GqlCase(unittest.TestCase):
"""Base that answers every `gql` call from a queue, so no case reaches the network."""
def setUp(self) -> None:
"""Patch `gh_rest` to a read that did not happen, for every case rather than every caller.
Patched inside `answer` instead, a case building its own payload and never calling it
could spawn a real `gh`. That `gh` would run against a pull request that does not exist.
That is what this suite exists not to do.
The re-read schedule is emptied too, so a case answering a failed read is not slept on or
asked again. A case about the re-read sets its own schedule.
"""
super().setUp()
# These readers are memoized for the run, and the cases share their commit constants.
pr_review.run_cause.cache_clear()
self.addCleanup(pr_review.run_cause.cache_clear)
pr_review.required_contexts.cache_clear()
self.addCleanup(pr_review.required_contexts.cache_clear)
self.enterContext(
mock.patch.object(
pr_review,
"gh_rest",
return_value=subprocess.CompletedProcess([], 1, "", "no read in this suite"),
)
)
self.enterContext(mock.patch.object(pr_review, "READ_RETRY_DELAYS", ()))
def answer(self, *responses: dict) -> mock.MagicMock:
"""Patch `gql` to return each response in turn, repeating the last one.
Also patches `gh_graphql` directly with a default reporting no Copilot review anywhere
to read a bot id from. `wait`'s auto-request therefore finds nothing to request and falls
straight through to polling, same as a repository with no Copilot history. `gql` itself
never reaches the real `gh_graphql`, since the mock above replaces it wholesale. The
two patches therefore govern disjoint call sites, and neither can shadow the other. A case
exercising the auto-request itself re-patches `gh_graphql` after calling this.
`origin_owner` is patched to this suite's own "o" too, since `wait` now runs the same
in-scope check `comment` and `reply` already did. It is needed too because the cases run against a
real checkout whose actual origin has nothing to do with the "o/r" they exercise.
`gh_rest` is patched in `setUp` rather than here, so a case that never calls this still
makes no REST read.
`page_files` is patched to leave each response as it stands, since a response here is
the whole read, a list marked cut short included. A case about paging patches
`gh_graphql` itself rather than calling this.
"""
queue = list(responses)
self.enterContext(mock.patch.object(pr_review, "page_files"))
def fake(_query, _owner, _repo, _num):
pr = queue.pop(0) if len(queue) > 1 else queue[0]
if isinstance(pr, dict) and pr.get("baseRefName"):
pr.setdefault(pr_review.POLICY_KEY, DEFAULT_POLICY)
return pr
patched = self.enterContext(mock.patch.object(pr_review, "gql", side_effect=fake))
self.enterContext(mock.patch.object(pr_review, "origin_owner", return_value="o"))
self.enterContext(
mock.patch.object(
pr_review,
"gh_graphql",
return_value={"repository": {"pullRequests": {"nodes": []}}},
)
)
return patched
class TestLiveState(GqlCase):
def test_the_review_must_be_the_reviewer_and_on_the_current_head(self) -> None:
"""A stale review is the failure the whole wait exists to avoid reporting as done."""
for label, reviews, want in (
("reviewer on head", [review()], True),
("reviewer on an older commit", [review(oid=OLD)], False),
("a human on head", [review(login="ptr727")], False),
("no reviews at all", [], False),
("stale round plus a current one", [review(oid=OLD), review()], True),
):
with self.subTest(case=label):
self.answer(payload(reviews))
self.assertEqual((want, None, []), pr_review.live_state("o", "r", 1))
def test_a_null_author_or_commit_does_not_raise(self) -> None:
"""GraphQL returns null for a deleted account, and a crash there stalls the whole wait."""
self.answer(payload([{"author": None, "state": "COMMENTED", "commit": None}]))
self.assertEqual((False, None, []), pr_review.live_state("o", "r", 1))
def test_a_poll_reads_the_same_three_readings_its_payload_gives(self) -> None:
for label, pr in (
("on head", payload([review()])),
("stale", payload([review(oid=OLD)])),
("answered outside", payload([review(oid=OLD, at=EARLY)], comments=[comment(at=LATE)])),
):
with self.subTest(case=label):
self.answer(pr)
self.assertEqual(pr_review.liveness(pr), pr_review.live_state("o", "r", 1))
class TestAnsweredOutsideReview(unittest.TestCase):
"""A refusal answers the request without covering the head, so a wait cannot read it as pending."""
def test_a_reviewer_comment_newer_than_every_review_is_the_answer(self) -> None:
answer = pr_review_rounds.answered_outside_review(
payload([review(oid=OLD, at=EARLY)], comments=[comment(at=LATE)])
)
self.assertIsNotNone(answer)
self.assertEqual(LATE, (answer or {}).get("createdAt"))
def test_an_answer_the_reviewer_then_superseded_is_spent(self) -> None:
"""The review it preceded did land, so the comment is history rather than a stop signal."""
self.assertIsNone(
pr_review_rounds.answered_outside_review(
payload([review(at=LATE)], comments=[comment(at=EARLY)])
)
)
def test_another_account_s_comment_is_not_the_reviewer_answering(self) -> None:
"""A maintainer note and a codecov post both postdate the review and mean nothing here."""
for login in ("ptr727", "codecov[bot]", "copilot-swe-agent"):
with self.subTest(login=login):
self.assertIsNone(
pr_review_rounds.answered_outside_review(
payload([review(oid=OLD)], comments=[comment(login=login)])
)
)
def test_no_comments_at_all_reads_as_no_answer(self) -> None:
self.assertIsNone(pr_review_rounds.answered_outside_review(payload([review(oid=OLD)])))
def test_ordinary_discussion_does_not_push_the_answer_out_of_the_window(self) -> None:
"""The window reads the newest comments, not the reviewer's, so others crowd it."""
chatter = [comment(login="ptr727", at=LATE) for _ in range(pr_review.WINDOW - 1)]
found = pr_review_rounds.answered_outside_review(
payload([review(oid=OLD, at=EARLY)], comments=[comment(at=LATE)] + chatter)
)
self.assertIsNotNone(found)
def test_comments_behind_the_window_are_unknown_rather_than_no_answer(self) -> None:
"""Finding nothing and having nothing to find are one reading once an answer can hide."""
full = [comment(login="ptr727") for _ in range(pr_review.WINDOW)]
self.assertTrue(
pr_review_rounds.window_blind(
payload([review()], comments=full, older=True), "comments"
)
)
def test_a_window_holding_every_comment_is_not_a_gap(self) -> None:
"""A full window and a window holding the lot are the same length, so length cannot say."""
full = [comment(login="ptr727") for _ in range(pr_review.WINDOW)]
self.assertFalse(
pr_review_rounds.window_blind(
payload([review()], comments=full, older=False), "comments"
)
)
def test_reviews_behind_the_window_report_nothing_rather_than_a_false_answer(self) -> None:
"""No reviewer review in view dates every comment as newer, so each reads as an answer.
Reporting nothing keeps the wait polling. In contrast, a wrong answer ends it outright on a
pull request whose review landed and simply sits behind a busier review history.
"""
pr = payload(
[review(login="ptr727") for _ in range(pr_review.WINDOW)],
comments=[comment(at=LATE)],
older_reviews=True,
)
self.assertTrue(pr_review_rounds.window_blind(pr, "reviews"))
self.assertIsNone(pr_review_rounds.answered_outside_review(pr))
def test_one_reviewer_review_in_view_is_a_baseline_the_answer_can_be_dated_against(
self,
) -> None:
"""Reviews arrive in creation order too, so a hidden one is older than the one in view."""
pr = payload(
[review(at=EARLY, oid=OLD)]
+ [review(login="ptr727") for _ in range(pr_review.WINDOW - 1)],
comments=[comment(at=LATE)],
older_reviews=True,
)
self.assertFalse(pr_review_rounds.window_blind(pr, "reviews"))
self.assertIsNotNone(pr_review_rounds.answered_outside_review(pr))
def test_one_spent_reviewer_comment_in_view_settles_the_question(self) -> None:
"""Comments arrive in creation order, so a hidden one is older than the spent one in view."""
full = [comment(at=EARLY)] + [comment(login="ptr727") for _ in range(pr_review.WINDOW - 1)]
pr = payload([review(at=LATE)], comments=full, older=True)
self.assertIsNone(pr_review_rounds.answered_outside_review(pr))
self.assertFalse(pr_review_rounds.window_blind(pr, "comments"))
def test_threads_truncated_reads_the_review_threads_page_info(self) -> None:
"""Unlike `window_blind`'s `last`-windowed connections, `reviewThreads` reads forward
from the first page. `hasNextPage` alone therefore says a page was cut, with nothing in view
to settle which end."""
self.assertTrue(pr_review_rounds.threads_truncated(payload([review()], more_threads=True)))
self.assertFalse(
pr_review_rounds.threads_truncated(payload([review()], more_threads=False))
)
class TestDigest(GqlCase):
def test_the_summary_line_counts_what_it_names(self) -> None:
self.answer(
payload([review(), review(oid=OLD)], [thread("T1"), thread("T2", resolved=True)])
)
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(1, unresolved)
self.assertIn("pr=7", out)
self.assertIn(f"head={HEAD[:8]}", out)
self.assertIn("rounds=2", out)
self.assertIn("review_on_head=yes", out)
self.assertIn("threads=2", out)
self.assertIn("unresolved=1", out)
self.assertIn("merge=CLEAN", out)
def test_a_truncated_thread_page_marks_the_summary_and_names_the_gap(self) -> None:
"""`reviewThreads(first:100)` carries no cursor, so a pull request with more than
that many threads must say so rather than letting `threads=`/`unresolved=` undercount
silently. The connection reads oldest-first, so what is cut is the newest threads."""
self.answer(payload([review()], [thread("T1")], more_threads=True))
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(1, unresolved)
self.assertIn("threads=1+ unresolved=1+", out)
self.assertIn("THREADS TRUNCATED", out)
def test_an_untruncated_thread_page_carries_no_marker_or_block(self) -> None:
self.answer(payload([review()], [thread("T1")], more_threads=False))
out, _ = pr_review.digest("o", "r", 7)
self.assertIn("threads=1 unresolved=1", out)
self.assertNotIn("THREADS TRUNCATED", out)
def test_review_on_head_reports_no_when_every_round_is_stale(self) -> None:
"""`NO` is upper-case on purpose, so the one state that blocks a merge is not skimmed past."""
self.answer(payload([review(oid=OLD)]))
out, _ = pr_review.digest("o", "r", 7)
self.assertIn("review_on_head=NO", out)
def test_digest_reports_effective_effort_without_changing_the_verdict(self) -> None:
self.answer(
payload(
[
review(
body=f"{OVERVIEW}\n{COVERED}\n\n<sub>Review effort: Default (Balanced)</sub>"
)
]
)
)
out, _ = pr_review.digest("o", "r", 7)
self.assertIn("effort=balanced effort_source=default", out)
self.assertIn("coverage=full", out)
def test_a_thread_from_a_deleted_account_does_not_crash_the_digest(self) -> None:
"""GraphQL sends `author` present and null, which a defaulted lookup returns as None.
The thread still blocks the merge, so it counts, attributed as `other`.
"""
orphan = thread("T1")
orphan["comments"]["nodes"][0]["author"] = None
self.answer(payload([review()], [orphan, thread("T2")]))
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(2, unresolved)
self.assertIn(f"unresolved=2 ({pr_review_rounds.REVIEWER}=1 other=1)", out)
self.assertIn("T1", out)
self.assertIn("T2", out)
def test_every_open_thread_is_listed_whoever_opened_it(self) -> None:
"""An open thread blocks a ruleset-gated merge whatever its author."""
self.answer(payload([review()], [thread("T1", login="ptr727"), thread("T2")]))
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(2, unresolved)
self.assertIn("T1", out)
self.assertIn("T2", out)
def test_a_seen_set_marks_each_thread_new_exactly_once(self) -> None:
"""The seen set is what tells a second round's findings from the ones already answered."""
seen: set[str] = set()
self.answer(
payload([review()], [thread("T1")]), payload([review()], [thread("T1"), thread("T2")])
)
first, _ = pr_review.digest("o", "r", 7, seen)
self.assertIn("NEW T1", first)
self.assertIn("new=1", first)
second, unresolved = pr_review.digest("o", "r", 7, seen)
self.assertNotIn("T1", second)
self.assertIn("NEW T2", second)
self.assertIn("new=1", second)
# The count still reports every open thread, not only the newly seen ones.
self.assertEqual(2, unresolved)
def test_a_body_is_flattened_and_bounded(self) -> None:
"""A multi-line finding on one digest line keeps the digest a few hundred bytes."""
self.answer(payload([review()], [thread("T1", body="one\n two\t\tthree " + "x" * 400)]))
out, _ = pr_review.digest("o", "r", 7)
body = out.split("\n")[1]
self.assertIn("one two three", body)
self.assertLessEqual(len(body.split("a.py:1 ")[1]), 160)
CROWDED_DIGEST = "\n".join(
(
(
"repo=o/r pr=7 head=aaaaaaaa rounds=2 review_on_head=yes effort=unknown "
"effort_source=unknown coverage=full shapes=ok refusal=no threads=2+ unresolved=2+ "
f"({pr_review_rounds.REVIEWER}=1 other=1) suppressed=0+ (on_head=0 earlier=0) "
"previously_missed=0+ (on_head=0 earlier=0) overview=?/0 cr_outside_diff=0+ "
"(on_head=0 earlier=0) qodo_open=unknown answered_outside_review=unknown requested=no "
"merge=BLOCKED checks=0/1 stuck=FAILED new=2"
),
(
" CHECK FAILED ('Check pull request workflow status job', COMPLETED/FAILURE): a verdict "
"rather than a stuck check, so read the run and fix what failed, since no wait and no "
"re-run clears a real failure"
),
(
" BEHIND THE WINDOW (comments): the newest 100 carry none from the reviewer and older "
"ones exist, so this cannot decide"
),
(
" THREADS TRUNCATED: this pull request carries more review threads than the 100 read "
"here, and the connection reads oldest-first, so the ones cut off are the newest rather "
"than the oldest, exactly the ones most likely to still be open. `threads=` and "
"`unresolved=` above undercount. Read the rest with `reply`'s own paginated walk before "
"trusting either number"
),
(
" REVIEWS TRUNCATED: this pull request carries more reviews than the 100 read here, and "
"the connection reads newest-first, so the ones cut off are the oldest, exactly where an "
"unanswered suppressed or outside-diff-range finding is most likely to still sit "
"unresolved. `suppressed=` and `cr_outside_diff=` above undercount"
),
" NEW T1 a.py:1 First finding.",
" NEW T2 a.py:1 A finding.",
)
)
QUIET_DIGEST = (
"repo=o/r pr=7 head=aaaaaaaa rounds=1 review_on_head=NO effort=unknown effort_source=unknown "
"coverage=none shapes=ok refusal=no threads=0 unresolved=0 suppressed=0 (on_head=0 earlier=0) "
"answered_outside_review=no requested=yes merge=CLEAN checks=1/1"
)
class TestDigestRenderIsPinned(GqlCase):
"""The whole digest, byte for byte, as `pr_review_digest.render` lays it out.
Each expected text was captured before the rendering moved to the leaf module.
A reorder among the fields and lines these two cases print fails here rather than in a parse.
"""
def test_a_crowded_digest_keeps_its_field_and_advisory_order(self) -> None:
self.answer(
payload(
[review(), review(oid=OLD, rid="PRR_two")],
[thread("T1", body="First finding."), thread("T2", login="ptr727")],
merge="BLOCKED",
comments=[comment(login="ptr727") for _ in range(pr_review.WINDOW)],
older=True,
older_reviews=True,
checks=[check(conclusion="FAILURE")],
more_threads=True,
)
)
out, unresolved = pr_review.digest("o", "r", 7, set(), now=NOW)
self.assertEqual(2, unresolved)
self.assertEqual(CROWDED_DIGEST, out)
def test_a_quiet_digest_leaves_out_every_optional_field(self) -> None:
self.answer(payload([review(oid=OLD)], checks=[check()], pending=True))
out, unresolved = pr_review.digest("o", "r", 7, now=NOW)
self.assertEqual(0, unresolved)
self.assertEqual(QUIET_DIGEST, out)
class TestOtherReviewers(GqlCase):
"""Thread resolution, head-presence, and the rate-limit marker's own structural pattern,
generalized past Copilot to the other review bots this repository has trialed. Free-text
prose parsing for CodeRabbit's outside-diff findings and Qodo's comment-only findings lives
in `TestCodeRabbitOutsideDiff` and `TestQodoOpenFindings` below, not here.
`status`'s `unresolved=0` used to hide a CodeRabbit/qodo thread that still blocked a
ruleset-gated merge. That held first since only Copilot's own threads counted and then since
only known reviewer logins did. So every open thread now counts, and a login only attributes it.
Coverage and refusal reading stay Copilot-only. `review_on_head` above names Copilot's own coverage
specifically, the reviewer this script requests and waits for, not "no review of any kind
covers this head".
"""
def other_review(self, login: str, oid: str = HEAD, body: str = "") -> dict:
"""A review node for a tracked non-Copilot reviewer, `body` empty unless a case needs it."""
return {
"author": {"login": login},
"state": "COMMENTED",
"commit": {"oid": oid},
"body": body,
"submittedAt": LATE,
}
def test_a_coderabbit_and_a_qodo_thread_both_count_toward_unresolved(self) -> None:
self.answer(
payload(
[review()],
[
thread("T1", login="coderabbitai"),
thread("T2", login="qodo-free-for-open-source-projects"),
thread("T3", resolved=True, login="coderabbitai"),
],
)
)
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(2, unresolved)
self.assertIn("unresolved=2", out)
self.assertIn("T1", out)
self.assertIn("T2", out)
self.assertNotIn("T3", out)
def test_a_thread_from_an_unknown_login_counts_and_is_named_other(self) -> None:
"""A reviewer posting under a login missing from the known set once read `unresolved=0`.
The known logins attribute a thread and never decide whether it counts. `other` is
named even where it is the only contributor, since it is the count a reader cannot assume.
"""
self.answer(payload([review()], [thread("T1", login="example-review-bot")]))
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(1, unresolved)
self.assertIn("unresolved=1 (other=1)", out)
self.assertIn("T1", out)
def test_status_and_wait_print_an_unknown_login_s_thread_in_the_digest(self) -> None:
"""`status` and `wait` print the digest a Merge Gate decision is read from."""
unknown = thread("T1", login="example-review-bot")
for command in (["status", "7"], ["wait", "7"]):
with self.subTest(command=command[0]):
self.answer(payload([review()], [unknown]))
out = io.StringIO()
with (
contextlib.redirect_stdout(out),
mock.patch.object(pr_review.time, "sleep"),
):
pr_review.main([*command, "--repo", "o/r"])
self.assertIn("unresolved=1 (other=1)", out.getvalue())
self.assertIn("T1", out.getvalue())
def test_one_known_reviewer_alone_prints_no_breakdown_and_two_print_one(self) -> None:
self.answer(payload([review()], [thread("T1"), thread("T2")]))
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(2, unresolved)
self.assertIn("unresolved=2 ", out)
self.assertNotIn("unresolved=2 (", out)
self.answer(payload([review()], [thread("T1"), thread("T2", login="coderabbitai")]))
out, unresolved = pr_review.digest("o", "r", 7)
self.assertEqual(2, unresolved)
self.assertIn(f"unresolved=2 ({pr_review_rounds.REVIEWER}=1 coderabbitai=1)", out)
def test_other_reviewed_names_only_the_bots_that_posted_on_this_exact_head(self) -> None:
self.answer(
payload(
[
review(),
self.other_review("coderabbitai"),
self.other_review(pr_review_rounds.QODO_LOGIN, oid=OLD),
]
)
)
out, _ = pr_review.digest("o", "r", 7)
self.assertIn("other_reviewed=coderabbitai", out)
self.assertNotIn(pr_review_rounds.QODO_LOGIN, out)