Debian Codegraph @

tests/commands/test_check_command.py

raw
1 from __future__ import annotations
2
3 from io import StringIO
4 from typing import TYPE_CHECKING, Any
5
6 import pytest
7
8 from commitizen import cmd, commands, git
9 from commitizen.cz import registry
10 from commitizen.cz.base import BaseCommitizen
11 from commitizen.exceptions import (
12 CommitMessageLengthExceededError,
13 InvalidCommandArgumentError,
14 InvalidCommitMessageError,
15 NoCommitsFoundError,
16 )
17
18 if TYPE_CHECKING:
19 from collections.abc import Mapping
20
21 from pytest_mock import MockFixture, MockType
22
23 from commitizen.config.base_config import BaseConfig
24 from commitizen.question import CzQuestion
25 from tests.utils import UtilFixture
26
27
28 COMMIT_LOG = [
29 "refactor: A code change that neither fixes a bug nor adds a feature",
30 r"refactor(cz/conventional_commit): use \S to check scope",
31 "refactor(git): remove unnecessary dot between git range",
32 "bump: version 1.16.3 → 1.16.4",
33 (
34 "Merge pull request #139 from Lee-W/fix-init-clean-config-file\n\n"
35 "Fix init clean config file"
36 ),
37 "ci(pyproject.toml): add configuration for coverage",
38 "fix(commands/init): fix clean up file when initialize commitizen config\n\n#138",
39 "refactor(defaults): split config files into long term support and deprecated ones",
40 "bump: version 1.16.2 → 1.16.3",
41 (
42 "Merge pull request #136 from Lee-W/remove-redundant-readme\n\n"
43 "Remove redundant readme"
44 ),
45 "fix: replace README.rst with docs/README.md in config files",
46 (
47 "refactor(docs): remove README.rst and use docs/README.md\n\n"
48 "By removing README.rst, we no longer need to maintain "
49 "two document with almost the same content\n"
50 "Github can read docs/README.md as README for the project."
51 ),
52 "docs(check): pin pre-commit to v1.16.2",
53 "docs(check): fix pre-commit setup",
54 "bump: version 1.16.1 → 1.16.2",
55 "Merge pull request #135 from Lee-W/fix-pre-commit-hook\n\nFix pre commit hook",
56 "docs(check): enforce cz check only when committing",
57 (
58 'Revert "fix(pre-commit): set pre-commit check stage to commit-msg"\n\n'
59 "This reverts commit afc70133e4a81344928561fbf3bb20738dfc8a0b."
60 ),
61 "feat!: add user stuff",
62 "fixup! test(commands): ignore fixup! prefix",
63 "fixup! test(commands): ignore squash! prefix",
64 ]
65
66
67 def _build_fake_git_commits(commit_msgs: list[str]) -> list[git.GitCommit]:
68 return [git.GitCommit("test_rev", commit_msg) for commit_msg in commit_msgs]
69
70
71 def test_check_jira_fails(mocker: MockFixture, util: UtilFixture):
72 mock_path = mocker.patch("commitizen.commands.check.Path")
73 mock_path.return_value.read_text.return_value = (
74 "random message for J-2 #fake_command blah"
75 )
76 with pytest.raises(InvalidCommitMessageError, match="commit validation: failed!"):
77 util.run_cli("-n", "cz_jira", "check", "--commit-msg-file", "some_file")
78
79
80 @pytest.mark.parametrize(
81 "commit_msg",
82 [
83 "JR-23 #command some arguments etc",
84 "JR-2 #command some arguments etc",
85 "JR-234 some text #command some arguments etc",
86 "JRA-23 some text #command1 args #command2 args",
87 ],
88 )
89 def test_check_jira_command_after_issue(
90 mocker: MockFixture, capsys, util: UtilFixture, commit_msg: str
91 ):
92 mock_path = mocker.patch("commitizen.commands.check.Path")
93 mock_path.return_value.read_text.return_value = commit_msg
94 util.run_cli("-n", "cz_jira", "check", "--commit-msg-file", "some_file")
95 out, _ = capsys.readouterr()
96 assert "Commit validation: successful!" in out
97
98
99 def test_check_conventional_commit_succeeds(
100 mocker: MockFixture, capsys, util: UtilFixture
101 ):
102 mock_path = mocker.patch("commitizen.commands.check.Path")
103 mock_path.return_value.read_text.return_value = "fix(scope): some commit message"
104 util.run_cli("check", "--commit-msg-file", "some_file")
105 out, _ = capsys.readouterr()
106 assert "Commit validation: successful!" in out
107
108
109 @pytest.mark.parametrize(
110 "commit_msg",
111 [
112 "feat!(lang): removed polish language",
113 "no conventional commit",
114 (
115 "ci: check commit message on merge\n"
116 "testing with more complex commit mes\n\n"
117 "age with error"
118 ),
119 ],
120 )
121 def test_check_no_conventional_commit(commit_msg, config, tmp_path):
122 tempfile = tmp_path / "temp_commit_file"
123 tempfile.write_text(commit_msg)
124
125 with pytest.raises(InvalidCommitMessageError):
126 commands.Check(config=config, arguments={"commit_msg_file": tempfile})()
127
128
129 @pytest.mark.parametrize(
130 "commit_msg",
131 [
132 "feat(lang)!: removed polish language",
133 "feat(lang): added polish language",
134 "feat: add polish language",
135 "bump: 0.0.1 -> 1.0.0",
136 ],
137 )
138 def test_check_conventional_commit(
139 commit_msg, config, success_mock: MockType, tmp_path
140 ):
141 tempfile = tmp_path / "temp_commit_file"
142 tempfile.write_text(commit_msg)
143 commands.Check(config=config, arguments={"commit_msg_file": tempfile})()
144 success_mock.assert_called_once()
145
146
147 def test_check_command_when_commit_file_not_found(config):
148 with pytest.raises(FileNotFoundError):
149 commands.Check(config=config, arguments={"commit_msg_file": "no_such_file"})()
150
151
152 def test_check_a_range_of_git_commits(
153 config, success_mock: MockType, mocker: MockFixture
154 ):
155 mocker.patch(
156 "commitizen.git.get_commits", return_value=_build_fake_git_commits(COMMIT_LOG)
157 )
158
159 commands.Check(config=config, arguments={"rev_range": "HEAD~10..master"})()
160 success_mock.assert_called_once()
161
162
163 def test_check_a_range_of_git_commits_and_failed(config, mocker: MockFixture):
164 mocker.patch(
165 "commitizen.git.get_commits",
166 return_value=_build_fake_git_commits(["This commit does not follow rule"]),
167 )
168
169 with pytest.raises(
170 InvalidCommitMessageError, match="This commit does not follow rule"
171 ):
172 commands.Check(config=config, arguments={"rev_range": "HEAD~10..master"})()
173
174
175 def test_check_rev_range_expands_env_vars(
176 config, success_mock: MockType, mocker: MockFixture, monkeypatch: pytest.MonkeyPatch
177 ):
178 """The ``commitizen-branch`` pre-push hook passes the literal string
179 ``$PRE_COMMIT_FROM_REF..$PRE_COMMIT_TO_REF`` and relies on env-var
180 expansion. Regression test for
181 https://github.com/commitizen-tools/commitizen/issues/2003.
182 """
183 monkeypatch.setenv("PRE_COMMIT_FROM_REF", "abc123")
184 monkeypatch.setenv("PRE_COMMIT_TO_REF", "def456")
185 get_commits = mocker.patch(
186 "commitizen.git.get_commits",
187 return_value=_build_fake_git_commits(COMMIT_LOG),
188 )
189
190 commands.Check(
191 config=config,
192 arguments={"rev_range": "$PRE_COMMIT_FROM_REF..$PRE_COMMIT_TO_REF"},
193 )()
194
195 success_mock.assert_called_once()
196 get_commits.assert_called_once_with(None, "abc123..def456")
197
198
199 def test_check_rev_range_leaves_unset_env_vars_literal(
200 config, mocker: MockFixture, monkeypatch: pytest.MonkeyPatch
201 ):
202 """Unset env-var references should pass through unchanged so git can
203 surface a clear ``ambiguous argument`` error instead of being silently
204 rewritten to an empty range."""
205 monkeypatch.delenv("PRE_COMMIT_FROM_REF", raising=False)
206 monkeypatch.delenv("PRE_COMMIT_TO_REF", raising=False)
207 get_commits = mocker.patch(
208 "commitizen.git.get_commits",
209 return_value=_build_fake_git_commits(COMMIT_LOG),
210 )
211
212 commands.Check(
213 config=config,
214 arguments={"rev_range": "$PRE_COMMIT_FROM_REF..$PRE_COMMIT_TO_REF"},
215 )()
216
217 get_commits.assert_called_once_with(
218 None, "$PRE_COMMIT_FROM_REF..$PRE_COMMIT_TO_REF"
219 )
220
221
222 def test_check_command_with_invalid_argument(config):
223 with pytest.raises(
224 InvalidCommandArgumentError,
225 match="Only one of --rev-range, --message, and --commit-msg-file is permitted by check command!",
226 ):
227 commands.Check(
228 config=config,
229 arguments={"commit_msg_file": "some_file", "rev_range": "HEAD~10..master"},
230 )
231
232
233 @pytest.mark.usefixtures("tmp_commitizen_project")
234 def test_check_command_with_empty_range(config: BaseConfig, util: UtilFixture):
235 # must initialize git with a commit
236 util.create_file_and_commit("feat: initial")
237 with pytest.raises(
238 NoCommitsFoundError, match="No commit found with range: 'master..master'"
239 ):
240 commands.Check(config=config, arguments={"rev_range": "master..master"})()
241
242
243 @pytest.mark.usefixtures("tmp_commitizen_project")
244 def test_check_rev_range_pre_commit_branch_hook_regression(
245 config: BaseConfig,
246 util: UtilFixture,
247 capsys: pytest.CaptureFixture[str],
248 monkeypatch: pytest.MonkeyPatch,
249 ):
250 """End-to-end regression test for the packaged ``commitizen-branch``
251 pre-push hook.
252
253 The hook in ``.pre-commit-hooks.yaml`` runs::
254
255 cz check --rev-range "$PRE_COMMIT_FROM_REF..$PRE_COMMIT_TO_REF"
256
257 ``pre-commit`` exports those refs as environment variables but does
258 *not* expand them in argv, so the literal string reaches ``cz check``.
259 Before this fix, ``Check`` forwarded that literal to ``git log`` via
260 ``shell=False`` (PR #1941, CWE-78 hardening) and git aborted with
261 ``fatal: ambiguous argument '$PRE_COMMIT_FROM_REF..$PRE_COMMIT_TO_REF'``.
262
263 This test exercises the real subprocess path -- no mocks on
264 ``git.get_commits`` -- to guard against any future regression that
265 bypasses env-var expansion in the rev-range argument.
266
267 See https://github.com/commitizen-tools/commitizen/issues/2003.
268 """
269 util.create_file_and_commit("feat: initial")
270 util.create_file_and_commit("fix: second commit")
271
272 from_ref = cmd.run(["git", "rev-parse", "HEAD~1"]).out.strip()
273 to_ref = cmd.run(["git", "rev-parse", "HEAD"]).out.strip()
274 monkeypatch.setenv("PRE_COMMIT_FROM_REF", from_ref)
275 monkeypatch.setenv("PRE_COMMIT_TO_REF", to_ref)
276
277 commands.Check(
278 config=config,
279 arguments={"rev_range": "$PRE_COMMIT_FROM_REF..$PRE_COMMIT_TO_REF"},
280 )()
281
282 captured = capsys.readouterr()
283 assert "Commit validation: successful!" in captured.out
284
285
286 def test_check_a_range_of_failed_git_commits(config, mocker: MockFixture):
287 ill_formatted_commits_msgs = [
288 "First commit does not follow rule",
289 "Second commit does not follow rule",
290 ("Third commit does not follow rule\nIll-formatted commit with body"),
291 ]
292 mocker.patch(
293 "commitizen.git.get_commits",
294 return_value=_build_fake_git_commits(ill_formatted_commits_msgs),
295 )
296
297 with pytest.raises(
298 InvalidCommitMessageError,
299 match=r"[\s\S]*".join(ill_formatted_commits_msgs),
300 ):
301 commands.Check(config=config, arguments={"rev_range": "HEAD~10..master"})()
302
303
304 def test_check_command_with_valid_message(config, success_mock: MockType):
305 commands.Check(
306 config=config, arguments={"message": "fix(scope): some commit message"}
307 )()
308 success_mock.assert_called_once()
309
310
311 @pytest.mark.parametrize("message", ["bad commit", ""])
312 def test_check_command_with_invalid_message(config, message):
313 with pytest.raises(InvalidCommitMessageError):
314 commands.Check(config=config, arguments={"message": message})()
315
316
317 def test_check_command_with_allow_abort_arg(config, success_mock):
318 commands.Check(config=config, arguments={"message": "", "allow_abort": True})()
319 success_mock.assert_called_once()
320
321
322 def test_check_command_with_allow_abort_config(config, success_mock):
323 config.settings["allow_abort"] = True
324 commands.Check(config=config, arguments={"message": ""})()
325 success_mock.assert_called_once()
326
327
328 def test_check_command_override_allow_abort_config(config):
329 config.settings["allow_abort"] = True
330 with pytest.raises(InvalidCommitMessageError):
331 commands.Check(config=config, arguments={"message": "", "allow_abort": False})()
332
333
334 def test_check_command_with_allowed_prefixes_arg(config, success_mock):
335 commands.Check(
336 config=config,
337 arguments={"message": "custom! test", "allowed_prefixes": ["custom!"]},
338 )()
339 success_mock.assert_called_once()
340
341
342 def test_check_command_with_allowed_prefixes_config(config, success_mock):
343 config.settings["allowed_prefixes"] = ["custom!"]
344 commands.Check(config=config, arguments={"message": "custom! test"})()
345 success_mock.assert_called_once()
346
347
348 def test_check_command_override_allowed_prefixes_config(config):
349 config.settings["allow_abort"] = ["fixup!"]
350 with pytest.raises(InvalidCommitMessageError):
351 commands.Check(
352 config=config,
353 arguments={"message": "fixup! test", "allowed_prefixes": ["custom!"]},
354 )()
355
356
357 def test_check_command_with_pipe_message(
358 mocker: MockFixture, capsys, util: UtilFixture
359 ):
360 mocker.patch("sys.stdin", StringIO("fix(scope): some commit message"))
361
362 util.run_cli("check")
363 out, _ = capsys.readouterr()
364 assert "Commit validation: successful!" in out
365
366
367 def test_check_command_with_pipe_message_and_failed(
368 mocker: MockFixture, util: UtilFixture
369 ):
370 mocker.patch("sys.stdin", StringIO("bad commit message"))
371
372 with pytest.raises(InvalidCommitMessageError, match="commit validation: failed!"):
373 util.run_cli("check")
374
375
376 def test_check_command_with_comment_in_message_file(
377 mocker: MockFixture, capsys, util: UtilFixture
378 ):
379 mock_path = mocker.patch("commitizen.commands.check.Path")
380 mock_path.return_value.read_text.return_value = (
381 "# <type>: (If applied, this commit will...) <subject>\n"
382 "# |<---- Try to Limit to a Max of 50 char ---->|\n"
383 "ci: add commitizen pre-commit hook\n"
384 "\n"
385 "# Explain why this change is being made\n"
386 "# |<---- Try To Limit Each Line to a Max Of 72 Char ---->|\n"
387 "This pre-commit hook will check our commits automatically."
388 )
389 util.run_cli("check", "--commit-msg-file", "some_file")
390 out, _ = capsys.readouterr()
391 assert "Commit validation: successful!" in out
392
393
394 def test_check_conventional_commit_succeed_with_git_diff(
395 mocker, capsys, util: UtilFixture
396 ):
397 mock_path = mocker.patch("commitizen.commands.check.Path")
398 mock_path.return_value.read_text.return_value = (
399 "feat: This is a test commit\n"
400 "# Please enter the commit message for your changes. Lines starting\n"
401 "# with '#' will be ignored, and an empty message aborts the commit.\n"
402 "#\n"
403 "# On branch ...\n"
404 "# Changes to be committed:\n"
405 "# modified: ...\n"
406 "#\n"
407 "# ------------------------ >8 ------------------------\n"
408 "# Do not modify or remove the line above.\n"
409 "# Everything below it will be ignored.\n"
410 "diff --git a/... b/...\n"
411 "index f1234c..1c5678 1234\n"
412 "--- a/...\n"
413 "+++ b/...\n"
414 "@@ -92,3 +92,4 @@ class Command(BaseCommand):\n"
415 '+ "this is a test"\n'
416 )
417 util.run_cli("check", "--commit-msg-file", "some_file")
418 out, _ = capsys.readouterr()
419 assert "Commit validation: successful!" in out
420
421
422 def test_check_command_with_message_length_limit(config, success_mock):
423 message = "fix(scope): some commit message"
424 commands.Check(
425 config=config,
426 arguments={"message": message, "message_length_limit": len(message) + 1},
427 )()
428 success_mock.assert_called_once()
429
430
431 def test_check_command_with_message_length_limit_exceeded(config):
432 message = "fix(scope): some commit message"
433 with pytest.raises(CommitMessageLengthExceededError):
434 commands.Check(
435 config=config,
436 arguments={"message": message, "message_length_limit": len(message) - 1},
437 )()
438
439
440 def test_check_command_with_amend_prefix_default(config, success_mock):
441 commands.Check(config=config, arguments={"message": "amend! test"})()
442 success_mock.assert_called_once()
443
444
445 def test_check_command_with_config_message_length_limit(config, success_mock):
446 message = "fix(scope): some commit message"
447 config.settings["message_length_limit"] = len(message) + 1
448 commands.Check(
449 config=config,
450 arguments={"message": message},
451 )()
452 success_mock.assert_called_once()
453
454
455 def test_check_command_with_config_message_length_limit_exceeded(config):
456 message = "fix(scope): some commit message"
457 config.settings["message_length_limit"] = len(message) - 1
458 with pytest.raises(CommitMessageLengthExceededError):
459 commands.Check(
460 config=config,
461 arguments={"message": message},
462 )()
463
464
465 def test_check_command_cli_overrides_config_message_length_limit(
466 config, success_mock: MockType
467 ):
468 message = "fix(scope): some commit message"
469 config.settings["message_length_limit"] = len(message) - 1
470 for message_length_limit in [len(message) + 1, 0]:
471 success_mock.reset_mock()
472 commands.Check(
473 config=config,
474 arguments={
475 "message": message,
476 "message_length_limit": message_length_limit,
477 },
478 )()
479 success_mock.assert_called_once()
480
481
482 class ValidationCz(BaseCommitizen):
483 def questions(self) -> list[CzQuestion]:
484 return [
485 {"type": "input", "name": "commit", "message": "Initial commit:\n"},
486 {"type": "input", "name": "issue_nb", "message": "ABC-123"},
487 ]
488
489 def message(self, answers: Mapping[str, Any]) -> str:
490 return f"{answers['issue_nb']}: {answers['commit']}"
491
492 def schema(self) -> str:
493 return "<issue_nb>: <commit>"
494
495 def schema_pattern(self) -> str:
496 return r"^(?P<issue_nb>[A-Z]{3}-\d+): (?P<commit>.*)$"
497
498 def example(self) -> str:
499 return "ABC-123: fixed a bug"
500
501 def info(self) -> str:
502 return "Commit message must start with an issue number like ABC-123"
503
504
505 @pytest.fixture
506 def use_cz_custom_validator(mocker):
507 new_cz = {**registry, "cz_custom_validator": ValidationCz}
508 mocker.patch.dict("commitizen.cz.registry", new_cz)
509
510
511 @pytest.mark.usefixtures("use_cz_custom_validator")
512 def test_check_command_with_custom_validator_succeed(
513 mocker: MockFixture, capsys, util: UtilFixture
514 ):
515 mock_path = mocker.patch("commitizen.commands.check.Path")
516 mock_path.return_value.read_text.return_value = (
517 "ABC-123: add commitizen pre-commit hook"
518 )
519 util.run_cli(
520 "--name", "cz_custom_validator", "check", "--commit-msg-file", "some_file"
521 )
522 out, _ = capsys.readouterr()
523 assert "Commit validation: successful!" in out
524
525
526 @pytest.mark.usefixtures("use_cz_custom_validator")
527 def test_check_command_with_custom_validator_failed(
528 mocker: MockFixture, util: UtilFixture
529 ):
530 mock_path = mocker.patch("commitizen.commands.check.Path")
531 mock_path.return_value.read_text.return_value = (
532 "123-ABC issue id has wrong format and misses colon"
533 )
534 with pytest.raises(
535 InvalidCommitMessageError,
536 match=r"commit validation: failed![\s\S]*pattern: ",
537 ):
538 util.run_cli(
539 "--name", "cz_custom_validator", "check", "--commit-msg-file", "some_file"
540 )