Debian Codegraph @

tests/unit/post_install/test_log_vc_info.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 import json
18 import logging
19 from pathlib import Path
20 import pytest
21 from pytest import MonkeyPatch, TempPathFactory
22 from secrets import token_hex
23 import shutil
24 import subprocess
25 from typing import Any, Callable, Tuple
26 from unittest.mock import Mock
27
28 from cylc.flow.install_plugins.log_vc_info import (
29 INFO_FILENAME,
30 VCSNotInstalledError,
31 _get_git_commit,
32 _run_cmd,
33 get_status,
34 get_vc_info,
35 main,
36 write_diff,
37 )
38 from cylc.flow.workflow_files import WorkflowFiles
39
40 Fixture = Any
41
42
43 BASIC_FLOW_1 = """
44 [scheduling]
45 [[graph]]
46 R1 = foo
47 """
48
49 BASIC_FLOW_2 = """
50 [scheduling]
51 [[graph]]
52 R1 = bar
53 """
54
55
56 require_git = pytest.mark.skipif(
57 shutil.which('git') is None,
58 reason="git is not installed"
59 )
60
61 require_svn = pytest.mark.skipif(
62 shutil.which('svn') is None,
63 reason="svn is not installed"
64 )
65
66
67 @pytest.fixture(scope='module')
68 def git_source_repo(tmp_path_factory: TempPathFactory) -> Tuple[str, str]:
69 """Init a git repo for a workflow source dir.
70
71 The repo has uncommitted changes. This dir is reused
72 by all tests requesting it in this module.
73
74 Returns (source_dir_path, commit_hash)
75 """
76 source_dir: Path = tmp_path_factory.getbasetemp() / 'git_repo'
77 source_dir.mkdir()
78 subprocess.run(['git', 'init'], cwd=source_dir, check=True)
79 flow_file = source_dir / 'flow.cylc'
80 flow_file.write_text(BASIC_FLOW_1)
81 subprocess.run(['git', 'add', '-A'], cwd=source_dir, check=True)
82 subprocess.run(
83 ['git', 'commit', '-am', '"Initial commit"'],
84 cwd=source_dir, check=True, capture_output=True)
85 # Overwrite file to introduce uncommitted changes:
86 flow_file.write_text(BASIC_FLOW_2)
87 # Also add new file:
88 (source_dir / 'gandalf.md').touch()
89 commit_sha = subprocess.run(
90 ['git', 'rev-parse', 'HEAD'],
91 cwd=source_dir, check=True, capture_output=True, text=True
92 ).stdout.splitlines()[0]
93 return (str(source_dir), commit_sha)
94
95
96 @pytest.fixture(scope='module')
97 def svn_source_repo(tmp_path_factory: TempPathFactory) -> Tuple[str, str, str]:
98 """Init an svn repo & working copy for a workflow source dir.
99
100 The working copy has a flow.cylc file with uncommitted changes. This dir
101 is reused by all tests requesting it in this module.
102
103 Returns (source_dir_path, repository_UUID, repository_path)
104 """
105 tmp_path: Path = tmp_path_factory.getbasetemp()
106 repo = tmp_path.joinpath('svn_repo')
107 subprocess.run(
108 ['svnadmin', 'create', 'svn_repo'], cwd=tmp_path, check=True)
109 uuid = subprocess.run(
110 ['svnlook', 'uuid', repo],
111 check=True, capture_output=True, text=True
112 ).stdout.splitlines()[0]
113 project_dir = tmp_path.joinpath('project')
114 project_dir.mkdir()
115 project_dir.joinpath('flow.cylc').write_text(BASIC_FLOW_1)
116 subprocess.run(
117 ['svn', 'import', project_dir, f'file://{repo}/project/trunk',
118 '-m', '"Initial import"'], check=True)
119 source_dir = tmp_path.joinpath('svn_working_copy')
120 subprocess.run(
121 ['svn', 'checkout', f'file://{repo}/project/trunk', source_dir],
122 check=True)
123
124 flow_file = source_dir.joinpath('flow.cylc')
125 # Overwrite file to introduce uncommitted changes:
126 flow_file.write_text(BASIC_FLOW_2)
127
128 return (str(source_dir), uuid, str(repo))
129
130
131 @require_git
132 def test_get_git_commit(git_source_repo: Tuple[str, str]):
133 """Test get_git_commit()"""
134 source_dir, commit_sha = git_source_repo
135 assert _get_git_commit(source_dir) == commit_sha
136
137
138 @require_git
139 def test_get_status_git(git_source_repo: Tuple[str, str]):
140 """Test get_status() for a git repo"""
141 source_dir, commit_sha = git_source_repo
142 assert get_status('git', source_dir) == [
143 " M flow.cylc",
144 "?? gandalf.md"
145 ]
146
147
148 @require_git
149 def test_get_vc_info_git(git_source_repo: Tuple[str, str]):
150 """Test get_vc_info() for a git repo"""
151 source_dir, commit_sha = git_source_repo
152 vc_info = get_vc_info(source_dir)
153 assert vc_info is not None
154 expected = [
155 ('version control system', "git"),
156 ('repository version', f"{commit_sha[:7]}-dirty"),
157 ('commit', commit_sha),
158 ('working copy root path', source_dir),
159 ('status', [
160 " M flow.cylc",
161 "?? gandalf.md"
162 ])
163 ]
164 assert list(vc_info.items()) == expected
165
166
167 @require_git
168 def test_write_diff_git(git_source_repo: Tuple[str, str], tmp_path: Path):
169 """Test write_diff() for a git repo"""
170 source_dir, _ = git_source_repo
171 run_dir = tmp_path / 'run_dir'
172 (run_dir / WorkflowFiles.LogDir.DIRNAME).mkdir(parents=True)
173 diff_file = write_diff('git', source_dir, run_dir)
174 diff_lines = diff_file.read_text().splitlines()
175 assert diff_lines[0].startswith("# Auto-generated diff")
176 for line in ("diff --git a/flow.cylc b/flow.cylc",
177 "- R1 = foo",
178 "+ R1 = bar"):
179 assert line in diff_lines
180
181
182 @require_git
183 def test_main_git(git_source_repo: Tuple[str, str], tmp_run_dir: Callable):
184 """Test the written JSON info file."""
185 source_dir, _ = git_source_repo
186 run_dir: Path = tmp_run_dir('frodo')
187 main(source_dir, None, run_dir)
188 with open(
189 run_dir
190 / WorkflowFiles.LogDir.DIRNAME
191 / WorkflowFiles.LogDir.VERSION
192 / INFO_FILENAME, 'r'
193 ) as f:
194 loaded = json.loads(f.read())
195 assert isinstance(loaded, dict)
196 assert loaded['version control system'] == 'git'
197 assert isinstance(loaded['status'], list)
198 assert len(loaded['status']) == 2
199
200
201 @require_svn
202 def test_get_vc_info_svn(svn_source_repo: Tuple[str, str, str]):
203 """Test get_vc_info() for an svn working copy"""
204 source_dir, uuid, repo_path = svn_source_repo
205 vc_info = get_vc_info(source_dir)
206 assert vc_info is not None
207 expected = [
208 ('version control system', "svn"),
209 ('working copy root path', str(source_dir)),
210 ('url', f"file://{repo_path}/project/trunk"),
211 ('repository uuid', uuid),
212 ('revision', "1"),
213 ('status', ["M flow.cylc"])
214 ]
215 assert list(vc_info.items()) == expected
216
217
218 @require_svn
219 def test_write_diff_svn(svn_source_repo: Tuple[str, str, str], tmp_path: Path):
220 """Test write_diff() for an svn working copy"""
221 source_dir, _, _ = svn_source_repo
222 run_dir = tmp_path / 'run_dir'
223 (run_dir / WorkflowFiles.LogDir.DIRNAME).mkdir(parents=True)
224 diff_file = write_diff('svn', source_dir, run_dir)
225 diff_lines = diff_file.read_text().splitlines()
226 assert diff_lines[0].startswith("# Auto-generated diff")
227 for line in (f"--- {source_dir}/flow.cylc (revision 1)",
228 f"+++ {source_dir}/flow.cylc (working copy)",
229 "- R1 = foo",
230 "+ R1 = bar"):
231 assert line in diff_lines
232
233
234 def test_not_repo(tmp_path: Path, monkeypatch: MonkeyPatch):
235 """Test get_vc_info() and main() for a dir that is not a supported repo"""
236 source_dir = Path(tmp_path, 'git_repo')
237 source_dir.mkdir()
238 flow_file = source_dir.joinpath('flow.cylc')
239 flow_file.write_text(BASIC_FLOW_1)
240 mock_write_vc_info = Mock()
241 monkeypatch.setattr('cylc.flow.install_plugins.log_vc_info.write_vc_info',
242 mock_write_vc_info)
243 mock_write_diff = Mock()
244 monkeypatch.setattr('cylc.flow.install_plugins.log_vc_info.write_diff',
245 mock_write_diff)
246
247 assert get_vc_info(source_dir) is None
248 assert main(source_dir, None, None) is False # type: ignore
249 assert mock_write_vc_info.called is False
250 assert mock_write_diff.called is False
251
252
253 @require_git
254 def test_no_base_commit_git(tmp_path: Path):
255 """Test get_vc_info() and write_diff() for a recently init'd git source dir
256 that does not have a base commit yet."""
257 source_dir = Path(tmp_path, 'new_git_repo')
258 source_dir.mkdir()
259 subprocess.run(['git', 'init'], cwd=source_dir, check=True)
260 flow_file = source_dir.joinpath('flow.cylc')
261 flow_file.write_text(BASIC_FLOW_1)
262 run_dir = tmp_path / 'run_dir'
263 (run_dir / WorkflowFiles.LogDir.DIRNAME).mkdir(parents=True)
264
265 vc_info = get_vc_info(source_dir)
266 assert vc_info is not None
267 assert list(vc_info.items()) == [
268 ('version control system', "git"),
269 ('working copy root path', str(source_dir)),
270 ('status', ["?? flow.cylc"])
271 ]
272
273 # Diff file expected to be empty (only containing comment lines),
274 # but should work without raising
275 diff_file = write_diff('git', source_dir, run_dir)
276 for line in diff_file.read_text().splitlines():
277 assert line.startswith('#')
278
279
280 @require_svn
281 def test_untracked_svn_subdir(
282 svn_source_repo: Tuple[str, str, str], log_filter
283 ):
284 repo_dir, *_ = svn_source_repo
285 source_dir = Path(repo_dir, 'jar_jar_binks')
286 source_dir.mkdir()
287 assert get_vc_info(source_dir) is None
288 assert log_filter(logging.WARNING, contains="$ svn info")
289
290
291 def test_not_installed(
292 tmp_path,
293 monkeypatch: pytest.MonkeyPatch,
294 caplog: pytest.LogCaptureFixture,
295 log_filter,
296 ):
297 """Test what happens if version control software is not installed."""
298 fake_vcs = token_hex(8)
299 with pytest.raises(VCSNotInstalledError):
300 _run_cmd(fake_vcs, [], cwd=tmp_path)
301
302 monkeypatch.setattr(
303 'cylc.flow.install_plugins.log_vc_info.INFO_COMMANDS',
304 {fake_vcs: []}
305 )
306 caplog.set_level(logging.DEBUG)
307 assert get_vc_info(tmp_path) is None
308 assert log_filter(
309 logging.DEBUG,
310 contains=f"{fake_vcs} does not appear to be installed",
311 )