Debian Codegraph @

tests/test_git.py

raw
1 from __future__ import annotations
2
3 import inspect
4 import os
5 from pathlib import Path
6 from typing import TYPE_CHECKING
7
8 import pytest
9
10 from commitizen import cmd, git
11 from commitizen.exceptions import GitCommandError
12
13 if TYPE_CHECKING:
14 from pytest_gitconfig import GitConfig
15 from pytest_mock import MockFixture
16
17 from tests.utils import UtilFixture
18
19
20 @pytest.mark.parametrize("date", ["2020-01-21", "1970-01-01"])
21 def test_git_tag_date(date: str):
22 git_tag = git.GitTag(rev="sha1-code", name="0.0.1", date="2025-05-30")
23 git_tag.date = date
24 assert git_tag.date == date
25
26
27 def test_git_object_eq():
28 git_commit = git.GitCommit(
29 rev="sha1-code", title="this is title", body="this is body"
30 )
31 git_tag = git.GitTag(rev="sha1-code", name="0.0.1", date="2020-01-21")
32
33 assert git_commit == git_tag
34 assert git_commit != "sha1-code"
35
36
37 def test_get_tags(util: UtilFixture):
38 tag_str = (
39 "v1.0.0---inner_delimiter---333---inner_delimiter---2020-01-20---inner_delimiter---\n"
40 "v0.5.0---inner_delimiter---222---inner_delimiter---2020-01-17---inner_delimiter---\n"
41 "v0.0.1---inner_delimiter---111---inner_delimiter---2020-01-17---inner_delimiter---\n"
42 )
43 util.mock_cmd(out=tag_str)
44
45 git_tags = git.get_tags()
46 latest_git_tag = git_tags[0]
47 assert latest_git_tag.rev == "333"
48 assert latest_git_tag.name == "v1.0.0"
49 assert latest_git_tag.date == "2020-01-20"
50
51 util.mock_cmd(out="", err="No tag available")
52 assert git.get_tags() == []
53
54
55 @pytest.mark.usefixtures("tmp_commitizen_project")
56 def test_get_reachable_tags(util: UtilFixture):
57 util.create_file_and_commit("Initial state")
58 util.create_tag("1.0.0")
59 # create develop
60 util.create_branch("develop")
61 util.switch_branch("develop")
62
63 # add a feature to develop
64 util.create_file_and_commit("develop")
65 util.create_tag("1.1.0b0")
66
67 # create staging
68 util.switch_branch("master")
69 util.create_file_and_commit("master")
70 util.create_tag("1.0.1")
71
72 tags = git.get_tags(reachable_only=True)
73 tag_names = set([t.name for t in tags])
74 # 1.1.0b0 is not present
75 assert tag_names == {"1.0.0", "1.0.1"}
76
77
78 @pytest.mark.usefixtures("tmp_commitizen_project")
79 @pytest.mark.parametrize("locale", ["en_US", "fr_FR"])
80 def test_get_reachable_tags_with_commits(locale: str, monkeypatch: pytest.MonkeyPatch):
81 monkeypatch.setenv("LANG", f"{locale}.UTF-8")
82 monkeypatch.setenv("LANGUAGE", f"{locale}.UTF-8")
83 monkeypatch.setenv("LC_ALL", f"{locale}.UTF-8")
84 assert git.get_tags(reachable_only=True) == []
85
86
87 def test_get_tag_names(util: UtilFixture):
88 tag_str = "v1.0.0\nv0.5.0\nv0.0.1\n"
89 util.mock_cmd(out=tag_str)
90
91 assert git.get_tag_names() == ["v1.0.0", "v0.5.0", "v0.0.1"]
92
93 util.mock_cmd(out="", err="No tag available")
94 assert git.get_tag_names() == []
95
96
97 def test_git_message_with_empty_body():
98 commit_title = "Some Title"
99 commit = git.GitCommit("test_rev", "Some Title", body="")
100
101 assert commit.message == commit_title
102
103
104 @pytest.mark.usefixtures("tmp_commitizen_project")
105 def test_get_log_as_str_list_empty():
106 """
107 Ensure an exception is raised or empty list in an empty project.
108 The behavior is different depending on the version of git.
109 """
110 try:
111 gitlog = git._get_log_as_str_list(start=None, end="HEAD", args=[])
112 except GitCommandError:
113 return
114 assert len(gitlog) == 0, "list should be empty if no assert"
115
116
117 @pytest.mark.usefixtures("tmp_commitizen_project")
118 def test_get_commits(util: UtilFixture):
119 util.create_file_and_commit("feat(users): add username")
120 util.create_file_and_commit("fix: username exception")
121 commits = git.get_commits()
122 assert len(commits) == 2
123
124
125 @pytest.mark.usefixtures("tmp_commitizen_project")
126 def test_get_commits_author_and_email(util: UtilFixture):
127 util.create_file_and_commit("fix: username exception")
128 commit = git.get_commits()[0]
129
130 assert commit.author != ""
131 assert "@" in commit.author_email
132
133
134 def test_get_commits_without_email(util: UtilFixture):
135 raw_commit = (
136 "a515bb8f71c403f6f7d1c17b9d8ebf2ce3959395\n"
137 "95bbfc703eb99cb49ba0d6ffd8469911303dbe63 12d3b4bdaa996ea7067a07660bb5df4772297bdd\n"
138 "\n"
139 "user name\n"
140 "\n"
141 "----------commit-delimiter----------\n"
142 "12d3b4bdaa996ea7067a07660bb5df4772297bdd\n"
143 "de33bc5070de19600f2f00262b3c15efea762408\n"
144 "feat(users): add username\n"
145 "user name\n"
146 "\n"
147 "----------commit-delimiter----------\n"
148 )
149 util.mock_cmd(out=raw_commit)
150
151 commits = git.get_commits()
152
153 assert commits[0].author == "user name"
154 assert commits[1].author == "user name"
155
156 assert commits[0].author_email == ""
157 assert commits[1].author_email == ""
158
159 assert commits[0].title == ""
160 assert commits[1].title == "feat(users): add username"
161
162
163 def test_get_commits_without_breakline_in_each_commit(util: UtilFixture):
164 raw_commit = (
165 "ae9ba6fc5526cf478f52ef901418d85505109744\n"
166 "ff2f56ca844de72a9d59590831087bf5a97bac84\n"
167 "bump: version 2.13.0 → 2.14.0\n"
168 "GitHub Action\n"
169 "[email protected]\n"
170 "----------commit-delimiter----------\n"
171 "ff2f56ca844de72a9d59590831087bf5a97bac84\n"
172 "b4dc83284dc8c9729032a774a037df1d1f2397d5 20a54bf1b82cd7b573351db4d1e8814dd0be205d\n"
173 "Merge pull request #332 from cliles/feature/271-redux\n"
174 "User\n"
175 "[email protected]\n"
176 "Feature/271 redux----------commit-delimiter----------\n"
177 "20a54bf1b82cd7b573351db4d1e8814dd0be205d\n"
178 "658f38c3fe832cdab63ed4fb1f7b3a0969a583be\n"
179 "feat(#271): enable creation of annotated tags when bumping\n"
180 "User 2\n"
181 "[email protected]\n"
182 "----------commit-delimiter----------\n"
183 )
184 util.mock_cmd(out=raw_commit)
185
186 commits = git.get_commits()
187
188 assert commits[0].author == "GitHub Action"
189 assert commits[1].author == "User"
190 assert commits[2].author == "User 2"
191
192 assert commits[0].author_email == "[email protected]"
193 assert commits[1].author_email == "[email protected]"
194 assert commits[2].author_email == "[email protected]"
195
196 assert commits[0].title == "bump: version 2.13.0 → 2.14.0"
197 assert commits[1].title == "Merge pull request #332 from cliles/feature/271-redux"
198 assert (
199 commits[2].title == "feat(#271): enable creation of annotated tags when bumping"
200 )
201
202
203 def test_get_commits_with_and_without_parents(util: UtilFixture):
204 raw_commit = (
205 "4206e661bacf9643373255965f34bbdb382cb2b9\n"
206 "ae9ba6fc5526cf478f52ef901418d85505109744 bf8479e7aa1a5b9d2f491b79e3a4d4015519903e\n"
207 "Merge pull request from someone\n"
208 "Maintainer\n"
209 "[email protected]\n"
210 "This is a much needed feature----------commit-delimiter----------\n"
211 "ae9ba6fc5526cf478f52ef901418d85505109744\n"
212 "ff2f56ca844de72a9d59590831087bf5a97bac84\n"
213 "Release 0.1.0\n"
214 "GitHub Action\n"
215 "[email protected]\n"
216 "----------commit-delimiter----------\n"
217 "ff2f56ca844de72a9d59590831087bf5a97bac84\n"
218 "\n"
219 "Initial commit\n"
220 "User\n"
221 "[email protected]\n"
222 "----------commit-delimiter----------\n"
223 )
224 util.mock_cmd(out=raw_commit)
225
226 commits = git.get_commits()
227
228 assert commits[0].author == "Maintainer"
229 assert commits[1].author == "GitHub Action"
230 assert commits[2].author == "User"
231
232 assert commits[0].author_email == "[email protected]"
233 assert commits[1].author_email == "[email protected]"
234 assert commits[2].author_email == "[email protected]"
235
236 assert commits[0].title == "Merge pull request from someone"
237 assert commits[1].title == "Release 0.1.0"
238 assert commits[2].title == "Initial commit"
239
240 assert commits[0].body == "This is a much needed feature"
241 assert commits[1].body == ""
242 assert commits[2].body == ""
243
244 assert commits[0].parents == [
245 "ae9ba6fc5526cf478f52ef901418d85505109744",
246 "bf8479e7aa1a5b9d2f491b79e3a4d4015519903e",
247 ]
248 assert commits[1].parents == ["ff2f56ca844de72a9d59590831087bf5a97bac84"]
249 assert commits[2].parents == []
250
251
252 @pytest.mark.usefixtures("in_repo_root")
253 def test_get_commits_with_signature(gitconfig: GitConfig):
254 # temporarily turn on --show-signature
255 gitconfig.set("log.showsignature", "true")
256
257 # retrieve a commit that we know has a signature
258 commit = git.get_commits(
259 start="bec20ebf433f2281c70f1eb4b0b6a1d0ed83e9b2",
260 end="9eae518235d051f145807ddf971ceb79ad49953a",
261 )[0]
262
263 assert commit.title.startswith("fix")
264
265
266 def test_get_tag_names_has_correct_arrow_annotation():
267 arrow_annotation = inspect.getfullargspec(git.get_tag_names).annotations["return"]
268
269 assert arrow_annotation == "list[str]"
270
271
272 @pytest.mark.usefixtures("tmp_commitizen_project")
273 def test_get_latest_tag_name(util: UtilFixture):
274 tag_name = git.get_latest_tag_name()
275 assert tag_name is None
276
277 util.create_file_and_commit("feat(test): test")
278 util.create_tag("1.0")
279 tag_name = git.get_latest_tag_name()
280 assert tag_name == "1.0"
281
282
283 @pytest.mark.usefixtures("tmp_commitizen_project")
284 def test_is_staging_clean_when_adding_file():
285 assert git.is_staging_clean() is True
286
287 Path("test_file").touch()
288
289 assert git.is_staging_clean() is True
290
291 cmd.run(["git", "add", "test_file"])
292
293 assert git.is_staging_clean() is False
294
295
296 @pytest.mark.usefixtures("tmp_commitizen_project")
297 def test_is_staging_clean_when_updating_file():
298 assert git.is_staging_clean() is True
299
300 Path("test_file").touch()
301 cmd.run(["git", "add", "test_file"])
302 cmd.run(["git", "commit", "-m", "add test_file"])
303 Path("test_file").write_text("test")
304
305 assert git.is_staging_clean() is True
306
307 cmd.run(["git", "add", "test_file"])
308
309 assert git.is_staging_clean() is False
310
311
312 @pytest.mark.usefixtures("tmp_commitizen_project")
313 def test_get_eol_for_open():
314 assert git.EOLType.for_open() == os.linesep
315
316 cmd.run(["git", "config", "core.eol", "lf"])
317 assert git.EOLType.for_open() == "\n"
318
319 cmd.run(["git", "config", "core.eol", "crlf"])
320 assert git.EOLType.for_open() == "\r\n"
321
322 cmd.run(["git", "config", "core.eol", "native"])
323 assert git.EOLType.for_open() == os.linesep
324
325
326 def test_get_core_editor(monkeypatch: pytest.MonkeyPatch, util: UtilFixture):
327 monkeypatch.setenv("GIT_EDITOR", "nano")
328 assert git.get_core_editor() == "nano"
329
330 monkeypatch.delenv("GIT_EDITOR")
331
332 util.mock_cmd(out="vim")
333 assert git.get_core_editor() == "vim"
334
335 util.mock_cmd()
336 assert git.get_core_editor() is None
337
338
339 @pytest.mark.usefixtures("tmp_commitizen_project")
340 def test_create_tag_with_message(util: UtilFixture):
341 util.create_file_and_commit("feat(test): test")
342 tag_name = "1.0"
343 tag_message = "test message"
344 util.create_tag(tag_name, tag_message)
345 assert git.get_latest_tag_name() == tag_name
346 assert git.get_tag_message(tag_name) == tag_message
347
348
349 @pytest.mark.parametrize(
350 ("file_path", "expected_cmd"),
351 [
352 (
353 "/tmp/temp file",
354 ["git", "commit", "--signoff", "-F", "/tmp/temp file"],
355 ),
356 (
357 "/tmp dir/temp file",
358 ["git", "commit", "--signoff", "-F", "/tmp dir/temp file"],
359 ),
360 (
361 "/tmp/tempfile",
362 ["git", "commit", "--signoff", "-F", "/tmp/tempfile"],
363 ),
364 ],
365 ids=[
366 "File contains spaces",
367 "Path contains spaces",
368 "Path does not contain spaces",
369 ],
370 )
371 def test_commit_with_spaces_in_path(
372 mocker: MockFixture, file_path: str, expected_cmd: list[str], util: UtilFixture
373 ):
374 mock_run = util.mock_cmd()
375 mock_unlink = mocker.patch("os.unlink")
376 mock_temp_file = mocker.patch("commitizen.git.NamedTemporaryFile")
377 mock_temp_file.return_value.name = file_path
378
379 git.commit("feat: new feature", ["--signoff"])
380
381 mock_run.assert_called_once_with(expected_cmd, env=None)
382 mock_unlink.assert_called_once_with(file_path)
383
384
385 @pytest.mark.usefixtures("tmp_commitizen_project")
386 def test_get_filenames_in_commit(util: UtilFixture):
387 """Test get_filenames_in_commit returns filenames from the last commit."""
388 util.create_file_and_commit("feat: old feature", filename="old_file.txt")
389
390 filename = "test_feature_file.txt"
391 util.create_file_and_commit("feat: add new feature", filename=filename)
392
393 filenames = git.get_filenames_in_commit()
394 assert [filename] == filenames
395
396
397 @pytest.mark.usefixtures("tmp_commitizen_project")
398 def test_get_filenames_in_commit_with_git_reference(util: UtilFixture):
399 """Test get_filenames_in_commit with a specific git reference (commit SHA)."""
400 first_filename = "first_feature.txt"
401 util.create_file_and_commit("feat: first feature", filename=first_filename)
402 first_commit_rev = cmd.run(["git", "rev-parse", "HEAD"]).out.strip()
403
404 second_filename = "second_feature.txt"
405 util.create_file_and_commit("feat: second feature", filename=second_filename)
406
407 # Query the first commit by its SHA
408 filenames = git.get_filenames_in_commit(git_reference=first_commit_rev)
409 assert first_filename in filenames
410 assert second_filename not in filenames
411
412
413 def test_get_filenames_in_commit_error(util: UtilFixture):
414 """Test that GitCommandError is raised when git command fails."""
415 util.mock_cmd(err="fatal: bad object HEAD", return_code=1)
416 with pytest.raises(GitCommandError, match="fatal: bad object HEAD"):
417 git.get_filenames_in_commit()
418
419
420 @pytest.mark.parametrize(
421 "linebreak", ["\n", "\r\n"], ids=["line_feed", "carriage_return"]
422 )
423 def test_git_commit_from_rev_and_commit(linebreak):
424 rev_and_commit = linebreak.join(
425 [
426 "abc123", # rev
427 "def456 ghi789", # parents
428 "feat: add new feature", # title
429 "John Doe", # author
430 "[email protected]", # author_email
431 "This is a detailed description", # body
432 "of the new feature",
433 "with multiple lines",
434 ]
435 )
436
437 commit = git.GitCommit.from_rev_and_commit(rev_and_commit)
438
439 assert commit.rev == "abc123"
440 assert commit.title == "feat: add new feature"
441 assert (
442 commit.body
443 == "This is a detailed description\nof the new feature\nwith multiple lines"
444 )
445 assert commit.author == "John Doe"
446 assert commit.author_email == "[email protected]"
447 assert commit.parents == ["def456", "ghi789"]
448
449 # Test with minimal data
450 minimal_commit = linebreak.join(
451 [
452 "abc123", # rev
453 "", # no parents
454 "feat: minimal commit", # title
455 "John Doe", # author
456 "[email protected]", # author_email
457 ]
458 )
459
460 commit = git.GitCommit.from_rev_and_commit(minimal_commit)
461
462 assert commit.rev == "abc123"
463 assert commit.title == "feat: minimal commit"
464 assert commit.body == ""
465 assert commit.author == "John Doe"
466 assert commit.author_email == "[email protected]"
467 assert commit.parents == []
468
469
470 @pytest.mark.parametrize(
471 "committer_date",
472 [
473 "2024-03-20",
474 None,
475 ],
476 )
477 def test_commit_uses_list_args_and_env(mocker: MockFixture, committer_date: str | None):
478 """Test that git.commit uses list-based subprocess (no shell injection)."""
479 mock_run = mocker.patch("commitizen.cmd.run")
480 mock_run.return_value = cmd.Command("", "", b"", b"", 0)
481
482 # We need to mock NamedTemporaryFile to control the file name
483 mock_file = mocker.MagicMock()
484 mock_file.name = "temp.txt"
485 mock_file.__enter__ = mocker.MagicMock(return_value=mock_file)
486 mock_file.__exit__ = mocker.MagicMock(return_value=False)
487 mocker.patch("commitizen.git.NamedTemporaryFile", return_value=mock_file)
488 mocker.patch("os.unlink")
489
490 git.commit(
491 "test message", args=["-a", "--no-verify"], committer_date=committer_date
492 )
493
494 call_args = mock_run.call_args
495 # First positional arg should be a list (no shell injection)
496 cmd_list = call_args[0][0]
497 assert isinstance(cmd_list, list)
498 assert cmd_list == ["git", "commit", "-a", "--no-verify", "-F", "temp.txt"]
499
500 if committer_date:
501 env = call_args[1]["env"]
502 assert env == {"GIT_COMMITTER_DATE": committer_date}
503 else:
504 env = call_args[1]["env"]
505 assert env is None
506
507
508 def test_get_default_branch_success(util: UtilFixture):
509 util.mock_cmd(out="refs/remotes/origin/main\n")
510 assert git.get_default_branch() == "refs/remotes/origin/main"
511
512
513 def test_get_default_branch_error(util: UtilFixture):
514 util.mock_cmd(
515 err="fatal: ref refs/remotes/origin/HEAD is not a symbolic ref", return_code=1
516 )
517 with pytest.raises(GitCommandError):
518 git.get_default_branch()