Debian Codegraph @

tests/conftest.py

raw
1 from __future__ import annotations
2
3 import os
4 import re
5 import subprocess
6 import sys
7 import tempfile
8 from pathlib import Path
9 from typing import TYPE_CHECKING, cast
10
11 import pytest
12
13 from commitizen import cmd, defaults
14 from commitizen.changelog_formats import (
15 ChangelogFormat,
16 get_changelog_format,
17 )
18 from commitizen.config import BaseConfig
19 from commitizen.cz import registry
20 from commitizen.cz.base import BaseCommitizen
21
22 if TYPE_CHECKING:
23 from collections.abc import Iterator, Mapping
24
25 from pytest_mock import MockerFixture
26
27 from commitizen.question import CzQuestion
28 from tests.utils import UtilFixture
29
30
31 SIGNER = "GitHub Action"
32 SIGNER_MAIL = "[email protected]"
33 PYTHON_VERSION = f"{sys.version_info.major}.{sys.version_info.minor}"
34
35 pytest_plugins = [
36 "tests.utils",
37 ]
38
39
40 @pytest.fixture
41 def repo_root() -> Path:
42 return Path(__file__).parent.parent
43
44
45 @pytest.fixture
46 def in_repo_root(repo_root: Path) -> Iterator[Path]:
47 cwd = os.getcwd()
48 os.chdir(repo_root)
49 yield repo_root
50 os.chdir(cwd)
51
52
53 @pytest.fixture
54 def data_dir(repo_root: Path) -> Path:
55 return repo_root / "tests" / "data"
56
57
58 @pytest.fixture(scope="session")
59 def set_default_gitconfig() -> dict[str, str]:
60 return {
61 "user.name": "SIGNER",
62 "user.email": SIGNER_MAIL,
63 "safe.directory": "*",
64 "init.defaultBranch": "master",
65 }
66
67
68 @pytest.fixture
69 def chdir(tmp_path: Path) -> Iterator[Path]:
70 cwd = os.getcwd()
71 os.chdir(tmp_path)
72 yield tmp_path
73 os.chdir(cwd)
74
75
76 @pytest.fixture
77 def tmp_git_project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
78 monkeypatch.chdir(tmp_path)
79 cmd.run(["git", "init"])
80
81 return tmp_path
82
83
84 @pytest.fixture
85 def tmp_commitizen_project(tmp_git_project: Path):
86 (tmp_git_project / "pyproject.toml").write_text(
87 '[tool.commitizen]\nversion="0.1.0"\n'
88 )
89
90 return tmp_git_project
91
92
93 @pytest.fixture
94 def pyproject(tmp_commitizen_project: Path) -> Path:
95 return tmp_commitizen_project / "pyproject.toml"
96
97
98 @pytest.fixture
99 def tmp_commitizen_project_initial(
100 tmp_git_project: Path, util: UtilFixture, monkeypatch: pytest.MonkeyPatch
101 ):
102 def _initial(
103 config_extra: str | None = None,
104 version="0.1.0",
105 initial_commit="feat: new user interface",
106 ):
107 monkeypatch.chdir(tmp_git_project)
108 tmp_commitizen_cfg_file = tmp_git_project / "pyproject.toml"
109 tmp_commitizen_cfg_file.write_text(f'[tool.commitizen]\nversion="{version}"\n')
110 tmp_version_file = tmp_git_project / "__version__.py"
111 tmp_version_file.write_text(version)
112 tmp_version_file_string = str(tmp_version_file).replace("\\", "/")
113 with tmp_commitizen_cfg_file.open("a", encoding="utf-8") as f:
114 f.write(f'\nversion_files = ["{tmp_version_file_string}"]\n')
115 if config_extra:
116 with tmp_commitizen_cfg_file.open("a", encoding="utf-8") as f:
117 f.write(config_extra)
118 util.create_file_and_commit(initial_commit)
119
120 return tmp_git_project
121
122 return _initial
123
124
125 def _get_gpg_keyid(signer_mail):
126 _new_key = cmd.run(["gpg", "--list-secret-keys", signer_mail])
127 _m = re.search(
128 r"[a-zA-Z0-9 \[\]-_]*\n[ ]*([0-9A-Za-z]*)\n[\na-zA-Z0-9 \[\]-_<>@]*",
129 _new_key.out,
130 )
131 return _m.group(1) if _m else None
132
133
134 @pytest.fixture
135 def tmp_commitizen_project_with_gpg(tmp_commitizen_project):
136 # create a temporary GPGHOME to store a temporary keyring.
137 # Home path must be less than 104 characters
138 gpg_home = tempfile.TemporaryDirectory(suffix="_cz")
139 old_gnupghome = os.environ.get("GNUPGHOME")
140 if os.name != "nt":
141 os.environ["GNUPGHOME"] = gpg_home.name # tempdir = temp keyring
142
143 try:
144 # create a key (a keyring will be generated within GPUPGHOME)
145 subprocess.run(
146 [
147 "gpg",
148 "--batch",
149 "--yes",
150 "--debug-quick-random",
151 "--passphrase",
152 "",
153 "--quick-gen-key",
154 f"{SIGNER} {SIGNER_MAIL}",
155 ],
156 check=True,
157 )
158 key_id = _get_gpg_keyid(SIGNER_MAIL)
159 assert key_id
160
161 # configure git to use gpg signing
162 cmd.run(["git", "config", "commit.gpgsign", "true"])
163 cmd.run(["git", "config", "user.signingkey", key_id])
164
165 yield tmp_commitizen_project
166 finally:
167 if old_gnupghome is not None:
168 os.environ["GNUPGHOME"] = old_gnupghome
169 elif "GNUPGHOME" in os.environ and os.name != "nt":
170 os.environ.pop("GNUPGHOME")
171 gpg_home.cleanup()
172
173
174 @pytest.fixture
175 def config():
176 _config = BaseConfig()
177 _config.settings.update({"name": defaults.DEFAULT_SETTINGS["name"]})
178 return _config
179
180
181 class SemverCommitizen(BaseCommitizen):
182 """A minimal cz rules used to test changelog and bump.
183
184 Samples:
185 ```
186 minor(users): add email to user
187 major: removed user profile
188 patch(deps): updated dependency for security
189 ```
190 """
191
192 bump_pattern = r"^(patch|minor|major)"
193 bump_map = {
194 "major": "MAJOR",
195 "minor": "MINOR",
196 "patch": "PATCH",
197 }
198 bump_map_major_version_zero = {
199 "major": "MINOR",
200 "minor": "MINOR",
201 "patch": "PATCH",
202 }
203 changelog_pattern = r"^(patch|minor|major)"
204 commit_parser = r"^(?P<change_type>patch|minor|major)(?:\((?P<scope>[^()\r\n]*)\)|\()?:?\s(?P<message>.+)"
205 change_type_map = {
206 "major": "Breaking Changes",
207 "minor": "Features",
208 "patch": "Bugs",
209 }
210
211 def questions(self) -> list[CzQuestion]:
212 return [
213 {
214 "type": "list",
215 "name": "prefix",
216 "message": "Select the type of change you are committing",
217 "choices": [
218 {
219 "value": "patch",
220 "name": "patch: a bug fix",
221 "key": "p",
222 },
223 {
224 "value": "minor",
225 "name": "minor: a new feature, non-breaking",
226 "key": "m",
227 },
228 {
229 "value": "major",
230 "name": "major: a breaking change",
231 "key": "b",
232 },
233 ],
234 },
235 {
236 "type": "input",
237 "name": "subject",
238 "message": (
239 "Write a short and imperative summary of the code changes: (lower case and no period)\n"
240 ),
241 },
242 ]
243
244 def message(self, answers: Mapping) -> str:
245 prefix = answers["prefix"]
246 subject = answers.get("subject", "default message").trim()
247 return f"{prefix}: {subject}"
248
249 def example(self) -> str:
250 return ""
251
252 def schema(self) -> str:
253 return ""
254
255 def schema_pattern(self) -> str:
256 return ""
257
258 def info(self) -> str:
259 return ""
260
261
262 @pytest.fixture
263 def use_cz_semver(mocker):
264 new_cz = {**registry, "cz_semver": SemverCommitizen}
265 mocker.patch.dict("commitizen.cz.registry", new_cz)
266
267
268 class MockPlugin(BaseCommitizen):
269 def questions(self) -> list[CzQuestion]:
270 return []
271
272 def message(self, answers: Mapping) -> str:
273 return ""
274
275 def example(self) -> str:
276 return ""
277
278 def schema(self) -> str:
279 return ""
280
281 def schema_pattern(self) -> str:
282 return ""
283
284 def info(self) -> str:
285 return ""
286
287
288 @pytest.fixture
289 def mock_plugin(mocker: MockerFixture, config: BaseConfig) -> BaseCommitizen:
290 mock = MockPlugin(config)
291 mocker.patch("commitizen.factory.committer_factory", return_value=mock)
292 return mock
293
294
295 SUPPORTED_FORMATS = ("markdown", "textile", "asciidoc", "restructuredtext")
296
297
298 @pytest.fixture(params=SUPPORTED_FORMATS)
299 def changelog_format(
300 config: BaseConfig, request: pytest.FixtureRequest
301 ) -> ChangelogFormat:
302 """For tests relying on formats specifics"""
303 format: str = request.param
304 config.settings["changelog_format"] = format
305 if "tmp_commitizen_project" in request.fixturenames:
306 tmp_commitizen_project = request.getfixturevalue("tmp_commitizen_project")
307 pyproject = tmp_commitizen_project / "pyproject.toml"
308 with pyproject.open("a", encoding="utf-8") as f:
309 f.write(f'\nchangelog_format = "{format}"\n')
310 return get_changelog_format(config)
311
312
313 @pytest.fixture
314 def any_changelog_format(config: BaseConfig) -> ChangelogFormat:
315 """For test not relying on formats specifics, use the default"""
316 config.settings["changelog_format"] = defaults.CHANGELOG_FORMAT
317 return get_changelog_format(config)
318
319
320 @pytest.fixture(params=[pytest.param(PYTHON_VERSION, id=f"py_{PYTHON_VERSION}")])
321 def python_version(request: pytest.FixtureRequest) -> str:
322 """The current python version in '{major}.{minor}' format"""
323 return cast("str", request.param)
324
325
326 @pytest.fixture
327 def consistent_terminal_output(monkeypatch: pytest.MonkeyPatch):
328 """Force consistent terminal output."""
329 monkeypatch.setenv("COLUMNS", "80")
330 monkeypatch.setenv("TERM", "dumb")
331 monkeypatch.setenv("LC_ALL", "C")
332 monkeypatch.setenv("LANG", "C")
333 monkeypatch.setenv("NO_COLOR", "1")
334 monkeypatch.setenv("PAGER", "cat")