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
|
"""Tests for the PR quality checks in check_pr.py."""
import json
import logging
import tempfile
import unittest
import urllib.error
from pathlib import Path
from unittest import mock
from pr_quality import check_pr
from pr_quality.errors import LEVEL_ERROR, LEVEL_WARNING, MISSING_TRAC_TICKET, Message
logger = logging.getLogger("pr_quality.check_pr")
UNSET = object()
ERROR_ICON, ERROR_LABEL = LEVEL_ERROR
WARNING_ICON, WARNING_LABEL = LEVEL_WARNING
def make_pr_body(
ticket="ticket-36991",
description=(
"Fix regression in template rendering where nested blocks were"
" incorrectly evaluated."
),
no_ai_checked=True,
ai_used_checked=False,
ai_description="",
checked_items=5,
):
no_ai_box = "[x]" if no_ai_checked else "[ ]"
ai_used_box = "[x]" if ai_used_checked else "[ ]"
ai_extra = f"\n{ai_description}" if ai_description else ""
checklist_items = [
"This PR follows the [contribution guidelines]"
"(https://docs.djangoproject.com/en/stable/internals/contributing/"
"writing-code/submitting-patches/).",
"This PR **does not** disclose a security vulnerability"
" (see [vulnerability reporting]"
"(https://docs.djangoproject.com/en/stable/internals/security/)).",
"This PR targets the `main` branch."
" <!-- Backports will be evaluated and done by mergers, when necessary. -->",
"The commit message is written in past tense, mentions the ticket"
" number, and ends with a period (see [guidelines]"
"(https://docs.djangoproject.com/en/dev/internals/contributing/"
"committing-code/#committing-guidelines)).",
"I have not requested, and will not request, an automated AI review"
" for this PR."
" <!-- You are welcome to do so in your own fork. -->",
'I have checked the "Has patch" ticket flag in the Trac system.',
"I have added or updated relevant tests.",
"I have added or updated relevant docs, including release notes if"
" applicable.",
"I have attached screenshots in both light and dark modes for any UI"
" changes.",
]
checklist_lines = "\n".join(
f"- [x] {item}" if i < checked_items else f"- [ ] {item}"
for i, item in enumerate(checklist_items)
)
# GitHub PR bodies are plain markdown with no leading spaces.
return (
f"#### Trac ticket number\n"
f"<!-- Replace XXXXX with the corresponding Trac ticket number. -->\n"
f'<!-- Or delete the line and write "N/A - typo" for typo fixes. -->\n'
f"\n"
f"{ticket}\n"
f"\n"
f"#### Branch description\n"
f"{description}\n"
f"\n"
f"#### AI Assistance Disclosure (REQUIRED)\n"
f"<!-- Please select exactly ONE of the following: -->\n"
f"- {no_ai_box} **No AI tools were used** in preparing this PR.\n"
f"- {ai_used_box} **If AI tools were used**, I have disclosed which"
f" ones, and fully reviewed and verified their output.{ai_extra}\n"
f"\n"
f"#### Checklist\n"
f"{checklist_lines}\n"
)
VALID_PR_BODY = make_pr_body()
VALID_PR_TITLE = "Fixed #36991 -- Fix template rendering regression."
def make_trac_json(
ticket_id="36991",
stage="Accepted",
status="assigned",
resolution="",
has_patch="0",
needs_docs="0",
needs_tests="0",
needs_better_patch="0",
):
return {
"id": int(ticket_id),
"summary": "Some summary",
"status": status,
"resolution": resolution,
"custom": {
"stage": stage,
"has_patch": has_patch,
"needs_docs": needs_docs,
"needs_tests": needs_tests,
"needs_better_patch": needs_better_patch,
},
}
def patch_urlopen(json_responses=(), status_code=200):
side_effects = []
if status_code == 200:
for data in json_responses:
mock_response = mock.MagicMock()
mock_response.read.return_value = json.dumps(data).encode()
mock_cm = mock.MagicMock()
mock_cm.__enter__.return_value = mock_response
side_effects.append(mock_cm)
else:
error = urllib.error.HTTPError(
url="https://example.com",
code=status_code,
msg="Error",
hdrs=None,
fp=None,
)
side_effects.append(error)
return mock.patch("urllib.request.urlopen", side_effect=side_effects)
class BaseTestCase(unittest.TestCase):
def setUp(self):
null_handler = logging.NullHandler()
logger.addHandler(null_handler)
self.addCleanup(logger.removeHandler, null_handler)
def call_main(
self,
repo="test/repo",
token="test-token",
pr_author="trusted",
pr_body="",
pr_title="",
pr_created_at=None,
pr_number="10",
total_changes=check_pr.LARGE_PR_THRESHOLD,
commit_count=0,
autoclose=True,
trac_data=UNSET,
):
if trac_data is UNSET:
trac_data = make_trac_json(stage="Accepted", has_patch="1")
with (
mock.patch.object(
check_pr, "get_pr_total_changes", return_value=total_changes
),
mock.patch.object(
check_pr, "get_recent_commit_count", return_value=commit_count
),
mock.patch.object(check_pr, "write_job_summary") as mock_summary,
mock.patch.object(check_pr, "github_request", mock.MagicMock()) as mock_gh,
mock.patch.object(check_pr, "fetch_trac_ticket", return_value=trac_data),
):
result = check_pr.main(
repo=repo,
token=token,
pr_author=pr_author,
pr_body=pr_body,
pr_title=pr_title,
pr_number=pr_number,
pr_created_at=pr_created_at,
autoclose=autoclose,
gha_formatter=False,
)
return result, mock_summary, mock_gh
class TestExtractTicketId(BaseTestCase):
def test_valid_ticket_returns_id(self):
self.assertEqual(check_pr.extract_ticket_id("ticket-36991"), "36991")
def test_ticket_in_sentence_returns_id(self):
self.assertEqual(
check_pr.extract_ticket_id("See ticket-12345 for details."), "12345"
)
def test_case_insensitive(self):
self.assertEqual(check_pr.extract_ticket_id("TICKET-99"), "99")
def test_no_ticket_returns_none(self):
self.assertIsNone(check_pr.extract_ticket_id("No ticket here."))
def test_na_returns_none(self):
self.assertIsNone(check_pr.extract_ticket_id("N/A - typo fix"))
def test_ticket_placeholder_returns_none(self):
self.assertIsNone(check_pr.extract_ticket_id("ticket-XXXXX"))
def test_returns_first_ticket_id(self):
self.assertEqual(check_pr.extract_ticket_id("ticket-111 and ticket-222"), "111")
class TestFetchTracTicket(BaseTestCase):
def test_success_returns_dict(self):
data = make_trac_json(stage="Accepted", has_patch="1")
with patch_urlopen([data]):
result = check_pr.fetch_trac_ticket("36991")
self.assertEqual(result["custom"]["stage"], "Accepted")
self.assertEqual(result["custom"]["has_patch"], "1")
def test_http_404_returns_ticket_not_found(self):
with patch_urlopen(status_code=404):
result = check_pr.fetch_trac_ticket("99999")
self.assertIs(result, check_pr.TICKET_NOT_FOUND)
def test_http_500_returns_none(self):
with patch_urlopen(status_code=500):
result = check_pr.fetch_trac_ticket("36991")
self.assertIsNone(result)
def test_network_error_returns_none(self):
with mock.patch(
"urllib.request.urlopen", side_effect=OSError("Connection refused")
):
result = check_pr.fetch_trac_ticket("36991")
self.assertIsNone(result)
def test_uses_trac_api_url(self):
data = make_trac_json()
with patch_urlopen([data]) as mock_urlopen:
check_pr.fetch_trac_ticket("36991")
url_called = mock_urlopen.call_args.args[0]
self.assertIn("djangoproject.com/trac/api/tickets/36991", url_called)
class TestCheckTracTicket(BaseTestCase):
def test_valid_ticket_small_pr_passes(self):
self.assertIsNone(
check_pr.check_trac_ticket(VALID_PR_BODY, check_pr.LARGE_PR_THRESHOLD - 1)
)
def test_valid_ticket_large_pr_passes(self):
self.assertIsNone(
check_pr.check_trac_ticket(VALID_PR_BODY, check_pr.LARGE_PR_THRESHOLD)
)
def test_placeholder_fails(self):
body = make_pr_body(ticket="ticket-XXXXX")
self.assertIsNotNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD - 1)
)
def test_missing_small_pr_fails(self):
body = make_pr_body(ticket="")
self.assertIsNotNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD - 1)
)
def test_missing_large_pr_fails(self):
body = make_pr_body(ticket="")
self.assertIsNotNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD)
)
def test_na_small_pr_passes(self):
body = make_pr_body(ticket="N/A - typo")
self.assertIsNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD - 1)
)
def test_na_bare_small_pr_passes(self):
body = make_pr_body(ticket="N/A")
self.assertIsNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD - 1)
)
def test_na_large_pr_fails(self):
body = make_pr_body(ticket="N/A - typo")
self.assertIsNotNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD)
)
def test_na_at_threshold_fails(self):
body = make_pr_body(ticket="N/A")
self.assertIsNotNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD)
)
def test_na_just_below_threshold_passes(self):
body = make_pr_body(ticket="N/A")
self.assertIsNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD - 1)
)
def test_ticket_na_format_fails(self):
body = make_pr_body(ticket="ticket-N/A")
self.assertIsNotNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD - 1)
)
def test_various_ticket_lengths_pass(self):
for ticket in ["ticket-1", "ticket-123", "ticket-999999"]:
with self.subTest(ticket=ticket):
body = make_pr_body(ticket=ticket)
self.assertIsNone(
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD)
)
class TestCheckTracStatus(BaseTestCase):
def test_accepted_assigned_unresolved_passes(self):
# The Trac API returns null (None) for open tickets.
data = make_trac_json(stage="Accepted", status="assigned", resolution=None)
self.assertIsNone(check_pr.check_trac_status("36991", data))
def test_non_accepted_stage_fails(self):
for stage in ["Unreviewed", "Ready for Checkin", "Someday/Maybe"]:
with self.subTest(stage=stage):
data = make_trac_json(stage=stage)
self.assertIsNotNone(check_pr.check_trac_status("36991", data))
def test_resolved_ticket_fails(self):
for resolution in [
"fixed",
"wontfix",
"duplicate",
"invalid",
"worksforme",
"needsinfo",
"needsnewfeatureprocess",
]:
with self.subTest(resolution=resolution):
data = make_trac_json(
stage="Accepted", status="assigned", resolution=resolution
)
self.assertIsNotNone(check_pr.check_trac_status("36991", data))
def test_unassigned_ticket_fails(self):
for status in ["new", "closed", ""]:
with self.subTest(status=status):
data = make_trac_json(stage="Accepted", status=status, resolution="")
self.assertIsNotNone(check_pr.check_trac_status("36991", data))
def test_failure_message_contains_ticket_id(self):
data = make_trac_json(stage="Unreviewed")
result = check_pr.check_trac_status("12345", data)
self.assertIsInstance(result, Message)
self.assertEqual(result.kwargs["ticket_id"], "12345")
def test_failure_message_contains_current_state(self):
data = make_trac_json(stage="Unreviewed", status="new", resolution="duplicate")
result = check_pr.check_trac_status("36991", data)
self.assertIsInstance(result, Message)
self.assertIn("stage='Unreviewed'", result.kwargs["current_state"])
self.assertIn("resolution='duplicate'", result.kwargs["current_state"])
self.assertIn("status='new'", result.kwargs["current_state"])
def test_ticket_not_found_current_state(self):
result = check_pr.check_trac_status("99999", check_pr.TICKET_NOT_FOUND)
self.assertIsInstance(result, Message)
self.assertIn("not found", result.kwargs["current_state"])
def test_none_data_skips_check(self):
self.assertIsNone(check_pr.check_trac_status("36991", None))
class TestCheckTracHasPatch(BaseTestCase):
def test_already_set_passes(self):
data = make_trac_json(has_patch="1")
self.assertIsNone(check_pr.check_trac_has_patch("36991", data))
def test_not_set_times_out_fails(self):
data = make_trac_json(has_patch="0")
result = check_pr.check_trac_has_patch(
"36991", data, poll_timeout=0, poll_interval=0
)
self.assertIsNotNone(result)
def test_failure_message_contains_ticket_id(self):
data = make_trac_json(ticket_id="36991", has_patch="0")
result = check_pr.check_trac_has_patch(
"36991", data, poll_timeout=0, poll_interval=0
)
self.assertIsInstance(result, Message)
self.assertEqual(result.kwargs["ticket_id"], "36991")
def test_set_on_second_poll_passes(self):
initial = make_trac_json(has_patch="0")
second = make_trac_json(has_patch="1")
with (
mock.patch.object(check_pr, "fetch_trac_ticket", return_value=second),
mock.patch("time.sleep"),
):
self.assertIsNone(
check_pr.check_trac_has_patch(
"36991", initial, poll_timeout=60, poll_interval=0
)
)
def test_none_data_skips_check(self):
self.assertIsNone(check_pr.check_trac_has_patch("36991", None))
def test_ticket_not_found_skips_check(self):
# Ticket not found -- already reported by check_trac_status.
self.assertIsNone(
check_pr.check_trac_has_patch("36991", check_pr.TICKET_NOT_FOUND)
)
def test_fetch_error_during_poll_skips_check(self):
initial = make_trac_json(has_patch="0")
with (
mock.patch.object(check_pr, "fetch_trac_ticket", return_value=None),
mock.patch("time.sleep"),
):
self.assertIsNone(
check_pr.check_trac_has_patch(
"36991", initial, poll_timeout=60, poll_interval=0
)
)
class TestCheckPrTitleHasTicket(BaseTestCase):
def test_ticket_in_title_passes(self):
self.assertIsNone(
check_pr.check_pr_title_has_ticket("Fixed #36991 -- Fix bug.", "36991")
)
def test_refs_format_passes(self):
self.assertIsNone(
check_pr.check_pr_title_has_ticket("Refs #36991 -- Add tests.", "36991")
)
def test_ticket_missing_from_title_fails(self):
self.assertIsNotNone(
check_pr.check_pr_title_has_ticket("Fix template rendering bug.", "36991")
)
def test_empty_title_fails(self):
self.assertIsNotNone(check_pr.check_pr_title_has_ticket("", "36991"))
def test_wrong_ticket_number_fails(self):
self.assertIsNotNone(
check_pr.check_pr_title_has_ticket("Fixed #11111 -- Fix bug.", "36991")
)
def test_failure_message_contains_ticket_id(self):
result = check_pr.check_pr_title_has_ticket("Fix something.", "36991")
self.assertIsInstance(result, Message)
self.assertEqual(result.kwargs["ticket_id"], "36991")
class TestCheckBranchDescription(BaseTestCase):
def test_valid_passes(self):
self.assertIsNone(check_pr.check_branch_description(VALID_PR_BODY))
def test_placeholder_fails(self):
body = make_pr_body(
description=(
"Provide a concise overview of the issue or rationale behind"
" the proposed changes."
)
)
self.assertIsNotNone(check_pr.check_branch_description(body))
def test_placeholder_with_appended_text_fails(self):
body = make_pr_body(
description=(
"Provide a concise overview of the issue or rationale behind"
" the proposed changes. Yes."
)
)
self.assertIsNotNone(check_pr.check_branch_description(body))
def test_empty_fails(self):
body = make_pr_body(description="")
self.assertIsNotNone(check_pr.check_branch_description(body))
def test_too_short_fails(self):
body = make_pr_body(description="Fix bug.")
self.assertIsNotNone(check_pr.check_branch_description(body))
def test_exactly_five_words_passes(self):
body = make_pr_body(description="Fix the template rendering bug.")
self.assertIsNone(check_pr.check_branch_description(body))
def test_html_comment_only_fails(self):
body = make_pr_body(
description="<!-- Provide a concise overview of the issue -->"
)
self.assertIsNotNone(check_pr.check_branch_description(body))
def test_html_comment_words_not_counted(self):
body = make_pr_body(description="<!-- this has five words --> fix")
self.assertIsNotNone(check_pr.check_branch_description(body))
def test_missing_section_header_fails(self):
body = VALID_PR_BODY.replace("#### Branch description\n", "")
self.assertIsNotNone(check_pr.check_branch_description(body))
def test_multiline_passes(self):
body = make_pr_body(
description=(
"This PR fixes a bug in the ORM.\n"
"The issue affects queries with multiple joins."
)
)
self.assertIsNone(check_pr.check_branch_description(body))
def test_crlf_line_endings_pass(self):
body = make_pr_body().replace("\n", "\r\n")
self.assertIsNone(check_pr.check_branch_description(body))
class TestCheckAIDisclosure(BaseTestCase):
def test_no_ai_checked_passes(self):
self.assertIsNone(check_pr.check_ai_disclosure(VALID_PR_BODY))
def test_ai_used_with_description_passes(self):
body = make_pr_body(
no_ai_checked=False,
ai_used_checked=True,
ai_description=(
"Used GitHub Copilot for autocomplete, all output manually reviewed."
),
)
self.assertIsNone(check_pr.check_ai_disclosure(body))
def test_neither_option_checked_fails(self):
body = make_pr_body(no_ai_checked=False, ai_used_checked=False)
self.assertIsNotNone(check_pr.check_ai_disclosure(body))
def test_both_options_checked_fails(self):
body = make_pr_body(no_ai_checked=True, ai_used_checked=True)
self.assertIsNotNone(check_pr.check_ai_disclosure(body))
def test_ai_used_no_description_fails(self):
body = make_pr_body(
no_ai_checked=False, ai_used_checked=True, ai_description=""
)
self.assertIsNotNone(check_pr.check_ai_disclosure(body))
def test_ai_used_short_description_fails(self):
body = make_pr_body(
no_ai_checked=False, ai_used_checked=True, ai_description="Used Copilot."
)
self.assertIsNotNone(check_pr.check_ai_disclosure(body))
def test_ai_used_exactly_five_word_description_passes(self):
body = make_pr_body(
no_ai_checked=False,
ai_used_checked=True,
ai_description="Used Claude for code review.",
)
self.assertIsNone(check_pr.check_ai_disclosure(body))
def test_missing_section_fails(self):
body = VALID_PR_BODY.replace("#### AI Assistance Disclosure (REQUIRED)\n", "")
self.assertIsNotNone(check_pr.check_ai_disclosure(body))
def test_uppercase_x_in_checkbox_passes(self):
body = VALID_PR_BODY.replace(
"- [x] **No AI tools were used**", "- [X] **No AI tools were used**"
)
self.assertIsNone(check_pr.check_ai_disclosure(body))
def test_commented_out_checkbox_not_counted(self):
body = make_pr_body(no_ai_checked=False, ai_used_checked=False)
body = body.replace(
"- [ ] **No AI tools were used**",
"<!-- - [x] No AI tools were used -->\n- [ ] **No AI tools were used**",
)
self.assertIsNotNone(check_pr.check_ai_disclosure(body))
class TestStripHtmlComments(BaseTestCase):
def test_removes_single_line_comment(self):
self.assertEqual(
check_pr.strip_html_comments("hello <!-- comment --> world"), "hello world"
)
def test_removes_multiline_comment(self):
self.assertEqual(
check_pr.strip_html_comments("before\n<!-- line one\nline two\n-->\nafter"),
"before\n\nafter",
)
def test_no_comment_unchanged(self):
self.assertEqual(
check_pr.strip_html_comments("no comments here"), "no comments here"
)
def test_empty_string(self):
self.assertEqual(check_pr.strip_html_comments(""), "")
def test_removes_multiple_comments(self):
self.assertEqual(
check_pr.strip_html_comments("a <!-- x --> b <!-- y --> c"),
"a b c",
)
class TestCheckChecklist(BaseTestCase):
def test_first_five_checked_passes(self):
self.assertIsNone(check_pr.check_checklist(VALID_PR_BODY))
def test_all_nine_checked_passes(self):
body = make_pr_body(checked_items=9)
self.assertIsNone(check_pr.check_checklist(body))
def test_none_checked_fails(self):
body = make_pr_body(checked_items=0)
self.assertIsNotNone(check_pr.check_checklist(body))
def test_four_of_five_checked_fails(self):
body = make_pr_body(checked_items=4)
self.assertIsNotNone(check_pr.check_checklist(body))
def test_three_of_five_checked_fails(self):
body = make_pr_body(checked_items=3)
self.assertIsNotNone(check_pr.check_checklist(body))
def test_missing_section_fails(self):
body = VALID_PR_BODY.replace("#### Checklist\n", "")
self.assertIsNotNone(check_pr.check_checklist(body))
def test_uppercase_x_passes(self):
body = VALID_PR_BODY.replace("- [x]", "- [X]")
self.assertIsNone(check_pr.check_checklist(body))
def test_crlf_line_endings_pass(self):
body = make_pr_body().replace("\n", "\r\n")
self.assertIsNone(check_pr.check_checklist(body))
class TestIntegration(BaseTestCase):
def test_fully_valid_pr_passes_all_checks(self):
data = make_trac_json(stage="Accepted", has_patch="1")
for label, body in [
("LF line endings", VALID_PR_BODY),
("CRLF line endings", VALID_PR_BODY.replace("\n", "\r\n")),
]:
with self.subTest(label=label):
ticket_id = check_pr.extract_ticket_id(body)
results = [
check_pr.check_trac_ticket(body, check_pr.LARGE_PR_THRESHOLD),
check_pr.check_trac_status(ticket_id, data),
check_pr.check_trac_has_patch(ticket_id, data),
check_pr.check_pr_title_has_ticket(VALID_PR_TITLE, ticket_id),
check_pr.check_branch_description(body),
check_pr.check_ai_disclosure(body),
check_pr.check_checklist(body),
]
failures = [r for r in results if r is not None]
self.assertEqual(
failures,
[],
f"Expected no failures ({label}), got: {failures!r}",
)
def test_blank_body_fails_non_status_checks(self):
results = [
check_pr.check_trac_ticket("", check_pr.LARGE_PR_THRESHOLD),
check_pr.check_branch_description(""),
check_pr.check_ai_disclosure(""),
check_pr.check_checklist(""),
]
for i, result in enumerate(results, 1):
self.assertIsNotNone(result, f"Check {i} should have failed on empty body")
def test_make_pr_body_matches_template(self):
template_path = (
Path(__file__).parents[3] / ".github" / "pull_request_template.md"
)
with open(template_path) as f:
raw_template = f.read()
blank_body = make_pr_body(
ticket="ticket-XXXXX",
description=(
"Provide a concise overview of the issue or rationale behind"
" the proposed changes."
),
no_ai_checked=False,
ai_used_checked=False,
checked_items=0,
)
self.assertEqual(blank_body, raw_template)
def test_unedited_template_fails_all_checks(self):
template_path = (
Path(__file__).parents[3] / ".github" / "pull_request_template.md"
)
with open(template_path) as f:
raw_template = f.read()
results = [
check_pr.check_trac_ticket(raw_template, check_pr.LARGE_PR_THRESHOLD),
check_pr.check_branch_description(raw_template),
check_pr.check_ai_disclosure(raw_template),
check_pr.check_checklist(raw_template),
]
for i, result in enumerate(results, 1):
self.assertIsNotNone(
result, f"Check {i} should have failed on raw template"
)
def test_pr_before_template_date_skips_all_checks(self):
with self.assertLogs(logger, level="INFO") as logs:
result, _, mock_gh = self.call_main(
pr_body=make_pr_body(ticket="", checked_items=0),
pr_created_at="2024-01-01T00:00:00Z",
)
self.assertIsNone(result)
mock_gh.assert_not_called()
self.assertIn("older than PR template", "\n".join(logs.output))
def test_pr_before_ai_disclosure_date_skips_ai_check(self):
body = make_pr_body(no_ai_checked=False, ai_used_checked=False)
with self.assertLogs(logger, level="INFO") as logs:
_, mock_summary, _ = self.call_main(
pr_body=body,
pr_title=VALID_PR_TITLE,
pr_created_at="2025-01-01T00:00:00Z",
)
_, results, _ = mock_summary.call_args.args
result_map = {name: result for name, result, _ in results}
self.assertIs(result_map["AI disclosure completed"], check_pr.SKIPPED)
self.assertIn("older than AI Disclosure", "\n".join(logs.output))
def test_no_ticket_skips_trac_status_and_has_patch(self):
with self.assertLogs(logger, level="INFO") as logs:
self.call_main(pr_body="")
self.assertIn(
"No Trac ticket -- skipping status and has_patch checks.",
"\n".join(logs.output),
)
def test_no_ticket_results_include_skipped_sentinels(self):
body = make_pr_body(ticket="")
_, mock_summary, _ = self.call_main(pr_body=body)
_, results, _ = mock_summary.call_args.args
result_map = {name: result for name, result, _ in results}
self.assertIs(result_map["Trac ticket status is Accepted"], check_pr.SKIPPED)
self.assertIs(result_map["Trac ticket has_patch flag set"], check_pr.SKIPPED)
self.assertIs(result_map["PR title includes ticket number"], check_pr.SKIPPED)
def test_non_accepted_ticket_skips_has_patch(self):
data = make_trac_json(stage="Unreviewed")
_, mock_summary, _ = self.call_main(
pr_body=VALID_PR_BODY, pr_title=VALID_PR_TITLE, trac_data=data
)
_, results, _ = mock_summary.call_args.args
result_map = {name: result for name, result, _ in results}
self.assertIsNotNone(result_map["Trac ticket status is Accepted"])
self.assertIs(result_map["Trac ticket has_patch flag set"], check_pr.SKIPPED)
def test_established_author_skips_all_checks(self):
body = make_pr_body(ticket="", checked_items=0)
result, _, mock_gh = self.call_main(pr_body=body, commit_count=5)
self.assertIsNone(result)
mock_gh.assert_not_called()
def test_fully_valid_pr_no_comment_posted(self):
result, _, mock_gh = self.call_main(
pr_body=VALID_PR_BODY, pr_title=VALID_PR_TITLE
)
self.assertIsNone(result)
mock_gh.assert_not_called()
def test_trusted_author_failures_no_close(self):
body = make_pr_body(ticket="", checked_items=0)
result, _, mock_gh = self.call_main(pr_body=body, commit_count=1)
self.assertEqual(result, 1)
mock_gh.assert_called_once_with(
"POST", "/issues/10/comments", "test-token", "test/repo", mock.ANY
)
def test_untrusted_author_failures_posts_comment_and_closes(self):
body = make_pr_body(ticket="", checked_items=0)
result, _, mock_gh = self.call_main(pr_body=body)
self.assertEqual(result, 1)
self.assertEqual(
mock_gh.mock_calls,
[
mock.call(
"POST", "/issues/10/comments", "test-token", "test/repo", mock.ANY
),
mock.call(
"PATCH", "/pulls/10", "test-token", "test/repo", {"state": "closed"}
),
],
)
def test_missing_pr_author_treated_as_untrusted(self):
body = make_pr_body(ticket="", checked_items=0)
result, _, mock_gh = self.call_main(pr_body=body, pr_author="")
self.assertEqual(result, 1)
self.assertEqual(
mock_gh.mock_calls,
[
mock.call(
"POST", "/issues/10/comments", "test-token", "test/repo", mock.ANY
),
mock.call(
"PATCH", "/pulls/10", "test-token", "test/repo", {"state": "closed"}
),
],
)
def test_autoclose_false_posts_comment_does_not_close(self):
body = make_pr_body(ticket="", checked_items=0)
result, _, mock_gh = self.call_main(pr_body=body, autoclose=False)
self.assertEqual(result, 1)
mock_gh.assert_called_once_with(
"POST", "/issues/10/comments", "test-token", "test/repo", mock.ANY
)
def test_warnings_only_posts_comment_does_not_close(self):
trac_data = make_trac_json(stage="Accepted", has_patch="0")
# pr_title="" triggers title warning.
# has_patch="0" triggers has_patch warning.
result, _, mock_gh = self.call_main(
pr_body=VALID_PR_BODY, pr_title="", trac_data=trac_data
)
self.assertIsNone(result)
mock_gh.assert_called_once_with(
"POST", "/issues/10/comments", "test-token", "test/repo", mock.ANY
)
def test_warnings_alongside_failures_still_closes(self):
trac_data = make_trac_json(stage="Accepted", has_patch="0")
# Empty body: fatal ticket failure + incorrect title warning.
body = make_pr_body(ticket="", checked_items=0)
result, _, mock_gh = self.call_main(pr_body=body, trac_data=trac_data)
self.assertEqual(result, 1)
self.assertEqual(
mock_gh.mock_calls,
[
mock.call(
"POST", "/issues/10/comments", "test-token", "test/repo", mock.ANY
),
mock.call(
"PATCH", "/pulls/10", "test-token", "test/repo", {"state": "closed"}
),
],
)
class TestWriteJobSummary(BaseTestCase):
def test_no_summary_file_does_nothing(self):
check_pr.write_job_summary(
"99",
[
("Some check", None, LEVEL_ERROR),
("Other check", "failure", LEVEL_ERROR),
],
)
def test_all_passed(self):
with tempfile.TemporaryDirectory() as tmpdir:
summary = Path(tmpdir) / "summary.md"
results = [
("Trac ticket referenced", None, LEVEL_ERROR),
("Branch description provided", None, LEVEL_ERROR),
]
check_pr.write_job_summary("7", results, str(summary))
content = summary.read_text()
self.assertIn("## PR #7 Quality Check Results", content)
self.assertIn("✅", content)
self.assertNotIn(ERROR_ICON, content)
self.assertIn("Trac ticket referenced", content)
self.assertIn("Branch description provided", content)
def test_with_failures(self):
with tempfile.TemporaryDirectory() as tmpdir:
summary = Path(tmpdir) / "summary.md"
results = [
("Trac ticket referenced", None, LEVEL_ERROR),
("Branch description provided", "Missing description", LEVEL_ERROR),
("Checklist completed", "Incomplete checklist", LEVEL_ERROR),
]
check_pr.write_job_summary("12", results, str(summary))
content = summary.read_text()
self.assertIn("## PR #12 Quality Check Results", content)
self.assertEqual(content.count("✅"), 1)
self.assertEqual(content.count(ERROR_ICON), 2)
self.assertIn("Passed", content)
self.assertIn(ERROR_LABEL, content)
def test_with_warning(self):
with tempfile.TemporaryDirectory() as tmpdir:
summary = Path(tmpdir) / "summary.md"
results = [
("Trac ticket referenced", None, LEVEL_ERROR),
("Trac ticket has_patch flag set", "No patch", LEVEL_WARNING),
]
check_pr.write_job_summary("8", results, str(summary))
content = summary.read_text()
self.assertIn("✅", content)
self.assertIn(WARNING_ICON, content)
self.assertIn(WARNING_LABEL, content)
self.assertNotIn(ERROR_ICON, content)
def test_appends_to_existing_file(self):
with tempfile.TemporaryDirectory() as tmpdir:
summary = Path(tmpdir) / "summary.md"
summary.write_text("## Previous step\n\nSome content.\n")
check_pr.write_job_summary(
"5", [("Checklist completed", None, LEVEL_ERROR)], str(summary)
)
content = summary.read_text()
self.assertIn("## Previous step", content)
self.assertIn("## PR #5 Quality Check Results", content)
def test_skipped_checks(self):
with tempfile.TemporaryDirectory() as tmpdir:
summary = Path(tmpdir) / "summary.md"
results = [
(
"Trac ticket referenced",
Message(*MISSING_TRAC_TICKET, threshold=80),
LEVEL_ERROR,
),
("Trac ticket status is Accepted", check_pr.SKIPPED, LEVEL_ERROR),
("Trac ticket has_patch flag set", check_pr.SKIPPED, LEVEL_WARNING),
]
check_pr.write_job_summary("3", results, str(summary))
content = summary.read_text()
self.assertEqual(content.count("⏭️"), 2)
self.assertEqual(content.count("Skipped"), 2)
self.assertIn(ERROR_ICON, content)
class TestGetRecentCommitCount(BaseTestCase):
def _make_github_request_mock(self, commits):
return mock.patch.object(check_pr, "github_request", return_value=commits)
def test_returns_number_of_commits(self):
commits = [{"sha": "abc"}, {"sha": "def"}, {"sha": "ghi"}]
with self._make_github_request_mock(commits):
self.assertEqual(
check_pr.get_recent_commit_count(
"someuser", "django/django", "token", since_days=365, max_count=5
),
3,
)
def test_no_commits_returns_zero(self):
with self._make_github_request_mock([]):
self.assertEqual(
check_pr.get_recent_commit_count(
"newuser", "django/django", "token", since_days=365, max_count=5
),
0,
)
def test_api_path_includes_author_since_and_max_count(self):
with mock.patch.object(check_pr, "github_request", return_value=[]) as mock_gh:
check_pr.get_recent_commit_count(
"someuser", "django/django", "token", since_days=365, max_count=5
)
params = mock_gh.call_args.kwargs["params"]
self.assertEqual(params["author"], "someuser")
self.assertIn("since", params)
self.assertEqual(params["per_page"], 5)
|