-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain_test.py
More file actions
2918 lines (2592 loc) · 119 KB
/
Copy pathmain_test.py
File metadata and controls
2918 lines (2592 loc) · 119 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
"""Unit tests for main.py."""
import importlib.metadata
import io
import json
import os
import re
import shutil
import sys
import tempfile
import unittest
from unittest.mock import MagicMock, patch
os.environ.setdefault("GITHUB_STEP_SUMMARY", "/tmp/step_summary.txt")
import main # noqa: E402
#: The report footer names the installed commit-check version, which differs
#: between a contributor's machine and CI. Golden tests pin it so they assert on
#: the report layout rather than on whatever version happens to be installed.
PINNED_VERSION = "2.13.1"
FOOTER = (
f"_commit-check {PINNED_VERSION} · "
"[Rules reference](https://commit-check.com/rules/)_"
)
pin_version = patch("main._commit_check_version", new=lambda: PINNED_VERSION)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def make_check(
check: str,
status: str = "pass",
rule_id: str = "CC001",
value: str = "",
error: str = "",
suggest: str = "",
fix: str = "",
docs_url: str = "",
) -> dict[str, str]:
"""Build a single check outcome dict as produced by commit-check JSON."""
return {
"rule_id": rule_id,
"check": check,
"status": status,
"value": value,
"error": error,
"suggest": suggest,
"fix": fix,
"docs_url": docs_url,
}
#: Full hashes for scopes that carry a commit; the first seven characters
#: are what a reader sees.
SHA_A = "d87faca811e7017bbaa82f5c53eade0a97c108d8"
SHA_B = "5584f462cc3c947b2ba8d3d1a5735571803ee159"
#: ``git log`` output in COMMIT_LOG_FORMAT for two commits: hash, NUL, message
#: (with its trailing newline), NUL, then git's own newline before the next.
TWO_COMMITS_LOG = f"{SHA_A}\x00fix: first\n\x00\n{SHA_B}\x00feat: second\n\x00"
def json_output(*checks) -> str:
"""Serialize checks to the CLI JSON output shape."""
status = "fail" if any(c["status"] == "fail" for c in checks) else "pass"
return json.dumps({"status": status, "checks": list(checks)})
def pass_scope(label: str = "Branch", value: str = "") -> main.ScopeResult:
return main.ScopeResult(label=label, checks=[make_check("branch", value=value)])
def fail_scope(label: str = "Commit 1/1", sha: str = "") -> main.ScopeResult:
return main.ScopeResult(
label=label,
sha=sha,
checks=[
make_check(
"message",
status="fail",
rule_id="CC001",
value="bad message",
error="The commit message should follow Conventional Commits.",
suggest="Use <type>(<scope>): <description>",
docs_url="https://commit-check.com/rules/#cc001",
)
],
)
def fix_scope(label: str = "Commit 2/3", sha: str = SHA_B) -> main.ScopeResult:
"""A CC002 failure as commit-check 2.17 reports it: a mechanical fix, and
a ``suggest`` the engine derived from that same fix."""
return main.ScopeResult(
label=label,
sha=sha,
checks=[
make_check(
"subject_capitalized",
status="fail",
rule_id="CC002",
value="feat: add login page",
error="Subject must start with a capital letter",
suggest='Use "feat: Add login page"',
fix="feat: Add login page",
docs_url="https://commit-check.com/rules/#cc002",
)
],
)
class TestEnvFlag(unittest.TestCase):
def test_true_value(self):
with patch.dict(os.environ, {"FEATURE_FLAG": "true"}):
self.assertTrue(main.env_flag("FEATURE_FLAG"))
def test_false_value(self):
with patch.dict(os.environ, {"FEATURE_FLAG": "false"}):
self.assertFalse(main.env_flag("FEATURE_FLAG"))
def test_missing_uses_default(self):
with patch.dict(os.environ, {}, clear=True):
self.assertTrue(main.env_flag("FEATURE_FLAG", default="true"))
class TestReconfigureIo(unittest.TestCase):
def test_reconfigures_streams_to_utf8(self):
class FakeStream:
def __init__(self):
self.reconfigured = None
def reconfigure(self, **kwargs):
self.reconfigured = kwargs
fake_out = FakeStream()
fake_err = FakeStream()
with (
patch.object(sys, "stdout", fake_out),
patch.object(sys, "stderr", fake_err),
):
main._reconfigure_io()
self.assertEqual(
fake_out.reconfigured, {"encoding": "utf-8", "errors": "replace"}
)
self.assertEqual(
fake_err.reconfigured, {"encoding": "utf-8", "errors": "replace"}
)
def test_streams_without_reconfigure_are_ignored(self):
class NoopStream:
pass
with (
patch.object(sys, "stdout", NoopStream()),
patch.object(sys, "stderr", NoopStream()),
):
main._reconfigure_io() # should not raise
class TestBuildCheckArgs(unittest.TestCase):
def test_all_true(self):
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", True),
patch("main.AUTHOR_NAME_ENABLED", True),
patch("main.AUTHOR_EMAIL_ENABLED", True),
):
result = main.build_check_args()
self.assertEqual(
result, ["--message", "--branch", "--author-name", "--author-email"]
)
def test_all_false(self):
with (
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
):
result = main.build_check_args()
self.assertEqual(result, [])
def test_message_and_branch(self):
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", True),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
):
result = main.build_check_args()
self.assertEqual(result, ["--message", "--branch"])
class TestParseCommitMessages(unittest.TestCase):
def test_splits_messages_and_trims_surrounding_newlines(self):
result = main.parse_commit_messages(
f"{SHA_A}\x00\nfix: first\n\x00\n{SHA_B}\x00\nfeat: second\n\n\x00"
)
self.assertEqual(result, [(SHA_A, "fix: first"), (SHA_B, "feat: second")])
def test_real_git_log_layout(self):
self.assertEqual(
main.parse_commit_messages(TWO_COMMITS_LOG),
[(SHA_A, "fix: first"), (SHA_B, "feat: second")],
)
def test_the_format_asks_git_for_the_hash_and_the_body(self):
"""A literal NUL cannot be an argument; git spells it %x00."""
self.assertEqual(main.COMMIT_LOG_FORMAT, "--pretty=format:%H%x00%B%x00")
self.assertNotIn("\x00", main.COMMIT_LOG_FORMAT)
def test_an_empty_message_does_not_shift_the_hashes_after_it(self):
output = f"{SHA_A}\x00\n\x00\n{SHA_B}\x00feat: second\n\x00"
self.assertEqual(main.parse_commit_messages(output), [(SHA_B, "feat: second")])
def test_empty_output_is_no_commits(self):
self.assertEqual(main.parse_commit_messages(""), [])
class TestGetPrTitle(unittest.TestCase):
def test_non_pr_event_returns_none(self):
with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "push"}):
self.assertIsNone(main.get_pr_title())
def test_pr_event_returns_title(self):
event = {
"pull_request": {"title": "feat: add login page"},
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(event, f)
event_path = f.name
with (
patch.dict(
os.environ,
{"GITHUB_EVENT_NAME": "pull_request", "GITHUB_EVENT_PATH": event_path},
),
):
self.assertEqual(main.get_pr_title(), "feat: add login page")
os.unlink(event_path)
def test_pull_request_target_event(self):
event = {
"pull_request": {"title": "fix: resolve timeout"},
}
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
json.dump(event, f)
event_path = f.name
with (
patch.dict(
os.environ,
{
"GITHUB_EVENT_NAME": "pull_request_target",
"GITHUB_EVENT_PATH": event_path,
},
),
):
self.assertEqual(main.get_pr_title(), "fix: resolve timeout")
os.unlink(event_path)
def test_missing_event_path_returns_none(self):
with patch.dict(os.environ, {}, clear=True):
os.environ["GITHUB_EVENT_NAME"] = "pull_request"
os.environ.pop("GITHUB_EVENT_PATH", None)
self.assertIsNone(main.get_pr_title())
def test_invalid_json_returns_none(self):
with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
f.write("not valid json")
event_path = f.name
with (
patch.dict(
os.environ,
{"GITHUB_EVENT_NAME": "pull_request", "GITHUB_EVENT_PATH": event_path},
),
patch("builtins.print"),
):
self.assertIsNone(main.get_pr_title())
os.unlink(event_path)
class TestRunCheckJson(unittest.TestCase):
def test_parses_json_output(self):
mock_result = MagicMock(returncode=0, stdout=json_output(make_check("branch")))
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
rc, data, raw = main.run_check_json(["--branch"])
self.assertEqual(rc, 0)
self.assertEqual(data["status"], "pass")
self.assertEqual(len(data["checks"]), 1)
self.assertIn("checks", raw)
def test_command_includes_format_json(self):
mock_result = MagicMock(returncode=0, stdout="{}")
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
main.run_check_json(["--branch"])
self.assertEqual(
mock_run.call_args[0][0],
["commit-check", "--format", "json", "--branch"],
)
def test_input_text_is_passed_through(self):
mock_result = MagicMock(returncode=0, stdout="{}")
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
main.run_check_json(["--message"], input_text="fix: demo")
self.assertEqual(mock_run.call_args[1]["input"], "fix: demo")
self.assertTrue(mock_run.call_args[1]["text"])
def test_invalid_json_returns_none_with_raw_output(self):
mock_result = MagicMock(returncode=1, stdout="Commit rejected.\n", stderr="")
with patch("main.subprocess.run", return_value=mock_result):
rc, data, raw = main.run_check_json(["--branch"])
self.assertEqual(rc, 1)
self.assertIsNone(data)
self.assertEqual(raw, "Commit rejected.\n")
class TestScopeResult(unittest.TestCase):
def test_status_pass_when_all_checks_pass(self):
scope = main.ScopeResult(
label="Branch", checks=[make_check("branch"), make_check("merge_base")]
)
self.assertEqual(scope.status, "pass")
self.assertEqual(scope.failures, [])
def test_status_fail_when_any_check_fails(self):
scope = main.ScopeResult(
label="Branch",
checks=[
make_check("branch", status="fail"),
make_check("merge_base"),
],
)
self.assertEqual(scope.status, "fail")
self.assertEqual(len(scope.failures), 1)
def test_raw_text_fallback_is_failure(self):
scope = main.ScopeResult(label="Branch", raw_text="unexpected output")
self.assertEqual(scope.status, "fail")
class TestCheckScope(unittest.TestCase):
def test_parses_checks_into_scope(self):
mock_result = MagicMock(
returncode=1, stdout=json_output(make_check("branch", status="fail"))
)
with patch("main.subprocess.run", return_value=mock_result):
scope = main.check_scope("Branch", ["--branch"])
self.assertEqual(scope.label, "Branch")
self.assertEqual(scope.status, "fail")
self.assertEqual(scope.failures[0]["rule_id"], "CC001")
def test_invalid_json_falls_back_to_raw_text(self):
mock_result = MagicMock(returncode=1, stdout="unexpected output", stderr="")
with patch("main.subprocess.run", return_value=mock_result):
scope = main.check_scope("Branch", ["--branch"])
self.assertEqual(scope.label, "Branch")
self.assertEqual(scope.raw_text, "unexpected output")
self.assertEqual(scope.status, "fail")
class TestRunPrMessageChecks(unittest.TestCase):
def test_single_message_pass(self):
mock_result = MagicMock(returncode=0, stdout=json_output(make_check("message")))
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
scopes = main.run_pr_message_checks([(SHA_A, "fix: something")])
self.assertEqual(len(scopes), 1)
self.assertEqual(scopes[0].status, "pass")
self.assertEqual(scopes[0].label, "Commit 1/1")
self.assertEqual(scopes[0].sha, SHA_A)
self.assertEqual(scopes[0].display_label, "Commit 1/1 (d87faca)")
self.assertEqual(
mock_run.call_args[0][0],
["commit-check", "--format", "json", "--message"],
)
self.assertEqual(mock_run.call_args[1]["input"], "fix: something")
def test_failed_message_marks_scope_failed(self):
mock_result = MagicMock(
returncode=1,
stdout=json_output(make_check("message", status="fail")),
)
with patch("main.subprocess.run", return_value=mock_result):
scopes = main.run_pr_message_checks([(SHA_A, "bad commit")])
self.assertEqual(scopes[0].status, "fail")
self.assertEqual(len(scopes[0].failures), 1)
self.assertEqual(scopes[0].sha, SHA_A)
def test_unparsable_output_still_names_the_commit(self):
mock_result = MagicMock(returncode=1, stdout="unexpected output", stderr="")
with patch("main.subprocess.run", return_value=mock_result):
scopes = main.run_pr_message_checks([(SHA_A, "bad commit")])
self.assertEqual(scopes[0].raw_text, "unexpected output")
self.assertEqual(scopes[0].sha, SHA_A)
def test_labels_commits_in_order(self):
results = [
MagicMock(returncode=0, stdout=json_output(make_check("message"))),
MagicMock(
returncode=1,
stdout=json_output(make_check("message", status="fail")),
),
MagicMock(returncode=0, stdout=json_output(make_check("message"))),
]
with patch("main.subprocess.run", side_effect=results):
scopes = main.run_pr_message_checks(
[("a" * 40, "ok"), ("b" * 40, "bad"), ("c" * 40, "ok")]
)
# The label stays the bare index for the ``result`` output; the hash
# is appended only where a person reads it.
self.assertEqual(
[s.label for s in scopes], ["Commit 1/3", "Commit 2/3", "Commit 3/3"]
)
self.assertEqual([s.sha for s in scopes], ["a" * 40, "b" * 40, "c" * 40])
self.assertEqual(scopes[1].status, "fail")
def test_empty_list(self):
with patch("main.subprocess.run") as mock_run:
scopes = main.run_pr_message_checks([])
self.assertEqual(scopes, [])
mock_run.assert_not_called()
class TestRunOtherChecks(unittest.TestCase):
def test_empty_args_returns_no_scopes(self):
with patch("main.subprocess.run") as mock_run:
scopes = main.run_other_checks([])
self.assertEqual(scopes, [])
mock_run.assert_not_called()
def test_runs_each_flag_as_its_own_scope(self):
results = [
MagicMock(
returncode=1, stdout=json_output(make_check("branch", status="fail"))
),
MagicMock(returncode=0, stdout=json_output(make_check("author_name"))),
]
with patch("main.subprocess.run", side_effect=results) as mock_run:
scopes = main.run_other_checks(["--branch", "--author-name"])
self.assertEqual([s.label for s in scopes], ["Branch", "Author name"])
self.assertEqual(scopes[0].status, "fail")
self.assertEqual(scopes[1].status, "pass")
self.assertEqual(
mock_run.call_args_list[0][0][0],
["commit-check", "--format", "json", "--branch"],
)
self.assertEqual(
mock_run.call_args_list[1][0][0],
["commit-check", "--format", "json", "--author-name"],
)
def test_unknown_flag_is_skipped(self):
with patch("main.subprocess.run") as mock_run:
scopes = main.run_other_checks(["--unknown"])
self.assertEqual(scopes, [])
mock_run.assert_not_called()
class TestGetPrCommitMessages(unittest.TestCase):
def test_non_pr_event_returns_empty(self):
with patch.dict(os.environ, {"GITHUB_EVENT_NAME": "push"}):
result = main.get_pr_commit_messages()
self.assertEqual(result, [])
def test_event_range_is_preferred(self):
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}),
patch(
"main.get_messages_from_event_range",
return_value=["fix: first", "feat: second"],
) as mock_range,
patch("main.get_messages_from_merge_ref") as mock_merge,
patch("main.get_messages_from_head_ref") as mock_head,
):
result = main.get_pr_commit_messages()
self.assertEqual(result, ["fix: first", "feat: second"])
mock_range.assert_called_once()
mock_merge.assert_not_called()
mock_head.assert_not_called()
def test_merge_ref_is_next(self):
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}),
patch("main.get_messages_from_event_range", return_value=[]),
patch(
"main.get_messages_from_merge_ref",
return_value=["fix: first", "feat: second"],
) as mock_merge,
patch("main.get_messages_from_head_ref") as mock_head,
):
result = main.get_pr_commit_messages()
self.assertEqual(result, ["fix: first", "feat: second"])
mock_merge.assert_called_once()
mock_head.assert_not_called()
def test_pull_request_target_is_supported(self):
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}),
patch("main.get_messages_from_event_range", return_value=["fix: first"]),
):
result = main.get_pr_commit_messages()
self.assertEqual(result, ["fix: first"])
def test_falls_back_to_base_ref_when_merge_ref_is_unavailable(self):
with (
patch.dict(
os.environ,
{
"GITHUB_EVENT_NAME": "pull_request",
"GITHUB_BASE_REF": "main",
},
),
patch("main.get_messages_from_event_range", return_value=[]),
patch("main.get_messages_from_merge_ref", return_value=[]),
patch(
"main.get_messages_from_head_ref",
return_value=["fix: first", "feat: second"],
) as mock_head,
):
result = main.get_pr_commit_messages()
self.assertEqual(result, ["fix: first", "feat: second"])
mock_head.assert_called_once_with("main")
def test_exception_returns_empty(self):
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}),
patch(
"main.get_messages_from_event_range",
side_effect=Exception("git failed"),
),
):
result = main.get_pr_commit_messages()
self.assertEqual(result, [])
class TestGitMessageReaders(unittest.TestCase):
def test_get_messages_from_merge_ref(self):
mock_result = MagicMock(returncode=0, stdout=TWO_COMMITS_LOG)
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}),
patch("main.subprocess.run", return_value=mock_result) as mock_run,
):
result = main.get_messages_from_merge_ref()
self.assertEqual(result, [(SHA_A, "fix: first"), (SHA_B, "feat: second")])
self.assertEqual(
mock_run.call_args[0][0],
["git", "log", main.COMMIT_LOG_FORMAT, "--reverse", "HEAD^1..HEAD^2"],
)
def test_merge_ref_is_never_read_on_pull_request_target(self):
"""HEAD is the base branch there; HEAD^2 belongs to some other merge."""
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}),
patch("main.subprocess.run") as mock_run,
):
self.assertEqual(main.get_messages_from_merge_ref(), [])
mock_run.assert_not_called()
def test_get_messages_from_event_range(self):
commands: list[list[str]] = []
def run(command, **_kwargs):
commands.append(command)
if command[:2] == ["git", "rev-parse"]:
return MagicMock(returncode=0, stdout="x\n")
return MagicMock(returncode=0, stdout=TWO_COMMITS_LOG)
with (
patch("main.get_pr_base_sha", return_value="base111"),
patch("main.get_pr_head_sha", return_value="head222"),
patch("main.subprocess.run", side_effect=run),
):
result = main.get_messages_from_event_range()
self.assertEqual(result, [(SHA_A, "fix: first"), (SHA_B, "feat: second")])
self.assertIn(
["git", "log", main.COMMIT_LOG_FORMAT, "--reverse", "base111..head222"],
commands,
)
def test_event_range_needs_both_commits_in_the_clone(self):
with (
patch("main.get_pr_base_sha", return_value="base111"),
patch("main.get_pr_head_sha", return_value="head222"),
patch("main.subprocess.run", return_value=MagicMock(returncode=1)),
):
self.assertEqual(main.get_messages_from_event_range(), [])
def test_event_range_without_a_payload_is_empty(self):
with (
patch("main.get_pr_base_sha", return_value=None),
patch("main.get_pr_head_sha", return_value=None),
patch("main.subprocess.run") as mock_run,
):
self.assertEqual(main.get_messages_from_event_range(), [])
mock_run.assert_not_called()
def test_a_failing_git_log_yields_no_messages(self):
with patch("main.subprocess.run", return_value=MagicMock(returncode=128)):
self.assertEqual(main.get_messages_from_head_ref("main"), [])
def test_get_messages_from_head_ref(self):
mock_result = MagicMock(returncode=0, stdout=f"{SHA_A}\x00fix: first\n\x00")
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
result = main.get_messages_from_head_ref("main")
self.assertEqual(result, [(SHA_A, "fix: first")])
self.assertEqual(
mock_run.call_args[0][0],
[
"git",
"log",
main.COMMIT_LOG_FORMAT,
"--reverse",
"origin/main..HEAD",
],
)
class TestHeadSha(unittest.TestCase):
def test_returns_the_full_hash(self):
mock_result = MagicMock(returncode=0, stdout=f"{SHA_A}\n")
with patch("main.subprocess.run", return_value=mock_result) as mock_run:
self.assertEqual(main.head_sha(), SHA_A)
self.assertEqual(mock_run.call_args[0][0], ["git", "rev-parse", "HEAD"])
def test_no_head_is_empty(self):
with patch("main.subprocess.run", return_value=MagicMock(returncode=128)):
self.assertEqual(main.head_sha(), "")
def test_missing_git_is_empty(self):
with patch("main.subprocess.run", side_effect=OSError("no git")):
self.assertEqual(main.head_sha(), "")
class TestRunCommitCheck(unittest.TestCase):
def test_pr_path_checks_each_commit(self):
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.get_pr_commit_messages", return_value=["fix: something"]),
patch("main.run_pr_message_checks", return_value=[pass_scope()]) as mock_pr,
patch("main.run_other_checks", return_value=[]),
):
rc, results = main.run_commit_check()
self.assertEqual(rc, 0)
mock_pr.assert_called_once_with(["fix: something"])
self.assertEqual(len(results), 1)
def test_pr_path_fails_when_any_scope_fails(self):
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", True),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.get_pr_commit_messages", return_value=["bad msg"]),
patch("main.run_pr_message_checks", return_value=[fail_scope()]),
patch("main.run_other_checks", return_value=[pass_scope()]),
):
rc, results = main.run_commit_check()
self.assertEqual(rc, 1)
self.assertEqual(len(results), 2)
def test_pr_title_check_runs_when_enabled(self):
with (
patch("main.PR_TITLE_ENABLED", True),
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.is_pr_event", return_value=True),
patch("main.get_pr_title", return_value="feat: a feature"),
patch(
"main.check_scope", return_value=pass_scope("PR title")
) as mock_scope,
patch("main.run_other_checks", return_value=[]),
):
rc, results = main.run_commit_check()
self.assertEqual(rc, 0)
mock_scope.assert_called_once_with(
"PR title", ["--message"], input_text="feat: a feature"
)
def test_pr_title_failure_propagates(self):
with (
patch("main.PR_TITLE_ENABLED", True),
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.is_pr_event", return_value=True),
patch("main.get_pr_title", return_value="bad title"),
patch("main.check_scope", return_value=fail_scope("PR title")),
patch("main.run_other_checks", return_value=[]),
):
rc, results = main.run_commit_check()
self.assertEqual(rc, 1)
def test_pr_title_skipped_outside_pr_context(self):
with (
patch("main.PR_TITLE_ENABLED", True),
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.is_pr_event", return_value=False),
patch("main.get_pr_title") as mock_title,
patch("main.run_other_checks", return_value=[]),
):
rc, results = main.run_commit_check()
self.assertEqual(rc, 0)
mock_title.assert_not_called()
def test_non_pr_message_check_uses_commit_message_scope(self):
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.get_pr_commit_messages", return_value=[]),
patch("main.run_pr_message_checks") as mock_pr,
patch("main.head_sha", return_value=SHA_A),
patch(
"main.check_scope", return_value=pass_scope("Commit message")
) as mock_scope,
patch("main.run_other_checks", return_value=[]),
):
rc, results = main.run_commit_check()
self.assertEqual(rc, 0)
mock_pr.assert_not_called()
# HEAD is the commit that was checked, so the scope names it too.
mock_scope.assert_called_once_with("Commit message", ["--message"], sha=SHA_A)
def test_message_flag_removed_before_other_checks_in_pr(self):
captured_args = []
def fake_other_checks(args, rev=None):
captured_args.extend(args)
return []
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", True),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.get_pr_commit_messages", return_value=["fix: x"]),
patch("main.run_pr_message_checks", return_value=[pass_scope()]),
patch("main.run_other_checks", side_effect=fake_other_checks),
):
main.run_commit_check()
self.assertNotIn("--message", captured_args)
self.assertIn("--branch", captured_args)
SHALLOW_PR_WARNING = (
"::warning title=commit-check::Could not list the pull request's commits "
"(is actions/checkout using fetch-depth: 0?); only HEAD was checked"
)
def _run_capturing_stdout(self):
buffer = io.StringIO()
with patch("sys.stdout", buffer):
rc, results = main.run_commit_check()
return rc, results, buffer.getvalue()
def test_pr_without_enumerable_commits_warns_and_checks_head(self):
"""A shallow clone must not turn a pull request green silently.
With fetch-depth: 1 neither HEAD^1..HEAD^2 nor origin/<base>..HEAD
can be listed, and the fallback validates HEAD — the synthetic
"Merge X into Y" commit, which passes CC001 by default.
"""
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.is_pr_event", return_value=True),
patch("main.get_pr_commit_messages", return_value=[]),
patch("main.head_sha", return_value=""),
patch(
"main.check_scope", return_value=pass_scope("Commit message")
) as mock_scope,
patch("main.run_other_checks", return_value=[]),
):
rc, results, output = self._run_capturing_stdout()
self.assertEqual(rc, 0)
self.assertIn(self.SHALLOW_PR_WARNING, output)
mock_scope.assert_called_once_with("Commit message", ["--message"], sha="")
def test_push_without_pr_commits_does_not_warn(self):
with (
patch("main.MESSAGE_ENABLED", True),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", False),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch("main.is_pr_event", return_value=False),
patch("main.get_pr_commit_messages", return_value=[]),
patch("main.check_scope", return_value=pass_scope("Commit message")),
patch("main.run_other_checks", return_value=[]),
):
_rc, _results, output = self._run_capturing_stdout()
self.assertNotIn("::warning", output)
@staticmethod
def _fake_git_and_cli(resolves: bool):
"""subprocess.run stand-in: answers rev-parse and the CLI alike."""
commands: list[list[str]] = []
def run(command, **_kwargs):
commands.append(command)
if command[:2] == ["git", "rev-parse"]:
return MagicMock(
returncode=0 if resolves else 1,
stdout="abc123\n" if resolves else "",
)
check = command[3].lstrip("-").replace("-", "_")
return MagicMock(returncode=0, stdout=json_output(make_check(check)))
return run, commands
def test_pr_author_checks_read_the_branch_tip(self):
"""On refs/pull/N/merge HEAD's author is GitHub, not the contributor."""
run, commands = self._fake_git_and_cli(resolves=True)
with (
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", True),
patch("main.AUTHOR_NAME_ENABLED", True),
patch("main.AUTHOR_EMAIL_ENABLED", True),
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}),
patch("main.get_pr_head_sha", return_value=None),
patch("main.subprocess.run", side_effect=run),
):
rc, results, output = self._run_capturing_stdout()
self.assertEqual(rc, 0)
self.assertEqual(
[s.label for s in results], ["Branch", "Author name", "Author email"]
)
self.assertIn(
["git", "rev-parse", "--verify", "--quiet", "HEAD^2^{commit}"], commands
)
self.assertIn(
["commit-check", "--format", "json", "--author-name", "--rev", "HEAD^2"],
commands,
)
self.assertIn(
["commit-check", "--format", "json", "--author-email", "--rev", "HEAD^2"],
commands,
)
# The branch check has no commit to point at.
self.assertIn(["commit-check", "--format", "json", "--branch"], commands)
self.assertNotIn("::warning", output)
def test_pr_author_checks_prefer_the_payload_head_sha(self):
"""pull_request.head.sha names the tip for either PR event type."""
run, commands = self._fake_git_and_cli(resolves=True)
with (
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", True),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}),
patch("main.get_pr_head_sha", return_value="deadbeefcafe"),
patch("main.subprocess.run", side_effect=run),
):
rc, results, output = self._run_capturing_stdout()
self.assertEqual(rc, 0)
self.assertEqual([s.status for s in results], ["pass"])
self.assertIn(
["git", "rev-parse", "--verify", "--quiet", "deadbeefcafe^{commit}"],
commands,
)
self.assertIn(
[
"commit-check",
"--format",
"json",
"--author-name",
"--rev",
"deadbeefcafe",
],
commands,
)
self.assertNotIn("::warning", output)
def test_pr_author_checks_are_skipped_on_a_shallow_clone(self):
"""HEAD's author is GitHub's merge commit: skip rather than grade it."""
run, commands = self._fake_git_and_cli(resolves=False)
with (
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", True),
patch("main.AUTHOR_NAME_ENABLED", True),
patch("main.AUTHOR_EMAIL_ENABLED", True),
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}),
patch("main.get_pr_head_sha", return_value=None),
patch("main.subprocess.run", side_effect=run),
):
rc, results, output = self._run_capturing_stdout()
self.assertEqual(rc, 0)
self.assertEqual(
[(s.label, s.status) for s in results],
[("Author name", "skip"), ("Author email", "skip"), ("Branch", "pass")],
)
self.assertEqual(
results[0].checks,
[
{
"rule_id": "CC101",
"check": "author_name",
"status": "skip",
"value": "",
"error": "",
"suggest": "",
"docs_url": "",
}
],
)
self.assertEqual(results[1].checks[0]["rule_id"], "CC102")
self.assertFalse([c for c in commands if "--author-name" in c], commands)
self.assertFalse([c for c in commands if "--author-email" in c], commands)
self.assertIn(["commit-check", "--format", "json", "--branch"], commands)
warning = [ln for ln in output.splitlines() if ln.startswith("::warning")]
self.assertEqual(len(warning), 1, output)
self.assertTrue(warning[0].startswith("::warning title=commit-check::"))
self.assertIn("Could not resolve the pull request's head commit", warning[0])
self.assertIn("is actions/checkout using fetch-depth: 0?", warning[0])
self.assertIn("they were skipped", warning[0])
def test_pull_request_target_never_uses_head2(self):
"""On pull_request_target HEAD is the base branch; HEAD^2 is unrelated."""
run, commands = self._fake_git_and_cli(resolves=True)
with (
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", True),
patch("main.AUTHOR_EMAIL_ENABLED", False),
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}),
patch("main.get_pr_head_sha", return_value=None),
patch("main.subprocess.run", side_effect=run),
):
rc, results, output = self._run_capturing_stdout()
self.assertEqual(rc, 0)
self.assertEqual(
[(s.label, s.status) for s in results], [("Author name", "skip")]
)
self.assertFalse([c for c in commands if "HEAD^2^{commit}" in c], commands)
self.assertFalse([c for c in commands if c[0] == "commit-check"], commands)
self.assertIn("::warning title=commit-check::", output)
def test_push_author_checks_never_pass_rev(self):
run, commands = self._fake_git_and_cli(resolves=True)
with (
patch("main.MESSAGE_ENABLED", False),
patch("main.BRANCH_ENABLED", False),
patch("main.AUTHOR_NAME_ENABLED", True),
patch("main.AUTHOR_EMAIL_ENABLED", True),
patch("main.is_pr_event", return_value=False),
patch("main.subprocess.run", side_effect=run),
):
_rc, _results, output = self._run_capturing_stdout()
self.assertFalse([c for c in commands if c[0] == "git"], commands)
self.assertFalse([c for c in commands if "--rev" in c], commands)
self.assertNotIn("::warning", output)
class TestPrHeadRev(unittest.TestCase):
def test_payload_head_sha_wins_when_the_clone_has_it(self):
with (
patch("main.get_pr_head_sha", return_value="abc123"),
patch(
"main.subprocess.run", return_value=MagicMock(returncode=0)
) as mock_run,
):
self.assertEqual(main.pr_head_rev(), "abc123")
self.assertEqual(
mock_run.call_args[0][0],
["git", "rev-parse", "--verify", "--quiet", "abc123^{commit}"],
)
def test_pull_request_falls_back_to_head2(self):
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request"}),
patch("main.get_pr_head_sha", return_value=None),
patch(
"main.subprocess.run", return_value=MagicMock(returncode=0)
) as mock_run,
):
self.assertEqual(main.pr_head_rev(), "HEAD^2")
self.assertEqual(
mock_run.call_args[0][0],
["git", "rev-parse", "--verify", "--quiet", "HEAD^2^{commit}"],
)
def test_pull_request_target_does_not_fall_back_to_head2(self):
with (
patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request_target"}),
patch("main.get_pr_head_sha", return_value=None),
patch(
"main.subprocess.run", return_value=MagicMock(returncode=0)
) as mock_run,