Debian Codegraph @

tests/commands/test_bump_command.py

raw
1 from __future__ import annotations
2
3 import inspect
4 import re
5 from pathlib import Path
6 from textwrap import dedent
7 from typing import TYPE_CHECKING
8 from unittest.mock import call
9
10 import pytest
11
12 import commitizen.commands.bump as bump
13 from commitizen import cmd, defaults, git, hooks
14 from commitizen.config.base_config import BaseConfig
15 from commitizen.exceptions import (
16 BumpTagFailedError,
17 CommitizenException,
18 CurrentVersionNotFoundError,
19 DryRunExit,
20 ExitCode,
21 ExpectedExit,
22 InvalidManualVersion,
23 NoCommitsFoundError,
24 NoneIncrementExit,
25 NoPatternMapError,
26 NotAGitProjectError,
27 NotAllowed,
28 NoVersionSpecifiedError,
29 )
30
31 if TYPE_CHECKING:
32 from pytest_mock import MockFixture
33 from pytest_regressions.file_regression import FileRegressionFixture
34
35 from commitizen.changelog_formats import ChangelogFormat
36 from commitizen.cz.base import BaseCommitizen
37 from tests.utils import UtilFixture
38
39
40 @pytest.mark.parametrize(
41 "commit_msg",
42 [
43 "fix: username exception",
44 "fix(user): username exception",
45 "refactor: remove ini configuration support",
46 "refactor(config): remove ini configuration support",
47 "perf: update to use multiprocess",
48 "perf(worker): update to use multiprocess",
49 ],
50 )
51 @pytest.mark.usefixtures("tmp_commitizen_project")
52 def test_bump_patch_increment(commit_msg: str, util: UtilFixture):
53 util.create_file_and_commit(commit_msg)
54 util.run_cli("bump", "--yes")
55 assert git.tag_exist("0.1.1") is True
56
57
58 @pytest.mark.parametrize("commit_msg", ["feat: new file", "feat(user): new file"])
59 @pytest.mark.usefixtures("tmp_commitizen_project")
60 def test_bump_minor_increment(commit_msg: str, util: UtilFixture):
61 util.create_file_and_commit(commit_msg)
62 util.run_cli("bump", "--yes")
63 assert git.tag_exist("0.2.0") is True
64 assert (
65 "commit:refs/tags/0.2.0"
66 in cmd.run(
67 ["git", "for-each-ref", "refs/tags", "--format", "%(objecttype):%(refname)"]
68 ).out
69 )
70
71
72 @pytest.mark.parametrize("commit_msg", ["feat: new file", "feat(user): new file"])
73 @pytest.mark.usefixtures("tmp_commitizen_project")
74 def test_bump_minor_increment_annotated(commit_msg: str, util: UtilFixture):
75 util.create_file_and_commit(commit_msg)
76 util.run_cli("bump", "--yes", "--annotated-tag")
77 assert git.tag_exist("0.2.0") is True
78 assert (
79 "tag:refs/tags/0.2.0"
80 in cmd.run(
81 ["git", "for-each-ref", "refs/tags", "--format", "%(objecttype):%(refname)"]
82 ).out
83 )
84
85 assert git.is_signed_tag("0.2.0") is False
86
87
88 @pytest.mark.parametrize("commit_msg", ["feat: new file", "feat(user): new file"])
89 @pytest.mark.usefixtures("tmp_commitizen_project_with_gpg")
90 def test_bump_minor_increment_signed(commit_msg: str, util: UtilFixture):
91 util.create_file_and_commit(commit_msg)
92 util.run_cli("bump", "--yes", "--gpg-sign")
93 assert git.tag_exist("0.2.0") is True
94 assert (
95 "tag:refs/tags/0.2.0"
96 in cmd.run(
97 ["git", "for-each-ref", "refs/tags", "--format", "%(objecttype):%(refname)"]
98 ).out
99 )
100
101 assert git.is_signed_tag("0.2.0") is True
102
103
104 @pytest.mark.parametrize("commit_msg", ["feat: new file", "feat(user): new file"])
105 def test_bump_minor_increment_annotated_config_file(
106 commit_msg: str, util: UtilFixture, pyproject: Path
107 ):
108 with pyproject.open("a", encoding="utf-8") as f:
109 f.write("\nannotated_tag = 1")
110 util.create_file_and_commit(commit_msg)
111 util.run_cli("bump", "--yes")
112 assert git.tag_exist("0.2.0") is True
113 assert (
114 "tag:refs/tags/0.2.0"
115 in cmd.run(
116 ["git", "for-each-ref", "refs/tags", "--format", "%(objecttype):%(refname)"]
117 ).out
118 )
119
120 assert git.is_signed_tag("0.2.0") is False
121
122
123 @pytest.mark.parametrize("commit_msg", ["feat: new file", "feat(user): new file"])
124 def test_bump_minor_increment_signed_config_file(
125 commit_msg: str, util: UtilFixture, tmp_commitizen_project_with_gpg
126 ):
127 tmp_commitizen_cfg_file = tmp_commitizen_project_with_gpg / "pyproject.toml"
128 with tmp_commitizen_cfg_file.open("a", encoding="utf-8") as f:
129 f.write("\ngpg_sign = 1")
130 util.create_file_and_commit(commit_msg)
131 util.run_cli("bump", "--yes")
132 assert git.tag_exist("0.2.0") is True
133 assert (
134 "tag:refs/tags/0.2.0"
135 in cmd.run(
136 ["git", "for-each-ref", "refs/tags", "--format", "%(objecttype):%(refname)"]
137 ).out
138 )
139
140 assert git.is_signed_tag("0.2.0") is True
141
142
143 @pytest.mark.usefixtures("tmp_commitizen_project")
144 @pytest.mark.parametrize(
145 "commit_msg",
146 [
147 "feat: new user interface\n\nBREAKING CHANGE: age is no longer supported",
148 "feat!: new user interface\n\nBREAKING CHANGE: age is no longer supported",
149 "feat!: new user interface",
150 "feat(user): new user interface\n\nBREAKING CHANGE: age is no longer supported",
151 "feat(user)!: new user interface\n\nBREAKING CHANGE: age is no longer supported",
152 "feat(user)!: new user interface",
153 "BREAKING CHANGE: age is no longer supported",
154 "BREAKING-CHANGE: age is no longer supported",
155 ],
156 )
157 def test_bump_major_increment(commit_msg: str, util: UtilFixture):
158 util.create_file_and_commit(commit_msg)
159 util.run_cli("bump", "--yes")
160 assert git.tag_exist("1.0.0") is True
161
162
163 @pytest.mark.usefixtures("tmp_commitizen_project")
164 @pytest.mark.parametrize(
165 "commit_msg",
166 [
167 "feat: new user interface\n\nBREAKING CHANGE: age is no longer supported",
168 "feat!: new user interface\n\nBREAKING CHANGE: age is no longer supported",
169 "feat!: new user interface",
170 "feat(user): new user interface\n\nBREAKING CHANGE: age is no longer supported",
171 "feat(user)!: new user interface\n\nBREAKING CHANGE: age is no longer supported",
172 "feat(user)!: new user interface",
173 "BREAKING CHANGE: age is no longer supported",
174 "BREAKING-CHANGE: age is no longer supported",
175 ],
176 )
177 def test_bump_major_increment_major_version_zero(commit_msg: str, util: UtilFixture):
178 util.create_file_and_commit(commit_msg)
179 util.run_cli("bump", "--yes", "--major-version-zero")
180 assert git.tag_exist("0.2.0") is True
181
182
183 @pytest.mark.usefixtures("tmp_commitizen_project")
184 @pytest.mark.parametrize(
185 ("commit_msg", "increment", "expected_tag"),
186 [
187 ("feat: new file", "PATCH", "0.1.1"),
188 ("fix: username exception", "major", "1.0.0"),
189 ("refactor: remove ini configuration support", "patch", "0.1.1"),
190 ("BREAKING CHANGE: age is no longer supported", "minor", "0.2.0"),
191 ],
192 )
193 def test_bump_command_increment_option(
194 commit_msg: str, increment: str, expected_tag: str, util: UtilFixture
195 ):
196 util.create_file_and_commit(commit_msg)
197 util.run_cli("bump", "--increment", increment, "--yes")
198 assert git.tag_exist(expected_tag) is True
199
200
201 @pytest.mark.usefixtures("tmp_commitizen_project")
202 def test_bump_command_prerelease(util: UtilFixture):
203 util.create_file_and_commit("feat: location")
204
205 # Create an alpha pre-release.
206 util.run_cli("bump", "--prerelease", "alpha", "--yes")
207 assert git.tag_exist("0.2.0a0") is True
208
209 # Create a beta pre-release.
210 util.run_cli("bump", "--prerelease", "beta", "--yes")
211 assert git.tag_exist("0.2.0b0") is True
212
213 # With a current beta pre-release, bumping alpha must bump beta
214 # because we can't bump "backwards".
215 util.run_cli("bump", "--prerelease", "alpha", "--yes")
216 assert git.tag_exist("0.2.0a1") is False
217 assert git.tag_exist("0.2.0b1") is True
218
219 # Create a rc pre-release.
220 util.run_cli("bump", "--prerelease", "rc", "--yes")
221 assert git.tag_exist("0.2.0rc0") is True
222
223 # With a current rc pre-release, bumping alpha must bump rc.
224 util.run_cli("bump", "--prerelease", "alpha", "--yes")
225 assert git.tag_exist("0.2.0a1") is False
226 assert git.tag_exist("0.2.0b2") is False
227 assert git.tag_exist("0.2.0rc1") is True
228
229 # With a current rc pre-release, bumping beta must bump rc.
230 util.run_cli("bump", "--prerelease", "beta", "--yes")
231 assert git.tag_exist("0.2.0a2") is False
232 assert git.tag_exist("0.2.0b2") is False
233 assert git.tag_exist("0.2.0rc2") is True
234
235 # Create a final release from the current pre-release.
236 util.run_cli("bump")
237 assert git.tag_exist("0.2.0") is True
238
239
240 @pytest.mark.usefixtures("tmp_commitizen_project")
241 def test_bump_command_prerelease_increment(util: UtilFixture):
242 # FINAL RELEASE
243 util.create_file_and_commit("fix: location")
244 util.run_cli("bump", "--yes")
245 assert git.tag_exist("0.1.1") is True
246
247 # PRERELEASE
248 util.create_file_and_commit("fix: location")
249 util.run_cli("bump", "--prerelease", "alpha", "--yes")
250 assert git.tag_exist("0.1.2a0") is True
251
252 util.create_file_and_commit("feat: location")
253 util.run_cli("bump", "--prerelease", "alpha", "--yes")
254 assert git.tag_exist("0.2.0a0") is True
255
256 util.create_file_and_commit("feat!: breaking")
257 util.run_cli("bump", "--prerelease", "alpha", "--yes")
258 assert git.tag_exist("1.0.0a0") is True
259
260
261 @pytest.mark.usefixtures("tmp_commitizen_project")
262 def test_bump_command_prerelease_exact_mode(util: UtilFixture):
263 # PRERELEASE
264 util.create_file_and_commit("feat: location")
265 util.run_cli("bump", "--prerelease", "alpha", "--yes")
266 assert git.tag_exist("0.2.0a0") is True
267
268 # PRERELEASE + PATCH BUMP
269 util.run_cli("bump", "--prerelease", "alpha", "--yes", "--increment-mode=exact")
270 assert git.tag_exist("0.2.0a1") is True
271
272 # PRERELEASE + MINOR BUMP
273 # --increment-mode allows the minor version to bump, and restart the prerelease
274 util.create_file_and_commit("feat: location")
275 util.run_cli("bump", "--prerelease", "alpha", "--yes", "--increment-mode=exact")
276 assert git.tag_exist("0.3.0a0") is True
277
278 # PRERELEASE + MAJOR BUMP
279 # --increment-mode=exact allows the major version to bump, and restart the prerelease
280 util.run_cli(
281 "bump",
282 "--prerelease",
283 "alpha",
284 "--yes",
285 "--increment=MAJOR",
286 "--increment-mode=exact",
287 )
288
289 assert git.tag_exist("1.0.0a0") is True
290
291
292 @pytest.mark.usefixtures("tmp_commitizen_project")
293 def test_bump_on_git_with_hooks_no_verify_disabled(util: UtilFixture):
294 """Bump commit without --no-verify"""
295 Path(".git/hooks").mkdir(parents=True, exist_ok=True)
296 with open(".git/hooks/pre-commit", "w", encoding="utf-8") as f:
297 f.write('#!/usr/bin/env bash\necho "0.1.0"')
298 Path(".git/hooks/pre-commit").chmod(0o755)
299
300 # MINOR
301 util.create_file_and_commit("feat: new file")
302 util.run_cli("bump", "--yes")
303 assert git.tag_exist("0.2.0") is True
304
305
306 @pytest.mark.usefixtures("tmp_commitizen_project")
307 def test_bump_tag_exists_raises_exception(util: UtilFixture):
308 Path(".git/hooks").mkdir(parents=True, exist_ok=True)
309 with open(".git/hooks/post-commit", "w", encoding="utf-8") as f:
310 f.write("#!/usr/bin/env bash\nexit 9")
311 Path(".git/hooks/post-commit").chmod(0o755)
312
313 # MINOR
314 util.create_file_and_commit("feat: new file")
315 git.tag("0.2.0")
316
317 with pytest.raises(BumpTagFailedError, match=re.escape("0.2.0")):
318 util.run_cli("bump", "--yes")
319
320
321 @pytest.mark.usefixtures("tmp_commitizen_project")
322 def test_bump_on_git_with_hooks_no_verify_enabled(util: UtilFixture):
323 Path(".git/hooks").mkdir(parents=True, exist_ok=True)
324 with open(".git/hooks/pre-commit", "w", encoding="utf-8") as f:
325 f.write('#!/usr/bin/env bash\necho "0.1.0"')
326 Path(".git/hooks/pre-commit").chmod(0o755)
327
328 # MINOR
329 util.create_file_and_commit("feat: new file")
330 util.run_cli("bump", "--yes", "--no-verify")
331 assert git.tag_exist("0.2.0") is True
332
333
334 @pytest.mark.usefixtures("tmp_commitizen_project")
335 def test_bump_when_bumping_is_not_support(util: UtilFixture):
336 util.create_file_and_commit(
337 "feat: new user interface\n\nBREAKING CHANGE: age is no longer supported"
338 )
339
340 with pytest.raises(NoPatternMapError, match="'cz_jira' rule does not support bump"):
341 util.run_cli("-n", "cz_jira", "bump", "--yes")
342
343
344 @pytest.mark.usefixtures("tmp_git_project")
345 def test_bump_when_version_is_not_specify(util: UtilFixture):
346 with pytest.raises(
347 NoVersionSpecifiedError, match=re.escape(NoVersionSpecifiedError.message)
348 ):
349 util.run_cli("bump")
350
351
352 @pytest.mark.usefixtures("tmp_commitizen_project")
353 def test_bump_when_no_new_commit(util: UtilFixture):
354 """bump without any commits since the last bump."""
355 # We need this first commit otherwise the revision is invalid.
356 util.create_file_and_commit("feat: initial")
357
358 util.run_cli("bump", "--yes")
359
360 # bump without a new commit.
361 with pytest.raises(
362 NoCommitsFoundError, match=r"\[NO_COMMITS_FOUND\]\nNo new commits found\."
363 ):
364 util.run_cli("bump", "--yes")
365
366
367 def test_bump_when_version_inconsistent_in_version_files(
368 tmp_commitizen_project, util: UtilFixture
369 ):
370 tmp_version_file = tmp_commitizen_project / "__version__.py"
371 tmp_version_file.write_text("100.999.10000")
372 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
373 tmp_version_file_string = str(tmp_version_file).replace("\\", "/")
374 with tmp_commitizen_cfg_file.open("a", encoding="utf-8") as f:
375 f.write(f'\nversion_files = ["{tmp_version_file_string}"]')
376
377 util.create_file_and_commit("feat: new file")
378
379 with pytest.raises(
380 CurrentVersionNotFoundError,
381 match=re.escape("Current version 0.1.0 is not found in"),
382 ):
383 util.run_cli("bump", "--yes", "--check-consistency")
384
385
386 def test_bump_major_version_zero_when_major_is_not_zero(
387 tmp_commitizen_project, util: UtilFixture
388 ):
389 tmp_version_file = tmp_commitizen_project / "__version__.py"
390 tmp_version_file.write_text("1.0.0")
391 tmp_version_file_string = str(tmp_version_file).replace("\\", "/")
392 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
393 tmp_commitizen_cfg_file.write_text(
394 f"[tool.commitizen]\n"
395 'version="1.0.0"\n'
396 f'version_files = ["{str(tmp_version_file_string)}"]'
397 )
398 tmp_changelog_file = tmp_commitizen_project / "CHANGELOG.md"
399 tmp_changelog_file.write_text("## v1.0.0")
400
401 util.create_file_and_commit("feat(user): new file")
402 util.create_tag("v1.0.0")
403 util.create_file_and_commit("feat(user)!: new file")
404
405 with pytest.raises(
406 NotAllowed,
407 match=re.escape(
408 "--major-version-zero is meaningless for current version 1.0.0"
409 ),
410 ):
411 util.run_cli("bump", "--yes", "--major-version-zero")
412
413
414 def test_bump_files_only(tmp_commitizen_project, util: UtilFixture):
415 tmp_version_file = tmp_commitizen_project / "__version__.py"
416 tmp_version_file.write_text("0.1.0")
417 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
418 tmp_version_file_string = str(tmp_version_file).replace("\\", "/")
419 with tmp_commitizen_cfg_file.open("a", encoding="utf-8") as f:
420 f.write(f'\nversion_files = ["{tmp_version_file_string}"]')
421
422 util.create_file_and_commit("feat: new user interface")
423 util.run_cli("bump", "--yes")
424 assert git.tag_exist("0.2.0") is True
425
426 util.create_file_and_commit("feat: another new feature")
427 with pytest.raises(ExpectedExit):
428 util.run_cli("bump", "--yes", "--version-files-only")
429
430 assert git.tag_exist("0.3.0") is False
431
432 assert "0.3.0" in tmp_version_file.read_text(encoding="utf-8")
433
434 assert "0.3.0" in tmp_commitizen_cfg_file.read_text(encoding="utf-8")
435
436
437 def test_bump_local_version(tmp_commitizen_project, util: UtilFixture):
438 tmp_version_file = tmp_commitizen_project / "__version__.py"
439 tmp_version_file.write_text("4.5.1+0.1.0")
440 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
441 tmp_version_file_string = str(tmp_version_file).replace("\\", "/")
442 tmp_commitizen_cfg_file.write_text(
443 f"[tool.commitizen]\n"
444 'version="4.5.1+0.1.0"\n'
445 f'version_files = ["{tmp_version_file_string}"]'
446 )
447
448 util.create_file_and_commit("feat: new user interface")
449 util.run_cli("bump", "--yes", "--local-version")
450 assert git.tag_exist("4.5.1+0.2.0") is True
451
452 assert "4.5.1+0.2.0" in tmp_version_file.read_text(encoding="utf-8")
453
454
455 @pytest.mark.usefixtures("tmp_commitizen_project")
456 def test_bump_dry_run(util: UtilFixture, capsys: pytest.CaptureFixture):
457 util.create_file_and_commit("feat: new file")
458
459 with pytest.raises(DryRunExit):
460 util.run_cli("bump", "--yes", "--dry-run")
461
462 out, _ = capsys.readouterr()
463 assert "0.2.0" in out
464 assert git.tag_exist("0.2.0") is False
465
466
467 def test_bump_in_non_git_project(tmp_path, monkeypatch, util: UtilFixture):
468 monkeypatch.chdir(tmp_path)
469 with pytest.raises(NotAGitProjectError):
470 util.run_cli("bump", "--yes")
471
472
473 def test_none_increment_exit_should_be_a_class():
474 assert inspect.isclass(NoneIncrementExit)
475
476
477 def test_none_increment_exit_should_be_expected_exit_subclass():
478 assert issubclass(NoneIncrementExit, CommitizenException)
479
480
481 def test_none_increment_exit_should_exist_in_bump():
482 assert hasattr(bump, "NoneIncrementExit")
483
484
485 def test_none_increment_exit_is_exception():
486 assert bump.NoneIncrementExit == NoneIncrementExit
487
488
489 @pytest.mark.usefixtures("tmp_commitizen_project")
490 def test_none_increment_should_not_call_git_tag_and_error_code_is_not_zero(
491 mocker: MockFixture,
492 util: UtilFixture,
493 ):
494 util.create_file_and_commit("test(test_get_all_droplets): fix bad comparison test")
495 git_tag_mock = mocker.patch("commitizen.git.tag")
496
497 with pytest.raises(NoneIncrementExit) as e:
498 util.run_cli("bump", "--yes")
499
500 git_tag_mock.assert_not_called()
501 assert e.value.exit_code == ExitCode.NO_INCREMENT
502
503
504 @pytest.mark.usefixtures("tmp_commitizen_project")
505 def test_bump_with_changelog_arg(util: UtilFixture, changelog_path):
506 util.create_file_and_commit("feat(user): new file")
507 util.run_cli("bump", "--yes", "--changelog")
508 assert git.tag_exist("0.2.0") is True
509
510 out = changelog_path.read_text(encoding="utf-8")
511 assert out.startswith("#")
512 assert "0.2.0" in out
513
514
515 @pytest.mark.usefixtures("tmp_commitizen_project")
516 def test_bump_with_changelog_config(util: UtilFixture, changelog_path, config_path):
517 util.create_file_and_commit("feat(user): new file")
518 with config_path.open("a", encoding="utf-8") as fp:
519 fp.write("update_changelog_on_bump = true\n")
520
521 util.run_cli("bump", "--yes")
522 assert git.tag_exist("0.2.0") is True
523
524 out = changelog_path.read_text(encoding="utf-8")
525 assert out.startswith("#")
526 assert "0.2.0" in out
527
528
529 @pytest.mark.usefixtures("tmp_commitizen_project")
530 def test_prevent_prerelease_when_no_increment_detected(
531 util: UtilFixture, capsys: pytest.CaptureFixture
532 ):
533 util.create_file_and_commit("feat: new file")
534
535 util.run_cli("bump", "--yes")
536 out, _ = capsys.readouterr()
537
538 assert "0.2.0" in out
539
540 util.create_file_and_commit("test: new file")
541
542 with pytest.raises(
543 NoCommitsFoundError,
544 match=re.escape(
545 "[NO_COMMITS_FOUND]\nNo commits found to generate a pre-release."
546 ),
547 ):
548 util.run_cli("bump", "-pr", "beta")
549
550
551 @pytest.mark.usefixtures("tmp_commitizen_project")
552 def test_bump_with_changelog_to_stdout_arg(
553 util: UtilFixture, capsys: pytest.CaptureFixture, changelog_path: Path
554 ):
555 util.create_file_and_commit("feat(user): this should appear in stdout")
556 util.run_cli("bump", "--yes", "--changelog-to-stdout")
557 out, _ = capsys.readouterr()
558
559 assert "this should appear in stdout" in out
560 assert git.tag_exist("0.2.0") is True
561
562 out = changelog_path.read_text(encoding="utf-8")
563 assert out.startswith("#")
564 assert "0.2.0" in out
565
566
567 @pytest.mark.usefixtures("tmp_commitizen_project")
568 def test_bump_with_changelog_to_stdout_dry_run_arg(
569 util: UtilFixture, capsys: pytest.CaptureFixture, changelog_path: Path
570 ):
571 util.create_file_and_commit(
572 "feat(user): this should appear in stdout with dry-run enabled"
573 )
574 with pytest.raises(DryRunExit):
575 util.run_cli("bump", "--yes", "--changelog-to-stdout", "--dry-run")
576 out, _ = capsys.readouterr()
577
578 assert git.tag_exist("0.2.0") is False
579 assert out.startswith("#")
580 assert "this should appear in stdout with dry-run enabled" in out
581 assert "0.2.0" in out
582
583
584 @pytest.mark.usefixtures("tmp_commitizen_project")
585 def test_bump_without_git_to_stdout_arg(
586 util: UtilFixture, capsys: pytest.CaptureFixture
587 ):
588 util.create_file_and_commit("feat(user): this should appear in stdout")
589 util.run_cli("bump", "--yes")
590 out, _ = capsys.readouterr()
591
592 assert (
593 re.search(r"^\[master \w+] bump: version 0.1.0 → 0.2.0", out, re.MULTILINE)
594 is not None
595 )
596
597
598 @pytest.mark.usefixtures("tmp_commitizen_project")
599 def test_bump_with_git_to_stdout_arg(util: UtilFixture, capsys: pytest.CaptureFixture):
600 util.create_file_and_commit("feat(user): this should appear in stdout")
601 util.run_cli("bump", "--yes", "--git-output-to-stderr")
602 out, _ = capsys.readouterr()
603
604 assert (
605 re.search(r"^\[master \w+] bump: version 0.1.0 → 0.2.0", out, re.MULTILINE)
606 is None
607 )
608
609
610 @pytest.mark.parametrize(
611 ("version_filepath", "version_regex", "version_file_content"),
612 [
613 pytest.param(
614 "pyproject.toml",
615 "pyproject.toml:^version",
616 """
617 [tool.poetry]
618 name = "my_package"
619 version = "0.1.0"
620 """,
621 id="version in pyproject.toml with regex",
622 ),
623 pytest.param(
624 "pyproject.toml",
625 "pyproject.toml",
626 """
627 [tool.poetry]
628 name = "my_package"
629 version = "0.1.0"
630 """,
631 id="version in pyproject.toml without regex",
632 ),
633 pytest.param(
634 "__init__.py",
635 "__init__.py:^__version__",
636 """
637 '''This is a test file.'''
638 __version__ = "0.1.0"
639 """,
640 id="version in __init__.py with regex",
641 ),
642 pytest.param(
643 "pyproject.toml",
644 "*.toml:^version",
645 """
646 [tool.poetry]
647 name = "my_package"
648 version = "0.1.0"
649 """,
650 id="version in pyproject.toml with glob and regex",
651 ),
652 ],
653 )
654 @pytest.mark.parametrize(
655 "cli_bump_changelog_args",
656 [
657 ("bump", "--changelog", "--yes"),
658 (
659 "bump",
660 "--changelog",
661 "--changelog-to-stdout",
662 "--annotated-tag",
663 "--check-consistency",
664 "--yes",
665 ),
666 ],
667 ids=lambda cmd_tuple: (
668 " ".join(["cz", *cmd_tuple]) if isinstance(cmd_tuple, tuple) else cmd_tuple
669 ),
670 )
671 def test_bump_changelog_command_commits_untracked_changelog_and_version_files(
672 tmp_commitizen_project,
673 util: UtilFixture,
674 cli_bump_changelog_args: tuple[str, ...],
675 version_filepath: str,
676 version_regex: str,
677 version_file_content: str,
678 ):
679 """Ensure that changelog always gets committed, no matter what version file or cli options get passed.
680
681 Steps:
682 - Append the version file's name and regex commitizen configuration lines to `pyproject.toml`.
683 - Append to or create the version file.
684 - Add a commit of type fix to be eligible for a version bump.
685 - Call commitizen main cli and assert that the `CHANGELOG.md` and the version file were committed.
686 """
687
688 with (tmp_commitizen_project / "pyproject.toml").open(
689 mode="a",
690 encoding="utf-8",
691 ) as commitizen_config:
692 commitizen_config.write(f"version_files = [\n'{version_regex}'\n]")
693
694 with (tmp_commitizen_project / version_filepath).open(
695 mode="a+", encoding="utf-8"
696 ) as version_file:
697 version_file.write(version_file_content)
698
699 util.create_file_and_commit("fix: some test commit")
700
701 util.run_cli(*cli_bump_changelog_args)
702
703 commit_file_names = git.get_filenames_in_commit()
704 assert "CHANGELOG.md" in commit_file_names
705 assert version_filepath in commit_file_names
706
707
708 @pytest.mark.parametrize(
709 "testargs",
710 [
711 ["--local-version", "1.2.3"],
712 ["--prerelease", "rc", "1.2.3"],
713 ["--devrelease", "0", "1.2.3"],
714 ["--devrelease", "1", "1.2.3"],
715 ["--increment", "PATCH", "1.2.3"],
716 ["--build-metadata=a.b.c", "1.2.3"],
717 ["--local-version", "--build-metadata=a.b.c"],
718 ],
719 )
720 @pytest.mark.usefixtures("tmp_commitizen_project")
721 def test_bump_invalid_manual_args_raises_exception(util: UtilFixture, testargs):
722 with pytest.raises(NotAllowed):
723 util.run_cli("bump", *testargs)
724
725
726 @pytest.mark.usefixtures("tmp_commitizen_project")
727 @pytest.mark.parametrize(
728 "manual_version",
729 [
730 "noversion",
731 "1.2..3",
732 ],
733 )
734 def test_bump_invalid_manual_version_raises_exception(
735 util: UtilFixture, manual_version
736 ):
737 util.create_file_and_commit("feat: new file")
738
739 with pytest.raises(
740 InvalidManualVersion,
741 match=re.escape(
742 f"[INVALID_MANUAL_VERSION]\nInvalid manual version: '{manual_version}'"
743 ),
744 ):
745 util.run_cli("bump", "--yes", manual_version)
746
747
748 @pytest.mark.usefixtures("tmp_commitizen_project")
749 @pytest.mark.parametrize(
750 "manual_version",
751 [
752 "0.0.1",
753 "0.1.0rc2",
754 "0.1.0.dev2",
755 "0.1.0+1.0.0",
756 "0.1.0rc2.dev2+1.0.0",
757 "0.1.1",
758 "0.2.0",
759 "1.0.0",
760 "1.2",
761 "1",
762 ],
763 )
764 def test_bump_manual_version(util: UtilFixture, manual_version):
765 util.create_file_and_commit("feat: new file")
766
767 util.run_cli("bump", "--yes", manual_version)
768 assert git.tag_exist(manual_version) is True
769
770
771 @pytest.mark.usefixtures("tmp_commitizen_project")
772 def test_bump_manual_version_disallows_major_version_zero(util: UtilFixture):
773 util.create_file_and_commit("feat: new file")
774 with pytest.raises(
775 NotAllowed,
776 match="--major-version-zero cannot be combined with MANUAL_VERSION",
777 ):
778 util.run_cli("bump", "--yes", "--major-version-zero", "0.2.0")
779
780
781 @pytest.mark.parametrize(
782 ("initial_version", "expected_version_after_bump"),
783 [
784 ("1", "1.1.0"),
785 ("1.2", "1.3.0"),
786 ],
787 )
788 def test_bump_version_with_less_components_in_config(
789 tmp_commitizen_project_initial,
790 initial_version,
791 expected_version_after_bump,
792 util: UtilFixture,
793 ):
794 tmp_commitizen_project = tmp_commitizen_project_initial(version=initial_version)
795 util.run_cli("bump", "--yes")
796
797 assert git.tag_exist(expected_version_after_bump) is True
798
799 for version_file in [
800 tmp_commitizen_project / "__version__.py",
801 tmp_commitizen_project / "pyproject.toml",
802 ]:
803 assert expected_version_after_bump in version_file.read_text(encoding="utf-8")
804
805
806 @pytest.mark.parametrize("commit_msg", ["feat: new file", "feat(user): new file"])
807 def test_bump_with_pre_bump_hooks(
808 commit_msg, mocker: MockFixture, tmp_commitizen_project, util: UtilFixture
809 ):
810 pre_bump_hook = "scripts/pre_bump_hook.sh"
811 post_bump_hook = "scripts/post_bump_hook.sh"
812
813 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
814 with tmp_commitizen_cfg_file.open("a", encoding="utf-8") as f:
815 f.write(
816 f'\npre_bump_hooks = ["{pre_bump_hook}"]\n'
817 f'post_bump_hooks = ["{post_bump_hook}"]\n'
818 )
819
820 run_mock = mocker.Mock()
821 mocker.patch.object(hooks, "run", run_mock)
822
823 util.create_file_and_commit(commit_msg)
824 util.run_cli("bump", "--yes")
825
826 assert git.tag_exist("0.2.0") is True
827
828 run_mock.assert_has_calls(
829 [
830 call(
831 [pre_bump_hook],
832 _env_prefix="CZ_PRE_",
833 is_initial=True,
834 current_version="0.1.0",
835 current_tag_version="0.1.0",
836 new_version="0.2.0",
837 new_tag_version="0.2.0",
838 message="bump: version 0.1.0 → 0.2.0",
839 increment="MINOR",
840 changelog_file_name=None,
841 ),
842 call(
843 [post_bump_hook],
844 _env_prefix="CZ_POST_",
845 was_initial=True,
846 previous_version="0.1.0",
847 previous_tag_version="0.1.0",
848 current_version="0.2.0",
849 current_tag_version="0.2.0",
850 message="bump: version 0.1.0 → 0.2.0",
851 increment="MINOR",
852 changelog_file_name=None,
853 ),
854 ]
855 )
856
857
858 def test_bump_with_hooks_and_increment(
859 mocker: MockFixture, tmp_commitizen_project, util: UtilFixture
860 ):
861 pre_bump_hook = "scripts/pre_bump_hook.sh"
862 post_bump_hook = "scripts/post_bump_hook.sh"
863
864 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
865 with tmp_commitizen_cfg_file.open("a", encoding="utf-8") as f:
866 f.write(
867 f'\npre_bump_hooks = ["{pre_bump_hook}"]\n'
868 f'post_bump_hooks = ["{post_bump_hook}"]\n'
869 )
870
871 run_mock = mocker.Mock()
872 mocker.patch.object(hooks, "run", run_mock)
873
874 util.create_file_and_commit("test: some test")
875 util.run_cli("bump", "--yes", "--increment", "MINOR")
876
877 assert git.tag_exist("0.2.0") is True
878
879
880 @pytest.mark.usefixtures("tmp_git_project")
881 def test_bump_use_version_provider(mocker: MockFixture, util: UtilFixture):
882 mock = mocker.MagicMock(name="provider")
883 mock.get_version.return_value = "0.0.0"
884 get_provider = mocker.patch(
885 "commitizen.commands.bump.get_provider", return_value=mock
886 )
887
888 util.create_file_and_commit("fix: fake commit")
889 util.run_cli("bump", "--yes", "--changelog")
890
891 assert git.tag_exist("0.0.1") is True
892 get_provider.assert_called_once()
893 mock.get_version.assert_called_once()
894 mock.set_version.assert_called_once_with("0.0.1")
895
896
897 def test_bump_command_prerelease_scheme_via_cli(
898 tmp_commitizen_project_initial, util: UtilFixture
899 ):
900 tmp_commitizen_project = tmp_commitizen_project_initial()
901 tmp_version_file = tmp_commitizen_project / "__version__.py"
902 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
903
904 util.run_cli(
905 "bump",
906 "--prerelease",
907 "alpha",
908 "--yes",
909 "--version-scheme",
910 "semver",
911 )
912 assert git.tag_exist("0.2.0-a0") is True
913
914 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
915 assert "0.2.0-a0" in version_file.read_text(encoding="utf-8")
916
917 # PRERELEASE BUMP CREATES VERSION WITHOUT PRERELEASE
918 util.run_cli("bump", "--yes")
919 assert git.tag_exist("0.2.0") is True
920
921 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
922 assert "0.2.0" in version_file.read_text(encoding="utf-8")
923
924
925 def test_bump_command_prerelease_scheme_via_config(
926 tmp_commitizen_project_initial, util: UtilFixture
927 ):
928 tmp_commitizen_project = tmp_commitizen_project_initial(
929 config_extra='version_scheme = "semver"\n',
930 )
931 tmp_version_file = tmp_commitizen_project / "__version__.py"
932 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
933
934 util.run_cli("bump", "--prerelease", "alpha", "--yes")
935 assert git.tag_exist("0.2.0-a0") is True
936
937 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
938 assert "0.2.0-a0" in version_file.read_text(encoding="utf-8")
939
940 util.run_cli("bump", "--prerelease", "alpha", "--yes")
941 assert git.tag_exist("0.2.0-a1") is True
942
943 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
944 assert "0.2.0-a1" in version_file.read_text(encoding="utf-8")
945
946 # PRERELEASE BUMP CREATES VERSION WITHOUT PRERELEASE
947 util.run_cli("bump", "--yes")
948 assert git.tag_exist("0.2.0") is True
949
950 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
951 assert "0.2.0" in version_file.read_text(encoding="utf-8")
952
953
954 def test_bump_command_prerelease_scheme_check_old_tags(
955 tmp_commitizen_project_initial, util: UtilFixture
956 ):
957 tmp_commitizen_project = tmp_commitizen_project_initial(
958 config_extra=('tag_format = "v$version"\nversion_scheme = "semver"\n'),
959 )
960 tmp_version_file = tmp_commitizen_project / "__version__.py"
961 tmp_commitizen_cfg_file = tmp_commitizen_project / "pyproject.toml"
962
963 util.run_cli("bump", "--prerelease", "alpha", "--yes")
964 assert git.tag_exist("v0.2.0-a0") is True
965
966 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
967 assert "0.2.0-a0" in version_file.read_text(encoding="utf-8")
968
969 util.run_cli("bump", "--prerelease", "alpha")
970 assert git.tag_exist("v0.2.0-a1") is True
971
972 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
973 assert "0.2.0-a1" in version_file.read_text(encoding="utf-8")
974
975 # PRERELEASE BUMP CREATES VERSION WITHOUT PRERELEASE
976 util.run_cli("bump")
977 assert git.tag_exist("v0.2.0") is True
978
979 for version_file in [tmp_version_file, tmp_commitizen_cfg_file]:
980 assert "0.2.0" in version_file.read_text(encoding="utf-8")
981
982
983 @pytest.mark.usefixtures("tmp_commitizen_project")
984 @pytest.mark.usefixtures("use_cz_semver")
985 @pytest.mark.parametrize(
986 ("message", "expected_tag"),
987 [
988 ("minor: add users", "0.2.0"),
989 ("patch: bug affecting users", "0.1.1"),
990 ("major: bug affecting users", "1.0.0"),
991 ],
992 )
993 def test_bump_with_plugin(util: UtilFixture, message: str, expected_tag: str):
994 util.create_file_and_commit(message)
995 util.run_cli("--name", "cz_semver", "bump", "--yes")
996 assert git.tag_exist(expected_tag) is True
997
998
999 @pytest.mark.usefixtures("tmp_commitizen_project")
1000 @pytest.mark.usefixtures("use_cz_semver")
1001 @pytest.mark.parametrize(
1002 ("message", "expected_tag"),
1003 [
1004 ("minor: add users", "0.2.0"),
1005 ("patch: bug affecting users", "0.1.1"),
1006 ("major: bug affecting users", "0.2.0"),
1007 ],
1008 )
1009 def test_bump_with_major_version_zero_with_plugin(
1010 util: UtilFixture, message: str, expected_tag: str
1011 ):
1012 util.create_file_and_commit(message)
1013 util.run_cli("--name", "cz_semver", "bump", "--yes", "--major-version-zero")
1014 assert git.tag_exist(expected_tag) is True
1015
1016
1017 @pytest.mark.usefixtures("tmp_commitizen_project")
1018 def test_bump_command_version_type_deprecation(util: UtilFixture):
1019 util.create_file_and_commit("feat: check deprecation on --version-type")
1020
1021 with pytest.warns(DeprecationWarning, match=r".*--version-type.*deprecated"):
1022 util.run_cli(
1023 "bump",
1024 "--prerelease",
1025 "alpha",
1026 "--yes",
1027 "--version-type",
1028 "semver",
1029 )
1030
1031 assert git.tag_exist("0.2.0-a0") is True
1032
1033
1034 @pytest.mark.usefixtures("tmp_commitizen_project")
1035 def test_bump_command_version_scheme_priority_over_version_type(util: UtilFixture):
1036 util.create_file_and_commit("feat: check deprecation on --version-type")
1037
1038 with pytest.warns(DeprecationWarning, match=r".*--version-type.*deprecated"):
1039 util.run_cli(
1040 "bump",
1041 "--prerelease",
1042 "alpha",
1043 "--yes",
1044 "--version-type",
1045 "semver",
1046 "--version-scheme",
1047 "pep440",
1048 )
1049
1050 assert git.tag_exist("0.2.0a0") is True
1051
1052
1053 @pytest.mark.parametrize(
1054 ("arg", "cfg", "expected"),
1055 [
1056 pytest.param("", "", "default", id="default"),
1057 pytest.param("", "changelog.cfg", "from config", id="from-config"),
1058 pytest.param(
1059 "--template=changelog.cmd", "changelog.cfg", "from cmd", id="from-command"
1060 ),
1061 ],
1062 )
1063 def test_bump_template_option_precedence(
1064 tmp_commitizen_project: Path,
1065 util: UtilFixture,
1066 any_changelog_format: ChangelogFormat,
1067 arg: str,
1068 cfg: str,
1069 expected: str,
1070 ):
1071 project_root = tmp_commitizen_project
1072 cfg_template = project_root / "changelog.cfg"
1073 cmd_template = project_root / "changelog.cmd"
1074 default_template = project_root / any_changelog_format.template
1075 changelog = project_root / any_changelog_format.default_changelog_file
1076
1077 cfg_template.write_text("from config")
1078 cmd_template.write_text("from cmd")
1079 default_template.write_text("default")
1080
1081 util.create_file_and_commit("feat: new file")
1082
1083 if cfg:
1084 pyproject = project_root / "pyproject.toml"
1085 pyproject.write_text(
1086 dedent(
1087 f"""\
1088 [tool.commitizen]
1089 version = "0.1.0"
1090 template = "{cfg}"
1091 """
1092 )
1093 )
1094
1095 args = ["bump", "--yes", "--changelog"]
1096 if arg:
1097 args.append(arg)
1098 args.append("0.1.1")
1099 util.run_cli(*args)
1100
1101 assert changelog.read_text() == expected
1102
1103
1104 def test_bump_template_extras_precedence(
1105 tmp_commitizen_project: Path,
1106 util: UtilFixture,
1107 any_changelog_format: ChangelogFormat,
1108 mock_plugin: BaseCommitizen,
1109 ):
1110 project_root = tmp_commitizen_project
1111 changelog_tpl = project_root / any_changelog_format.template
1112 changelog_tpl.write_text("{{first}} - {{second}} - {{third}}")
1113
1114 mock_plugin.template_extras = dict(
1115 first="from-plugin", second="from-plugin", third="from-plugin"
1116 )
1117
1118 pyproject = project_root / "pyproject.toml"
1119 pyproject.write_text(
1120 dedent(
1121 """\
1122 [tool.commitizen]
1123 version = "0.1.0"
1124 [tool.commitizen.extras]
1125 first = "from-config"
1126 second = "from-config"
1127 """
1128 )
1129 )
1130
1131 util.create_file_and_commit("feat: new file")
1132
1133 util.run_cli(
1134 "bump",
1135 "--yes",
1136 "--changelog",
1137 "--extra",
1138 "first=from-command",
1139 "0.1.1",
1140 )
1141
1142 changelog = project_root / any_changelog_format.default_changelog_file
1143 assert changelog.read_text() == "from-command - from-config - from-plugin"
1144
1145
1146 def test_bump_template_extra_quotes(
1147 tmp_commitizen_project: Path,
1148 util: UtilFixture,
1149 any_changelog_format: ChangelogFormat,
1150 ):
1151 project_root = tmp_commitizen_project
1152 changelog_tpl = project_root / any_changelog_format.template
1153 changelog_tpl.write_text("{{first}} - {{second}} - {{third}}")
1154
1155 util.create_file_and_commit("feat: new file")
1156
1157 util.run_cli(
1158 "bump",
1159 "--changelog",
1160 "--yes",
1161 "-e",
1162 "first=no-quote",
1163 "-e",
1164 "second='single quotes'",
1165 "-e",
1166 'third="double quotes"',
1167 "0.1.1",
1168 )
1169
1170 changelog = project_root / any_changelog_format.default_changelog_file
1171 assert changelog.read_text() == "no-quote - single quotes - double quotes"
1172
1173
1174 def test_bump_changelog_contains_increment_only(
1175 tmp_commitizen_project: Path, util: UtilFixture, capsys: pytest.CaptureFixture
1176 ):
1177 """Issue 1024"""
1178 # Initialize commitizen up to v1.0.0
1179 project_root = tmp_commitizen_project
1180 tmp_commitizen_cfg_file = project_root / "pyproject.toml"
1181 tmp_commitizen_cfg_file.write_text(
1182 '[tool.commitizen]\nversion="1.0.0"\nupdate_changelog_on_bump = true\n'
1183 )
1184 tmp_changelog_file = project_root / "CHANGELOG.md"
1185 tmp_changelog_file.write_text("## v1.0.0")
1186 util.create_file_and_commit("feat(user): new file")
1187 util.create_tag("v1.0.0")
1188
1189 # Add a commit and bump to v2.0.0
1190 util.create_file_and_commit("feat(user)!: new file")
1191 util.run_cli("bump", "--yes")
1192 _ = capsys.readouterr()
1193
1194 # Add a commit and create the incremental changelog to v3.0.0
1195 # it should only include v3 changes
1196 util.create_file_and_commit("feat(next)!: next version")
1197 with pytest.raises(ExpectedExit):
1198 util.run_cli("bump", "--yes", "--version-files-only", "--changelog-to-stdout")
1199 out, _ = capsys.readouterr()
1200
1201 assert "3.0.0" in out
1202 assert "2.0.0" not in out
1203
1204
1205 @pytest.mark.usefixtures("tmp_commitizen_project")
1206 def test_bump_get_next(util: UtilFixture, capsys: pytest.CaptureFixture):
1207 util.create_file_and_commit("feat: new file")
1208
1209 with pytest.raises(DryRunExit):
1210 util.run_cli("bump", "--yes", "--get-next")
1211
1212 out, _ = capsys.readouterr()
1213 assert "0.2.0" in out
1214 assert git.tag_exist("0.2.0") is False
1215
1216
1217 @pytest.mark.usefixtures("tmp_commitizen_project")
1218 def test_bump_get_next_update_changelog_on_bump(
1219 util: UtilFixture, capsys: pytest.CaptureFixture, config_path: Path
1220 ):
1221 util.create_file_and_commit("feat: new file")
1222 with config_path.open("a", encoding="utf-8") as fp:
1223 fp.write("update_changelog_on_bump = true\n")
1224
1225 with pytest.raises(DryRunExit):
1226 util.run_cli("bump", "--yes", "--get-next")
1227
1228 out, _ = capsys.readouterr()
1229 assert "0.2.0" in out
1230 assert git.tag_exist("0.2.0") is False
1231
1232
1233 @pytest.mark.usefixtures("tmp_commitizen_project")
1234 def test_bump_get_next__no_eligible_commits_raises(util: UtilFixture):
1235 util.create_file_and_commit("chore: new commit")
1236
1237 with pytest.raises(NoneIncrementExit):
1238 util.run_cli("bump", "--yes", "--get-next")
1239
1240
1241 def test_bump_allow_no_commit_with_no_commit(
1242 tmp_commitizen_project, monkeypatch, util: UtilFixture, capsys
1243 ):
1244 monkeypatch.chdir(tmp_commitizen_project)
1245 # Create the first commit and bump to 1.0.0
1246 util.create_file_and_commit("feat(user)!: new file")
1247 util.run_cli("bump", "--yes")
1248
1249 # Verify NoCommitsFoundError should be raised
1250 # when there's no new commit and "--allow-no-commit" is not set
1251 with pytest.raises(NoCommitsFoundError):
1252 util.run_cli("bump")
1253
1254 # bump to 1.0.1 with new commit when "--allow-no-commit" is set
1255 util.run_cli("bump", "--allow-no-commit")
1256 out, _ = capsys.readouterr()
1257 assert "bump: version 1.0.0 → 1.0.1" in out
1258
1259
1260 def test_bump_allow_no_commit_with_no_eligible_commit(
1261 tmp_commitizen_project, monkeypatch, util: UtilFixture, capsys
1262 ):
1263 monkeypatch.chdir(tmp_commitizen_project)
1264 # Create the first commit and bump to 1.0.0
1265 util.create_file_and_commit("feat(user)!: new file")
1266 util.run_cli("bump", "--yes")
1267
1268 # Create a commit that is ineligible to bump
1269 util.create_file_and_commit("docs(bump): add description for allow no commit")
1270
1271 # Verify NoneIncrementExit should be raised
1272 # when there's no eligible bumping commit and "--allow-no-commit" is not set
1273 with pytest.raises(NoneIncrementExit):
1274 util.run_cli("bump", "--yes")
1275
1276 # bump to 1.0.1 with ineligible commit when "--allow-no-commit" is set
1277 util.run_cli("bump", "--allow-no-commit")
1278 out, _ = capsys.readouterr()
1279 assert "bump: version 1.0.0 → 1.0.1" in out
1280
1281
1282 def test_bump_allow_no_commit_with_increment(
1283 tmp_commitizen_project, monkeypatch, util: UtilFixture, capsys
1284 ):
1285 monkeypatch.chdir(tmp_commitizen_project)
1286 # # Create the first commit and bump to 1.0.0
1287 util.create_file_and_commit("feat(user)!: new file")
1288 util.run_cli("bump", "--yes")
1289
1290 # Verify NoCommitsFoundError should be raised
1291 # when there's no new commit and "--allow-no-commit" is not set
1292 with pytest.raises(NoCommitsFoundError):
1293 util.run_cli("bump", "--yes")
1294
1295 # bump to 1.1.0 with no new commit when "--allow-no-commit" is set
1296 # and increment is specified
1297 util.run_cli("bump", "--yes", "--allow-no-commit", "--increment", "MINOR")
1298 out, _ = capsys.readouterr()
1299 assert "bump: version 1.0.0 → 1.1.0" in out
1300
1301
1302 def test_bump_allow_no_commit_with_manual_version(
1303 tmp_commitizen_project, monkeypatch, util: UtilFixture, capsys
1304 ):
1305 monkeypatch.chdir(tmp_commitizen_project)
1306 # # Create the first commit and bump to 1.0.0
1307 util.create_file_and_commit("feat(user)!: new file")
1308 util.run_cli("bump", "--yes")
1309
1310 # Verify NoCommitsFoundError should be raised
1311 # when there's no new commit and "--allow-no-commit" is not set
1312 with pytest.raises(NoCommitsFoundError):
1313 util.run_cli("bump", "--yes")
1314
1315 # bump to 1.1.0 with no new commit when "--allow-no-commit" is set
1316 # and increment is specified
1317 util.run_cli("bump", "--yes", "--allow-no-commit", "2.0.0")
1318 out, _ = capsys.readouterr()
1319 assert "bump: version 1.0.0 → 2.0.0" in out
1320
1321
1322 def test_bump_detect_legacy_tags_from_scm(
1323 tmp_commitizen_project: Path, util: UtilFixture
1324 ):
1325 project_root = tmp_commitizen_project
1326 tmp_commitizen_cfg_file = project_root / "pyproject.toml"
1327 tmp_commitizen_cfg_file.write_text(
1328 "\n".join(
1329 [
1330 "[tool.commitizen]",
1331 'version_provider = "scm"',
1332 'tag_format = "v$version"',
1333 "legacy_tag_formats = [",
1334 ' "legacy-${version}"',
1335 "]",
1336 ]
1337 ),
1338 )
1339 util.create_file_and_commit("feat: new file")
1340 util.create_tag("legacy-0.4.2")
1341 util.create_file_and_commit("feat: new file")
1342
1343 util.run_cli("bump", "--increment", "patch", "--changelog")
1344
1345 assert git.tag_exist("v0.4.3") is True
1346
1347
1348 def test_bump_warn_but_dont_fail_on_invalid_tags(
1349 tmp_commitizen_project: Path,
1350 util: UtilFixture,
1351 capsys: pytest.CaptureFixture,
1352 ):
1353 project_root = tmp_commitizen_project
1354 tmp_commitizen_cfg_file = project_root / "pyproject.toml"
1355 tmp_commitizen_cfg_file.write_text(
1356 "\n".join(
1357 [
1358 "[tool.commitizen]",
1359 'version_provider = "scm"',
1360 'version_scheme = "pep440"',
1361 ]
1362 ),
1363 )
1364 util.create_file_and_commit("feat: new file")
1365 util.create_tag("0.4.2")
1366 util.create_file_and_commit("feat: new file")
1367 util.create_tag("0.4.3.deadbeaf")
1368 util.create_file_and_commit("feat: new file")
1369
1370 util.run_cli("bump", "--increment", "patch", "--changelog")
1371
1372 _, err = capsys.readouterr()
1373
1374 assert err.count("Invalid version tag: '0.4.3.deadbeaf'") == 1
1375 assert git.tag_exist("0.4.3") is True
1376
1377
1378 def test_is_initial_tag(mocker: MockFixture, tmp_commitizen_project, util: UtilFixture):
1379 """Test the _is_initial_tag method behavior."""
1380 # Create a commit but no tags
1381 util.create_file_and_commit("feat: initial commit")
1382
1383 # Initialize Bump with minimal config
1384 config = BaseConfig()
1385 config.settings.update(
1386 {
1387 "name": defaults.DEFAULT_SETTINGS["name"],
1388 "encoding": "utf-8",
1389 "pre_bump_hooks": [],
1390 "post_bump_hooks": [],
1391 }
1392 )
1393
1394 # Initialize with required arguments
1395 arguments = {
1396 "changelog": False,
1397 "changelog_to_stdout": False,
1398 "git_output_to_stderr": False,
1399 "no_verify": False,
1400 "check_consistency": False,
1401 "retry": False,
1402 "version_scheme": None,
1403 "file_name": None,
1404 "template": None,
1405 "extras": None,
1406 }
1407
1408 bump_cmd = bump.Bump(config, arguments) # type: ignore[arg-type]
1409
1410 # Test case 1: No current tag, not yes mode
1411 mocker.patch("questionary.confirm", return_value=mocker.Mock(ask=lambda: True))
1412 assert bump_cmd._is_initial_tag(None, is_yes=False) is True
1413
1414 # Test case 2: No current tag, yes mode
1415 assert bump_cmd._is_initial_tag(None, is_yes=True) is True
1416
1417 # Test case 3: Has current tag
1418 mock_tag = mocker.Mock()
1419 assert bump_cmd._is_initial_tag(mock_tag, is_yes=False) is False
1420
1421 # Test case 4: No current tag, user denies
1422 mocker.patch("questionary.confirm", return_value=mocker.Mock(ask=lambda: False))
1423 assert bump_cmd._is_initial_tag(None, is_yes=False) is False
1424
1425
1426 @pytest.mark.parametrize("test_input", ["rc", "alpha", "beta"])
1427 @pytest.mark.usefixtures("tmp_commitizen_project")
1428 @pytest.mark.freeze_time("2025-01-01")
1429 def test_changelog_config_flag_merge_prerelease(
1430 mocker: MockFixture,
1431 util: UtilFixture,
1432 changelog_path: Path,
1433 config_path: Path,
1434 file_regression: FileRegressionFixture,
1435 test_input: str,
1436 ):
1437 with config_path.open("a") as f:
1438 f.write("changelog_merge_prerelease = true\n")
1439 f.write("update_changelog_on_bump = true\n")
1440 f.write("annotated_tag = true\n")
1441
1442 util.create_file_and_commit("irrelevant commit")
1443 mocker.patch("commitizen.git.GitTag.date", "1970-01-01")
1444 git.tag("0.1.0")
1445
1446 util.create_file_and_commit("feat: add new output")
1447 util.create_file_and_commit("fix: output glitch")
1448 util.run_cli("bump", "--prerelease", test_input, "--yes")
1449
1450 util.run_cli("bump", "--changelog")
1451
1452 out = changelog_path.read_text()
1453
1454 file_regression.check(out, extension=".md")
1455
1456
1457 @pytest.mark.parametrize("test_input", ["rc", "alpha", "beta"])
1458 @pytest.mark.usefixtures("tmp_commitizen_project")
1459 @pytest.mark.freeze_time("2025-01-01")
1460 def test_changelog_config_flag_merge_prerelease_only_prerelease_present(
1461 util: UtilFixture,
1462 changelog_path: Path,
1463 config_path: Path,
1464 file_regression: FileRegressionFixture,
1465 test_input: str,
1466 ):
1467 with config_path.open("a") as f:
1468 f.write("changelog_merge_prerelease = true\n")
1469 f.write("update_changelog_on_bump = true\n")
1470 f.write("annotated_tag = true\n")
1471
1472 util.create_file_and_commit("feat: more relevant commit")
1473 util.run_cli("bump", "--prerelease", test_input, "--yes")
1474
1475 util.create_file_and_commit("feat: add new output")
1476 util.create_file_and_commit("fix: output glitch")
1477 util.run_cli("bump", "--prerelease", test_input, "--yes")
1478
1479 util.run_cli("bump", "--changelog")
1480
1481 out = changelog_path.read_text()
1482
1483 file_regression.check(out, extension=".md")
1484
1485
1486 @pytest.mark.usefixtures("tmp_commitizen_project")
1487 def test_bump_deprecate_files_only(util: UtilFixture):
1488 util.create_file_and_commit("feat: new file")
1489 with (
1490 pytest.warns(DeprecationWarning, match=r".*--files-only.*deprecated"),
1491 pytest.raises(ExpectedExit),
1492 ):
1493 util.run_cli("bump", "--yes", "--files-only")
1494
1495
1496 @pytest.mark.parametrize(
1497 ("prerelease", "merge"),
1498 [
1499 pytest.param(True, "true", id="with_prerelease_merge"),
1500 pytest.param(True, "false", id="with_prerelease_no_merge"),
1501 pytest.param(False, "true", id="without_prerelease"),
1502 ],
1503 )
1504 @pytest.mark.usefixtures("tmp_commitizen_project")
1505 @pytest.mark.freeze_time("2025-01-01")
1506 def test_changelog_merge_preserves_header(
1507 mocker: MockFixture,
1508 util: UtilFixture,
1509 changelog_path: Path,
1510 config_path: Path,
1511 file_regression: FileRegressionFixture,
1512 prerelease: bool,
1513 merge: str,
1514 ):
1515 """Test that merge_prerelease preserves existing changelog header."""
1516 with config_path.open("a") as f:
1517 f.write(f"changelog_merge_prerelease = {merge}\n")
1518 f.write("update_changelog_on_bump = true\n")
1519 f.write("annotated_tag = true\n")
1520
1521 # Create initial version with changelog that has a header
1522 util.create_file_and_commit("irrelevant commit")
1523 mocker.patch("commitizen.git.GitTag.date", "1970-01-01")
1524 git.tag("0.1.0")
1525
1526 # Create a changelog with a header manually
1527 changelog_path.write_text(
1528 dedent("""\
1529 # Changelog
1530
1531 All notable changes to this project will be documented here.
1532
1533 ## 0.1.0 (1970-01-01)
1534 """)
1535 )
1536
1537 util.create_file_and_commit("feat: add new output")
1538 util.create_file_and_commit("fix: output glitch")
1539
1540 if prerelease:
1541 util.run_cli("bump", "--prerelease", "alpha", "--yes")
1542
1543 util.create_file_and_commit("feat: new feature right before the bump")
1544 util.run_cli("bump", "--changelog")
1545
1546 out = changelog_path.read_text()
1547
1548 file_regression.check(out, extension=".md")
1549
1550
1551 @pytest.mark.freeze_time("2025-01-01")
1552 def test_bump_allow_no_commit_issue(
1553 tmp_commitizen_project_initial,
1554 util: UtilFixture,
1555 ) -> None:
1556 """Issue #1866: bump command called changelog command with allow_no_commit=True, but changelog command raised NoCommitsFoundError"""
1557 tmp_commitizen_project_initial(
1558 version="1.0.0", config_extra="update_changelog_on_bump = true\n"
1559 )
1560 util.run_cli("bump", "--yes", "--allow-no-commit", "--prerelease", "beta")
1561 util.run_cli(
1562 "bump", "--allow-no-commit", "--prerelease", "rc"
1563 ) # Should not fail when changelog generation runs with no new commits