Debian Codegraph @

tests/commands/test_commit_command.py

raw
1 import re
2 import sys
3 from pathlib import Path
4 from unittest.mock import ANY
5
6 import pytest
7 from pytest_mock import MockFixture, MockType
8
9 from commitizen import cli, cmd, commands
10 from commitizen.cz.exceptions import CzException
11 from commitizen.cz.utils import get_backup_file_path
12 from commitizen.exceptions import (
13 CommitError,
14 CommitMessageLengthExceededError,
15 CustomError,
16 DryRunExit,
17 NoAnswersError,
18 NoCommitBackupError,
19 NotAGitProjectError,
20 NotAllowed,
21 NothingToCommitError,
22 )
23
24
25 @pytest.fixture
26 def commit_mock(mocker: MockFixture):
27 return mocker.patch(
28 "commitizen.git.commit", return_value=cmd.Command("success", "", b"", b"", 0)
29 )
30
31
32 @pytest.fixture
33 def prompt_mock_feat(mocker: MockFixture):
34 return mocker.patch(
35 "questionary.prompt",
36 return_value={
37 "prefix": "feat",
38 "subject": "user created",
39 "scope": "",
40 "is_breaking_change": False,
41 "body": "closes #21",
42 "footer": "",
43 },
44 )
45
46
47 @pytest.fixture
48 def staging_is_clean(mocker: MockFixture, tmp_git_project):
49 mocker.patch("commitizen.git.is_staging_clean", return_value=False)
50 return tmp_git_project
51
52
53 @pytest.fixture
54 def backup_file(tmp_git_project, monkeypatch):
55 """Write backup message so Commit finds it when run from tmp_git_project."""
56 monkeypatch.chdir(tmp_git_project)
57 path = get_backup_file_path()
58 path.write_text("backup commit", encoding="utf-8")
59
60
61 @pytest.mark.usefixtures("staging_is_clean", "commit_mock", "prompt_mock_feat")
62 def test_commit(config, success_mock: MockType):
63 commands.Commit(config, {})()
64 success_mock.assert_called_once()
65
66
67 @pytest.mark.usefixtures("staging_is_clean")
68 def test_commit_backup_on_failure(
69 config, mocker: MockFixture, prompt_mock_feat: MockType
70 ):
71 mocker.patch(
72 "commitizen.git.commit", return_value=cmd.Command("", "error", b"", b"", 9)
73 )
74 error_mock = mocker.patch("commitizen.out.error")
75
76 commit_cmd = commands.Commit(config, {})
77 temp_file = commit_cmd.backup_file_path
78 with pytest.raises(CommitError):
79 commit_cmd()
80
81 prompt_mock_feat.assert_called_once()
82 error_mock.assert_called_once()
83 assert Path(temp_file).exists()
84
85
86 @pytest.mark.usefixtures("staging_is_clean", "commit_mock")
87 def test_commit_retry_fails_no_backup(config):
88 with pytest.raises(
89 NoCommitBackupError, match=re.escape(NoCommitBackupError.message)
90 ):
91 commands.Commit(config, {"retry": True})()
92
93
94 @pytest.mark.usefixtures("staging_is_clean", "backup_file")
95 def test_commit_retry_works(
96 config, success_mock: MockType, mocker: MockFixture, commit_mock: MockType
97 ):
98 prompt_mock = mocker.patch("questionary.prompt")
99
100 commit_cmd = commands.Commit(config, {"retry": True})
101 temp_file = commit_cmd.backup_file_path
102 commit_cmd()
103
104 commit_mock.assert_called_with("backup commit", args=[])
105 prompt_mock.assert_not_called()
106 success_mock.assert_called_once()
107 assert not Path(temp_file).exists()
108
109
110 @pytest.mark.usefixtures("staging_is_clean")
111 def test_commit_retry_after_failure_no_backup(
112 config, success_mock: MockType, commit_mock: MockType, prompt_mock_feat: MockType
113 ):
114 config.settings["retry_after_failure"] = True
115 commands.Commit(config, {})()
116
117 commit_mock.assert_called_with("feat: user created\n\ncloses #21", args=[])
118 prompt_mock_feat.assert_called_once()
119 success_mock.assert_called_once()
120
121
122 @pytest.mark.usefixtures("staging_is_clean", "backup_file")
123 def test_commit_retry_after_failure_works(
124 config, success_mock: MockType, mocker: MockFixture, commit_mock: MockType
125 ):
126 prompt_mock = mocker.patch("questionary.prompt")
127
128 config.settings["retry_after_failure"] = True
129 commit_cmd = commands.Commit(config, {})
130 temp_file = commit_cmd.backup_file_path
131 commit_cmd()
132
133 commit_mock.assert_called_with("backup commit", args=[])
134 prompt_mock.assert_not_called()
135 success_mock.assert_called_once()
136 assert not Path(temp_file).exists()
137
138
139 @pytest.mark.usefixtures("staging_is_clean", "backup_file")
140 def test_commit_retry_after_failure_with_no_retry_works(
141 config, success_mock: MockType, commit_mock: MockType, prompt_mock_feat: MockType
142 ):
143 config.settings["retry_after_failure"] = True
144 commit_cmd = commands.Commit(config, {"no_retry": True})
145 temp_file = commit_cmd.backup_file_path
146 commit_cmd()
147
148 commit_mock.assert_called_with("feat: user created\n\ncloses #21", args=[])
149 prompt_mock_feat.assert_called_once()
150 success_mock.assert_called_once()
151 assert not Path(temp_file).exists()
152
153
154 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
155 def test_commit_command_with_dry_run_option(config):
156 with pytest.raises(DryRunExit):
157 commands.Commit(config, {"dry_run": True})()
158
159
160 @pytest.mark.usefixtures("staging_is_clean", "commit_mock", "prompt_mock_feat")
161 def test_commit_command_with_write_message_to_file_option(
162 config, tmp_path, success_mock: MockType
163 ):
164 tmp_file = tmp_path / "message"
165 commands.Commit(config, {"write_message_to_file": tmp_file})()
166 success_mock.assert_called_once()
167 assert tmp_file.exists()
168 assert "feat: user created" in tmp_file.read_text()
169
170
171 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
172 def test_commit_command_with_invalid_write_message_to_file_option(config, tmp_path):
173 with pytest.raises(NotAllowed):
174 commands.Commit(config, {"write_message_to_file": tmp_path})()
175
176
177 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
178 def test_commit_command_with_signoff_option(
179 config, success_mock: MockType, commit_mock: MockType
180 ):
181 commands.Commit(config, {"signoff": True})()
182
183 commit_mock.assert_called_once_with(ANY, args=["-s"])
184 success_mock.assert_called_once()
185
186
187 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
188 def test_commit_command_with_always_signoff_enabled(
189 config, success_mock: MockType, commit_mock: MockType
190 ):
191 config.settings["always_signoff"] = True
192 commands.Commit(config, {})()
193
194 commit_mock.assert_called_once_with(ANY, args=["-s"])
195 success_mock.assert_called_once()
196
197
198 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
199 def test_commit_command_with_gpgsign_and_always_signoff_enabled(
200 config, success_mock: MockType, commit_mock: MockType
201 ):
202 config.settings["always_signoff"] = True
203 commands.Commit(config, {"extra_cli_args": ["-S"]})()
204
205 commit_mock.assert_called_once_with(ANY, args=["-S", "-s"])
206 success_mock.assert_called_once()
207
208
209 @pytest.mark.usefixtures("tmp_git_project")
210 def test_commit_when_nothing_to_commit(config, mocker: MockFixture):
211 mocker.patch("commitizen.git.is_staging_clean", return_value=True)
212
213 with pytest.raises(NothingToCommitError, match="No files added to staging!"):
214 commands.Commit(config, {})()
215
216
217 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
218 def test_commit_with_allow_empty(config, success_mock: MockType, commit_mock: MockType):
219 commands.Commit(config, {"extra_cli_args": ["--allow-empty"]})()
220 commit_mock.assert_called_with(
221 "feat: user created\n\ncloses #21", args=["--allow-empty"]
222 )
223 success_mock.assert_called_once()
224
225
226 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
227 def test_commit_with_signoff_and_allow_empty(
228 config, success_mock: MockType, commit_mock: MockType
229 ):
230 config.settings["always_signoff"] = True
231 commands.Commit(config, {"extra_cli_args": ["--allow-empty"]})()
232
233 commit_mock.assert_called_with(
234 "feat: user created\n\ncloses #21", args=["--allow-empty", "-s"]
235 )
236 success_mock.assert_called_once()
237
238
239 @pytest.mark.usefixtures("staging_is_clean")
240 def test_commit_when_customized_expected_raised(config, mocker: MockFixture):
241 _err = ValueError()
242 _err.__context__ = CzException("This is the root custom err")
243 mocker.patch("questionary.prompt", side_effect=_err)
244 with pytest.raises(CustomError, match="This is the root custom err"):
245 commands.Commit(config, {})()
246
247
248 @pytest.mark.usefixtures("staging_is_clean")
249 def test_commit_when_non_customized_expected_raised(config, mocker: MockFixture):
250 mocker.patch("questionary.prompt", side_effect=ValueError("error message"))
251 with pytest.raises(ValueError, match="error message"):
252 commands.Commit(config, {})()
253
254
255 @pytest.mark.usefixtures("staging_is_clean")
256 def test_commit_when_no_user_answer(config, mocker: MockFixture):
257 mocker.patch("questionary.prompt", return_value=None)
258 with pytest.raises(NoAnswersError):
259 commands.Commit(config, {})()
260
261
262 def test_commit_in_non_git_project(tmp_path, monkeypatch, config):
263 monkeypatch.chdir(tmp_path)
264 with pytest.raises(NotAGitProjectError):
265 commands.Commit(config, {})
266
267
268 @pytest.mark.usefixtures("staging_is_clean", "commit_mock", "prompt_mock_feat")
269 def test_commit_command_with_all_option(
270 config, success_mock: MockType, mocker: MockFixture
271 ):
272 add_mock = mocker.patch("commitizen.git.add")
273 commands.Commit(config, {"all": True})()
274 add_mock.assert_called()
275 success_mock.assert_called_once()
276
277
278 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
279 def test_commit_command_with_extra_args(
280 config, success_mock: MockType, commit_mock: MockType
281 ):
282 commands.Commit(config, {"extra_cli_args": ["--", "-extra-args1", "-extra-arg2"]})()
283 commit_mock.assert_called_once_with(ANY, args=["--", "-extra-args1", "-extra-arg2"])
284 success_mock.assert_called_once()
285
286
287 @pytest.mark.usefixtures(
288 "tmp_commitizen_project", "staging_is_clean", "prompt_mock_feat"
289 )
290 def test_commit_cli_extra_args_parsing(mocker: MockFixture, commit_mock: MockType):
291 """Test that extra args after -- are passed as a list through the CLI."""
292 mocker.patch.object(sys, "argv", ["cz", "commit", "--", "--no-verify"])
293 cli.main()
294 commit_mock.assert_called_once_with(ANY, args=["--no-verify"])
295
296
297 @pytest.mark.usefixtures("staging_is_clean")
298 @pytest.mark.parametrize("editor", ["vim", None])
299 def test_manual_edit(editor, config, mocker: MockFixture, tmp_path):
300 mocker.patch("commitizen.git.get_core_editor", return_value=editor)
301 subprocess_mock = mocker.patch("subprocess.call")
302
303 mocker.patch("shutil.which", return_value=editor)
304
305 test_message = "Initial commit message"
306 temp_file = tmp_path / "temp_commit_message"
307 temp_file.write_text(test_message)
308
309 mock_temp_file = mocker.patch("tempfile.NamedTemporaryFile")
310 mock_temp_file.return_value.__enter__.return_value.name = str(temp_file)
311
312 commit_cmd = commands.Commit(config, {"edit": True})
313
314 if editor is None:
315 with pytest.raises(RuntimeError):
316 commit_cmd.manual_edit(test_message)
317 else:
318 edited_message = commit_cmd.manual_edit(test_message)
319 subprocess_mock.assert_called_once_with(["vim", str(temp_file)])
320 assert edited_message == test_message.strip()
321
322
323 @pytest.mark.usefixtures("staging_is_clean", "prompt_mock_feat")
324 @pytest.mark.parametrize(
325 "out", ["no changes added to commit", "nothing added to commit"]
326 )
327 def test_commit_when_nothing_added_to_commit(config, mocker: MockFixture, out):
328 commit_mock = mocker.patch(
329 "commitizen.git.commit",
330 return_value=cmd.Command(
331 out=out,
332 err="",
333 stdout=out.encode(),
334 stderr=b"",
335 return_code=0,
336 ),
337 )
338 error_mock = mocker.patch("commitizen.out.error")
339
340 commands.Commit(config, {})()
341
342 commit_mock.assert_called_once()
343 error_mock.assert_called_once_with(out)
344
345
346 @pytest.mark.usefixtures("staging_is_clean", "commit_mock")
347 def test_commit_command_with_config_message_length_limit(
348 config, success_mock: MockType, prompt_mock_feat: MockType
349 ):
350 prefix = prompt_mock_feat.return_value["prefix"]
351 subject = prompt_mock_feat.return_value["subject"]
352 message_length = len(f"{prefix}: {subject}")
353
354 commands.Commit(config, {"message_length_limit": message_length})()
355 success_mock.assert_called_once()
356
357 with pytest.raises(CommitMessageLengthExceededError):
358 commands.Commit(config, {"message_length_limit": message_length - 1})()
359
360 config.settings["message_length_limit"] = message_length
361 success_mock.reset_mock()
362 commands.Commit(config, {})()
363 success_mock.assert_called_once()
364
365 config.settings["message_length_limit"] = message_length - 1
366 with pytest.raises(CommitMessageLengthExceededError):
367 commands.Commit(config, {})()
368
369 # Test config message length limit is overridden by CLI argument
370 success_mock.reset_mock()
371 commands.Commit(config, {"message_length_limit": message_length})()
372 success_mock.assert_called_once()
373
374 success_mock.reset_mock()
375 commands.Commit(config, {"message_length_limit": 0})()
376 success_mock.assert_called_once()
377
378
379 @pytest.mark.usefixtures("staging_is_clean")
380 @pytest.mark.parametrize(
381 ("body", "body_length_limit"),
382 [
383 pytest.param(
384 "This is a very long line that exceeds 72 characters and should be automatically wrapped by the system to fit within the limit",
385 72,
386 id="wrapping",
387 ),
388 pytest.param(
389 "Line1 is shorter than the limit but has newline\nLine2 is shorter than the limit but has newline\nLine3 is shorter than the limit but has newline",
390 100,
391 id="preserves_line_breaks",
392 ),
393 pytest.param(
394 "Line1 is shorter than the limit but has paragraph break\n\nLine2 stays in a separate paragraph",
395 100,
396 id="preserves_blank_lines",
397 ),
398 pytest.param(
399 "This is a very long line that exceeds 72 characters and should NOT be wrapped when body_length_limit is set to 0",
400 0,
401 id="disabled",
402 ),
403 pytest.param(
404 "",
405 72,
406 id="no_body",
407 ),
408 ],
409 )
410 def test_commit_command_body_length_limit(
411 body,
412 body_length_limit,
413 config,
414 success_mock: MockType,
415 commit_mock,
416 mocker: MockFixture,
417 file_regression,
418 ):
419 """Parameterized test for body_length_limit feature with file regression."""
420 mocker.patch(
421 "questionary.prompt",
422 return_value={
423 "prefix": "feat",
424 "subject": "add feature",
425 "scope": "",
426 "is_breaking_change": False,
427 "body": body,
428 "footer": "",
429 },
430 )
431
432 commands.Commit(config, {"body_length_limit": body_length_limit})()
433 success_mock.assert_called_once()
434 committed_message = commit_mock.call_args[0][0]
435 file_regression.check(committed_message, extension=".txt")
436
437 lines = committed_message.split("\n")
438 body_lines = lines[2:] # Skip subject and blank line
439
440 if body_length_limit > 0:
441 for line in body_lines:
442 assert len(line) <= body_length_limit, (
443 f"Line exceeds {body_length_limit} chars: '{line}' ({len(line)} chars)"
444 )
445 elif body_length_limit == 0:
446 assert len(body_lines) == 1, (
447 "Body should not be wrapped when body_length_limit is set to 0"
448 )
449
450
451 @pytest.mark.usefixtures("staging_is_clean")
452 def test_commit_command_body_length_limit_preserves_whitespace_only_lines(
453 config,
454 success_mock: MockType,
455 commit_mock,
456 mocker: MockFixture,
457 ):
458 """A whitespace-only body line must be kept, not just an empty one.
459
460 ``textwrap.wrap`` returns ``[]`` for a whitespace-only string just like it
461 does for an empty one, so ``_wrap_body`` must special-case it the same
462 way to avoid silently dropping the paragraph separator. This is asserted
463 directly (not via ``file_regression``) because the repository's
464 trailing-whitespace pre-commit hook would strip the whitespace-only line
465 from any committed fixture file, invalidating the comparison.
466 """
467 body = (
468 "Line1 is shorter than the limit but has paragraph break"
469 "\n \n"
470 "Line2 stays in a separate paragraph"
471 )
472
473 mocker.patch(
474 "questionary.prompt",
475 return_value={
476 "prefix": "feat",
477 "subject": "add feature",
478 "scope": "",
479 "is_breaking_change": False,
480 "body": body,
481 "footer": "",
482 },
483 )
484
485 commands.Commit(config, {"body_length_limit": 100})()
486 success_mock.assert_called_once()
487 committed_message = commit_mock.call_args[0][0]
488 body_lines = committed_message.split("\n")[2:]
489
490 assert body_lines == [
491 "Line1 is shorter than the limit but has paragraph break",
492 " ",
493 "Line2 stays in a separate paragraph",
494 ], "Whitespace-only body line should be preserved, not dropped"