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