Debian Codegraph @

tests/test_conf.py

raw
1 from __future__ import annotations
2
3 import json
4 import os
5 import re
6 from pathlib import Path
7 from typing import Any
8
9 import pytest
10 import yaml
11
12 from commitizen import cmd, config, defaults, git
13 from commitizen.config.json_config import JsonConfig
14 from commitizen.config.toml_config import TomlConfig
15 from commitizen.config.yaml_config import YAMLConfig
16 from commitizen.exceptions import ConfigFileIsEmpty, InvalidConfigurationError
17
18 TOML_STR = """
19 [tool.commitizen]
20 name = "cz_jira"
21 version = "1.0.0"
22 version_files = [
23 "commitizen/__version__.py",
24 "pyproject.toml"
25 ]
26 style = [
27 ["pointer", "reverse"],
28 ["question", "underline"]
29 ]
30 pre_bump_hooks = [
31 "scripts/generate_documentation.sh"
32 ]
33 post_bump_hooks = ["scripts/slack_notification.sh"]
34 """
35
36 PYPROJECT = f"""
37 {TOML_STR}
38
39 [tool.black]
40 line-length = 88
41 target-version = ['py36', 'py37', 'py38']
42 """
43
44
45 DICT_CONFIG = {
46 "commitizen": {
47 "name": "cz_jira",
48 "version": "1.0.0",
49 "version_files": ["commitizen/__version__.py", "pyproject.toml"],
50 "style": [["pointer", "reverse"], ["question", "underline"]],
51 "pre_bump_hooks": ["scripts/generate_documentation.sh"],
52 "post_bump_hooks": ["scripts/slack_notification.sh"],
53 }
54 }
55
56 JSON_STR = r"""
57 {
58 "commitizen": {
59 "name": "cz_jira",
60 "version": "1.0.0",
61 "version_files": [
62 "commitizen/__version__.py",
63 "pyproject.toml"
64 ]
65 }
66 }
67 """
68
69 YAML_STR = """
70 commitizen:
71 name: cz_jira
72 version: 1.0.0
73 version_files:
74 - commitizen/__version__.py
75 - pyproject.toml
76 """
77
78 _settings: dict[str, Any] = {
79 "name": "cz_jira",
80 "version": "1.0.0",
81 "version_provider": "commitizen",
82 "version_scheme": None,
83 "tag_format": "$version",
84 "legacy_tag_formats": [],
85 "ignored_tag_formats": [],
86 "bump_message": None,
87 "retry_after_failure": False,
88 "allow_abort": False,
89 "allowed_prefixes": [
90 "Merge",
91 "Revert",
92 "Pull request",
93 "fixup!",
94 "squash!",
95 "amend!",
96 ],
97 "version_files": ["commitizen/__version__.py", "pyproject.toml"],
98 "style": [["pointer", "reverse"], ["question", "underline"]],
99 "changelog_file": "CHANGELOG.md",
100 "changelog_format": None,
101 "changelog_incremental": False,
102 "changelog_start_rev": None,
103 "changelog_merge_prerelease": False,
104 "update_changelog_on_bump": False,
105 "use_shortcuts": False,
106 "major_version_zero": False,
107 "pre_bump_hooks": ["scripts/generate_documentation.sh"],
108 "post_bump_hooks": ["scripts/slack_notification.sh"],
109 "prerelease_offset": 0,
110 "encoding": "utf-8",
111 "always_signoff": False,
112 "template": None,
113 "extras": {},
114 "breaking_change_exclamation_in_title": False,
115 "message_length_limit": 0,
116 "body_length_limit": 0,
117 }
118
119 _new_settings: dict[str, Any] = {
120 "name": "cz_jira",
121 "version": "2.0.0",
122 "version_provider": "commitizen",
123 "version_scheme": None,
124 "tag_format": "$version",
125 "legacy_tag_formats": [],
126 "ignored_tag_formats": [],
127 "bump_message": None,
128 "retry_after_failure": False,
129 "allow_abort": False,
130 "allowed_prefixes": [
131 "Merge",
132 "Revert",
133 "Pull request",
134 "fixup!",
135 "squash!",
136 "amend!",
137 ],
138 "version_files": ["commitizen/__version__.py", "pyproject.toml"],
139 "style": [["pointer", "reverse"], ["question", "underline"]],
140 "changelog_file": "CHANGELOG.md",
141 "changelog_format": None,
142 "changelog_incremental": False,
143 "changelog_start_rev": None,
144 "changelog_merge_prerelease": False,
145 "update_changelog_on_bump": False,
146 "use_shortcuts": False,
147 "major_version_zero": False,
148 "pre_bump_hooks": ["scripts/generate_documentation.sh"],
149 "post_bump_hooks": ["scripts/slack_notification.sh"],
150 "prerelease_offset": 0,
151 "encoding": "utf-8",
152 "always_signoff": False,
153 "template": None,
154 "extras": {},
155 "breaking_change_exclamation_in_title": False,
156 "message_length_limit": 0,
157 "body_length_limit": 0,
158 }
159
160
161 @pytest.fixture
162 def config_files_manager(request, tmp_path, monkeypatch):
163 monkeypatch.chdir(tmp_path)
164 filename = request.param
165 path = tmp_path / filename
166 path.parent.mkdir(parents=True, exist_ok=True)
167 with path.open("w", encoding="utf-8") as f:
168 if "toml" in filename:
169 f.write(PYPROJECT)
170 elif "json" in filename:
171 json.dump(DICT_CONFIG, f)
172 elif "yaml" in filename:
173 yaml.dump(DICT_CONFIG, f)
174 return
175
176
177 @pytest.mark.usefixtures("in_repo_root")
178 def test_find_git_project_root(tmp_path, monkeypatch):
179 assert git.find_git_project_root() == Path(os.getcwd())
180
181 monkeypatch.chdir(tmp_path)
182 assert git.find_git_project_root() is None
183
184
185 @pytest.mark.parametrize("config_files_manager", defaults.CONFIG_FILES, indirect=True)
186 def test_set_key(config_files_manager):
187 _conf = config.read_cfg()
188 _conf.set_key("version", "2.0.0")
189 cfg = config.read_cfg()
190 assert cfg.settings == _new_settings
191
192
193 class TestReadCfg:
194 @pytest.mark.parametrize(
195 "config_files_manager", defaults.CONFIG_FILES, indirect=True
196 )
197 def test_load_conf(self, config_files_manager):
198 cfg = config.read_cfg()
199 assert cfg.settings == _settings
200
201 def test_conf_returns_default_when_no_files(self, tmp_path, monkeypatch):
202 monkeypatch.chdir(tmp_path)
203 cfg = config.read_cfg()
204 assert cfg.settings == defaults.DEFAULT_SETTINGS
205
206 def test_load_empty_pyproject_toml_and_cz_toml_with_config(
207 self, tmp_path, monkeypatch
208 ):
209 monkeypatch.chdir(tmp_path)
210 (tmp_path / "pyproject.toml").write_text("")
211 (tmp_path / ".cz.toml").write_text(TOML_STR)
212
213 cfg = config.read_cfg()
214 assert cfg.settings == _settings
215
216 def test_load_pyproject_toml_from_config_argument(self, tmp_path, monkeypatch):
217 monkeypatch.chdir(tmp_path)
218 _not_root_path = tmp_path / "not_in_root" / "pyproject.toml"
219 _not_root_path.parent.mkdir(parents=True, exist_ok=True)
220 _not_root_path.write_text(PYPROJECT)
221
222 cfg = config.read_cfg(_not_root_path)
223 assert cfg.settings == _settings
224
225 def test_load_cz_json_not_from_config_argument(self, tmp_path, monkeypatch):
226 monkeypatch.chdir(tmp_path)
227 _not_root_path = tmp_path / "not_in_root" / ".cz.json"
228 _not_root_path.parent.mkdir(parents=True, exist_ok=True)
229 _not_root_path.write_text(JSON_STR)
230
231 cfg = config.read_cfg(_not_root_path)
232 json_cfg_by_class = JsonConfig(data=JSON_STR, path=_not_root_path)
233 assert cfg.settings == json_cfg_by_class.settings
234
235 def test_load_cz_yaml_not_from_config_argument(self, tmp_path, monkeypatch):
236 monkeypatch.chdir(tmp_path)
237 _not_root_path = tmp_path / "not_in_root" / ".cz.yaml"
238 _not_root_path.parent.mkdir(parents=True, exist_ok=True)
239 _not_root_path.write_text(YAML_STR)
240
241 cfg = config.read_cfg(_not_root_path)
242 yaml_cfg_by_class = YAMLConfig(data=YAML_STR, path=_not_root_path)
243 assert cfg.settings == yaml_cfg_by_class._settings
244
245 def test_load_empty_pyproject_toml_from_config_argument(
246 self, tmp_path, monkeypatch
247 ):
248 monkeypatch.chdir(tmp_path)
249 _not_root_path = tmp_path / "not_in_root" / "pyproject.toml"
250 _not_root_path.parent.mkdir(parents=True, exist_ok=True)
251 _not_root_path.write_text("")
252
253 with pytest.raises(ConfigFileIsEmpty):
254 config.read_cfg(_not_root_path)
255
256 def test_load_empty_json_from_config_argument(self, tmpdir):
257 with tmpdir.as_cwd():
258 _not_root_path = tmpdir.mkdir("not_in_root").join(".cz.json")
259 _not_root_path.write("")
260
261 with pytest.raises(ConfigFileIsEmpty):
262 config.read_cfg(filepath="./not_in_root/.cz.json")
263
264 def test_load_empty_yaml_from_config_argument(self, tmpdir):
265 with tmpdir.as_cwd():
266 _not_root_path = tmpdir.mkdir("not_in_root").join(".cz.yaml")
267 _not_root_path.write("")
268
269 with pytest.raises(ConfigFileIsEmpty):
270 config.read_cfg(filepath="./not_in_root/.cz.yaml")
271
272
273 class TestWarnMultipleConfigFiles:
274 @pytest.mark.parametrize(
275 ("files", "expected_path"),
276 [
277 # Same directory, different file types
278 ([(".cz.toml", TOML_STR), (".cz.json", JSON_STR)], ".cz.toml"),
279 ([(".cz.json", JSON_STR), (".cz.yaml", YAML_STR)], ".cz.json"),
280 ([(".cz.toml", TOML_STR), (".cz.yaml", YAML_STR)], ".cz.toml"),
281 # With pyproject.toml
282 (
283 [("pyproject.toml", PYPROJECT), (".cz.json", JSON_STR)],
284 ".cz.json",
285 ),
286 (
287 [("pyproject.toml", PYPROJECT), (".cz.toml", TOML_STR)],
288 ".cz.toml",
289 ),
290 ],
291 )
292 def test_warn_multiple_config_files_same_dir(
293 self, tmp_path, monkeypatch, capsys, files, expected_path
294 ):
295 """Test warning when multiple config files exist in same directory."""
296 monkeypatch.chdir(tmp_path)
297 for filename, content in files:
298 (tmp_path / filename).write_text(content)
299
300 cfg = config.read_cfg()
301 captured = capsys.readouterr()
302
303 assert "Multiple config files detected" in captured.err
304 for filename, _ in files:
305 assert filename in captured.err
306 assert f"Using config file: '{expected_path}'" in captured.err
307
308 assert cfg.path == Path(expected_path)
309
310 @pytest.mark.parametrize(
311 ("config_file", "content"),
312 [
313 (".cz.json", JSON_STR),
314 (".cz.toml", TOML_STR),
315 (".cz.yaml", YAML_STR),
316 ("cz.toml", TOML_STR),
317 ("cz.json", JSON_STR),
318 ("cz.yaml", YAML_STR),
319 ],
320 )
321 def test_warn_same_filename_different_directories_with_git(
322 self, tmp_path, monkeypatch, capsys, config_file, content
323 ):
324 """Test warning when same config filename exists in the current directory and in the git root."""
325 monkeypatch.chdir(tmp_path)
326 cmd.run(["git", "init"])
327
328 # Create config in git root
329 (tmp_path / config_file).write_text(content)
330
331 # Create same filename in subdirectory
332 subdir = tmp_path / "subdir"
333 subdir.mkdir()
334 (subdir / config_file).write_text(content)
335
336 monkeypatch.chdir(subdir)
337 cfg = config.read_cfg()
338 captured = capsys.readouterr()
339
340 assert "Multiple config files detected" in captured.err
341 assert f"Using config file: '{config_file}'" in captured.err
342 assert cfg.path == Path(config_file)
343
344 def test_no_warn_with_explicit_config_path(self, tmp_path, monkeypatch, capsys):
345 """Test that no warning is issued when user explicitly specifies config."""
346 monkeypatch.chdir(tmp_path)
347 # Create multiple config files
348 (tmp_path / ".cz.toml").write_text(PYPROJECT)
349 (tmp_path / ".cz.json").write_text(JSON_STR)
350
351 # Read config with explicit path
352 cfg = config.read_cfg(Path(".cz.json"))
353
354 # No warning should be issued
355 captured = capsys.readouterr()
356 assert "Multiple config files detected" not in captured.err
357
358 # Verify the explicitly specified config is loaded (compare to expected JSON config)
359 json_cfg_expected = JsonConfig(data=JSON_STR, path=Path(".cz.json"))
360 assert cfg.settings == json_cfg_expected.settings
361
362 @pytest.mark.parametrize(
363 ("config_file", "content", "with_git"),
364 [
365 (file, content, with_git)
366 for file, content in [
367 (".cz.toml", TOML_STR),
368 (".cz.json", JSON_STR),
369 (".cz.yaml", YAML_STR),
370 ("pyproject.toml", PYPROJECT),
371 ("cz.toml", TOML_STR),
372 ("cz.json", JSON_STR),
373 ("cz.yaml", YAML_STR),
374 ]
375 for with_git in [True, False]
376 ],
377 )
378 def test_no_warn_with_single_config_file(
379 self, tmp_path, monkeypatch, capsys, config_file, content, with_git
380 ):
381 """Test that no warning is issued when user explicitly specifies config."""
382 monkeypatch.chdir(tmp_path)
383 if with_git:
384 cmd.run(["git", "init"])
385
386 (tmp_path / config_file).write_text(content)
387
388 cfg = config.read_cfg()
389 captured = capsys.readouterr()
390
391 # No warning should be issued
392 assert "Multiple config files detected" not in captured.err
393 assert cfg.path == Path(config_file)
394
395 def test_no_warn_with_no_commitizen_section_in_pyproject_toml_and_cz_toml(
396 self, tmp_path, monkeypatch, capsys
397 ):
398 monkeypatch.chdir(tmp_path)
399 (tmp_path / "pyproject.toml").write_text("[tool.foo]\nbar = 'baz'")
400 (tmp_path / ".cz.toml").write_text(TOML_STR)
401
402 cfg = config.read_cfg()
403 captured = capsys.readouterr()
404 assert "Multiple config files detected" not in captured.err
405 assert cfg.path == Path(".cz.toml")
406
407
408 @pytest.mark.parametrize(
409 "config_file",
410 [
411 ".cz.toml",
412 "cz.toml",
413 "pyproject.toml",
414 ],
415 )
416 class TestTomlConfig:
417 def test_init_empty_config_content(self, tmp_path, config_file):
418 path = tmp_path / "commitizen" / config_file
419 path.parent.mkdir(parents=True, exist_ok=True)
420 toml_config = TomlConfig(data="", path=path)
421 toml_config.init_empty_config_content()
422
423 assert path.read_text(encoding="utf-8") == "[tool.commitizen]\n"
424
425 def test_init_empty_config_content_with_existing_content(
426 self, tmp_path, config_file
427 ):
428 existing_content = "[tool.black]\nline-length = 88\n"
429
430 path = tmp_path / "commitizen" / config_file
431 path.parent.mkdir(parents=True, exist_ok=True)
432 path.write_text(existing_content)
433 toml_config = TomlConfig(data="", path=path)
434 toml_config.init_empty_config_content()
435
436 assert (
437 path.read_text(encoding="utf-8")
438 == existing_content + "\n[tool.commitizen]\n"
439 )
440
441 def test_init_with_invalid_config_content(self, tmp_path, config_file):
442 existing_content = "invalid toml content"
443 path = tmp_path / "commitizen" / config_file
444 path.parent.mkdir(parents=True, exist_ok=True)
445
446 with pytest.raises(InvalidConfigurationError, match=re.escape(config_file)):
447 TomlConfig(data=existing_content, path=path)
448
449
450 @pytest.mark.parametrize(
451 "config_file",
452 [
453 ".cz.json",
454 "cz.json",
455 ],
456 )
457 class TestJsonConfig:
458 def test_init_empty_config_content(self, tmp_path, config_file):
459 path = tmp_path / "commitizen" / config_file
460 path.parent.mkdir(parents=True, exist_ok=True)
461 json_config = JsonConfig(data="{}", path=path)
462 json_config.init_empty_config_content()
463
464 with path.open(encoding="utf-8") as json_file:
465 assert json.load(json_file) == {"commitizen": {}}
466
467 def test_init_with_invalid_config_content(self, tmp_path, config_file):
468 existing_content = "invalid json content"
469 path = tmp_path / "commitizen" / config_file
470 path.parent.mkdir(parents=True, exist_ok=True)
471
472 with pytest.raises(InvalidConfigurationError, match=re.escape(config_file)):
473 JsonConfig(data=existing_content, path=path)
474
475
476 @pytest.mark.parametrize(
477 "config_file",
478 [
479 ".cz.yaml",
480 "cz.yaml",
481 ],
482 )
483 class TestYamlConfig:
484 def test_init_empty_config_content(self, tmp_path, config_file):
485 path = tmp_path / "commitizen" / config_file
486 path.parent.mkdir(parents=True, exist_ok=True)
487 yaml_config = YAMLConfig(data="{}", path=path)
488 yaml_config.init_empty_config_content()
489
490 with path.open() as yaml_file:
491 assert yaml.safe_load(yaml_file) == {"commitizen": {}}
492
493 def test_init_with_invalid_content(self, tmp_path, config_file):
494 existing_content = "invalid: .cz.yaml: content: maybe?"
495 path = tmp_path / "commitizen" / config_file
496 path.parent.mkdir(parents=True, exist_ok=True)
497
498 with pytest.raises(InvalidConfigurationError, match=re.escape(config_file)):
499 YAMLConfig(data=existing_content, path=path)