Debian Codegraph @

tests/unit/test_workflow_files.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 logging
18 from pathlib import Path
19 from typing import (
20 Any,
21 Callable,
22 Dict,
23 Optional,
24 Type,
25 Union,
26 )
27
28 import pytest
29
30 from cylc.flow import workflow_files
31 from cylc.flow.exceptions import (
32 InputError,
33 WorkflowFilesError,
34 )
35 from cylc.flow.workflow_files import (
36 WorkflowFiles,
37 abort_if_flow_file_in_path,
38 check_flow_file,
39 check_reserved_dir_names,
40 detect_both_flow_and_suite,
41 get_symlink_dirs,
42 infer_latest_run,
43 is_forbidden,
44 is_installed,
45 validate_workflow_name,
46 )
47
48 from .filetree import (
49 FILETREE_1,
50 FILETREE_2,
51 FILETREE_3,
52 FILETREE_4,
53 create_filetree,
54 )
55
56 NonCallableFixture = Any
57
58
59 @pytest.mark.parametrize(
60 'path, expected',
61 [('a/b/c', '/mock_cylc_dir/a/b/c'),
62 ('/a/b/c', '/a/b/c')]
63 )
64 def test_get_cylc_run_abs_path(
65 path: str, expected: str,
66 monkeypatch: pytest.MonkeyPatch
67 ) -> None:
68 monkeypatch.setattr('cylc.flow.pathutil._CYLC_RUN_DIR', '/mock_cylc_dir')
69 assert workflow_files.get_cylc_run_abs_path(path) == expected
70
71
72 @pytest.mark.parametrize('is_abs_path', [False, True])
73 def test_is_valid_run_dir(is_abs_path: bool, tmp_run_dir: Callable):
74 """Test that a directory is correctly identified as a valid run dir when
75 it contains a service dir.
76 """
77 cylc_run_dir: Path = tmp_run_dir()
78 prefix = str(cylc_run_dir) if is_abs_path else ''
79 # What if no dir there?
80 assert workflow_files.is_valid_run_dir(
81 Path(prefix, 'nothing/here')) is False
82 # What if only flow.cylc exists but no service dir?
83 # (Non-run dirs can still contain flow.cylc)
84 run_dir = cylc_run_dir.joinpath('foo/bar')
85 run_dir.mkdir(parents=True)
86 flow_file = run_dir.joinpath(WorkflowFiles.FLOW_FILE)
87 flow_file.touch()
88 assert workflow_files.is_valid_run_dir(Path(prefix, 'foo/bar')) is True
89 # What if service dir exists?
90 flow_file.unlink()
91 run_dir.joinpath(WorkflowFiles.Service.DIRNAME).mkdir()
92 assert workflow_files.is_valid_run_dir(Path(prefix, 'foo/bar')) is True
93
94
95 @pytest.mark.parametrize(
96 'id_, expected_err, expected_msg',
97 [('foo/bar/', None, None),
98 ('/foo/bar', WorkflowFilesError, "cannot be an absolute path"),
99 ('$HOME/alone', WorkflowFilesError, "invalid workflow name"),
100 ('./foo', WorkflowFilesError, "invalid workflow name"),
101 ('meow/..', WorkflowFilesError,
102 "cannot be a path that points to the cylc-run directory or above")]
103 )
104 def test_validate_workflow_name(id_, expected_err, expected_msg):
105 if expected_err:
106 with pytest.raises(expected_err) as exc:
107 validate_workflow_name(id_)
108 if expected_msg:
109 assert expected_msg in str(exc.value)
110 else:
111 validate_workflow_name(id_)
112
113
114 @pytest.mark.parametrize(
115 'name, err_expected',
116 [
117 # Basic ok:
118 ('foo/bar/baz', False),
119 # Reserved dir names:
120 ('foo/log/baz', True),
121 ('foo/runN/baz', True),
122 ('foo/run9000/baz', True),
123 ('work', True),
124 # If not exact match, but substring, that's fine:
125 ('foo/underrunN/baz', False),
126 ('foo/overrun2', False),
127 ('slog', False)
128 ]
129 )
130 def test_check_reserved_dir_names(name: str, err_expected: bool):
131 if err_expected:
132 with pytest.raises(WorkflowFilesError) as exc_inf:
133 check_reserved_dir_names(name)
134 assert "cannot contain a directory named" in str(exc_inf.value)
135 else:
136 check_reserved_dir_names(name)
137
138
139 def test_validate_workflow_name__reserved_name():
140 """Check that validate_workflow_name() doesn't check for reserved dir names
141 unless we tell it to with the arg."""
142 name = 'foo/runN'
143 validate_workflow_name(name)
144 with pytest.raises(WorkflowFilesError):
145 validate_workflow_name(name, check_reserved_names=True)
146
147
148 @pytest.mark.parametrize(
149 'path, implicit_runN, expected_reg',
150 [
151 ('{cylc_run}/numbered/workflow', True, 'numbered/workflow/run2'),
152 ('{cylc_run}/numbered/workflow', False, 'numbered/workflow'),
153 ('{cylc_run}/numbered/workflow/runN', True, 'numbered/workflow/run2'),
154 ('{cylc_run}/numbered/workflow/runN', False, 'numbered/workflow/run2'),
155 ('{cylc_run}/numbered/workflow/run1', True, 'numbered/workflow/run1'),
156 ('{cylc_run}/numbered/workflow/run1', False, 'numbered/workflow/run1'),
157 ('{cylc_run}/non_numbered/workflow', True, 'non_numbered/workflow'),
158 ('{cylc_run}/non_numbered/workflow', False, 'non_numbered/workflow'),
159 ]
160 )
161 def test_infer_latest_run(
162 path: str,
163 implicit_runN: bool,
164 expected_reg: str,
165 tmp_run_dir: Callable,
166 ) -> None:
167 """Test infer_latest_run().
168
169 Params:
170 path: Input arg.
171 implicit_runN: Input arg.
172 expected_reg: The id_ part of the expected returned tuple.
173 """
174 # Setup
175 cylc_run_dir: Path = tmp_run_dir()
176
177 run_dir = cylc_run_dir / 'numbered' / 'workflow'
178 run_dir.mkdir(parents=True)
179 (run_dir / 'run1').mkdir()
180 (run_dir / 'run2').mkdir()
181 (run_dir / 'runN').symlink_to('run2')
182
183 run_dir = cylc_run_dir / 'non_numbered' / 'workflow' / 'named_run'
184 run_dir.mkdir(parents=True)
185
186 path: Path = Path(path.format(cylc_run=cylc_run_dir))
187 expected = (cylc_run_dir / expected_reg, expected_reg)
188
189 # Test
190 assert infer_latest_run(path, implicit_runN) == expected
191 # Check implicit_runN=True is the default:
192 if implicit_runN:
193 assert infer_latest_run(path) == expected
194
195
196 @pytest.mark.parametrize('warn_arg', [True, False])
197 def test_infer_latest_run_warns_for_runN(
198 warn_arg: bool,
199 log_filter: Callable,
200 tmp_run_dir: Callable,
201 monkeypatch: pytest.MonkeyPatch
202 ):
203 """Tests warning is produced to discourage use of /runN in workflow_id"""
204 (tmp_run_dir() / 'run1').mkdir()
205 runN_path = tmp_run_dir() / 'runN'
206 runN_path.symlink_to('run1')
207 monkeypatch.setattr('cylc.flow.LOG.level', logging.INFO)
208 infer_latest_run(runN_path, warn_runN=warn_arg)
209 filtered_log = log_filter(
210 logging.WARNING, contains="You do not need to include"
211 )
212 assert filtered_log if warn_arg else not filtered_log
213
214
215 @pytest.mark.parametrize(
216 ('reason', 'error_type'),
217 [
218 ('not dir', WorkflowFilesError),
219 ('not symlink', WorkflowFilesError),
220 ('broken symlink', WorkflowFilesError),
221 ('invalid target', WorkflowFilesError),
222 ('not exist', InputError)
223 ]
224 )
225 def test_infer_latest_run__bad(
226 reason: str,
227 error_type: Type[Exception],
228 tmp_run_dir: Callable,
229 ) -> None:
230 # -- Setup --
231 cylc_run_dir: Path = tmp_run_dir()
232 run_dir = cylc_run_dir / 'sulu'
233 run_dir.mkdir()
234 runN_path = run_dir / 'runN'
235 err_msg = f"{runN_path} symlink not valid"
236 if reason == 'not dir':
237 (run_dir / 'run1').touch()
238 runN_path.symlink_to('run1')
239 elif reason == 'not symlink':
240 runN_path.mkdir()
241 elif reason == 'broken symlink':
242 runN_path.symlink_to('run1')
243 elif reason == 'invalid target': # noqa: SIM106
244 (run_dir / 'palpatine').mkdir()
245 runN_path.symlink_to('palpatine')
246 err_msg = (
247 f"{runN_path} symlink target not valid: palpatine"
248 )
249 elif reason == 'not exist':
250 run_dir = run_dir / 'not-exist'
251 err_msg = (
252 f"Workflow ID not found: sulu/not-exist\n"
253 f"(Directory not found: {run_dir})"
254 )
255 else:
256 raise ValueError(reason)
257 # -- Test --
258 with pytest.raises(error_type) as excinfo:
259 infer_latest_run(run_dir)
260 assert str(excinfo.value) == err_msg
261
262
263 @pytest.mark.parametrize(
264 'filetree, expected',
265 [
266 pytest.param(
267 FILETREE_1,
268 {'log': 'sym/cylc-run/foo/bar/log'},
269 id="filetree1"
270 ),
271 pytest.param(
272 FILETREE_2,
273 {
274 'share/cycle': 'sym-cycle/cylc-run/foo/bar/share/cycle',
275 'share': 'sym-share/cylc-run/foo/bar/share',
276 '': 'sym-run/cylc-run/foo/bar/'
277 },
278 id="filetree2"
279 ),
280 pytest.param(
281 FILETREE_3,
282 {
283 'share/cycle': 'sym-cycle/cylc-run/foo/bar/share/cycle',
284 '': 'sym-run/cylc-run/foo/bar/'
285 },
286 id="filetree3"
287 ),
288 pytest.param(
289 FILETREE_4,
290 {'share/cycle': 'sym-cycle/cylc-run/foo/bar/share/cycle'},
291 id="filetree4"
292 ),
293 ]
294 )
295 def test_get_symlink_dirs(
296 filetree: Dict[str, Any],
297 expected: Dict[str, Union[Path, str]],
298 tmp_run_dir: Callable, tmp_path: Path
299 ):
300 """Test get_symlink_dirs().
301
302 Params:
303 filetree: The directory structure to test against.
304 expected: The expected return dictionary, except with the values being
305 relative to tmp_path instead of absolute paths.
306 """
307 # Setup
308 cylc_run_dir = tmp_run_dir()
309 create_filetree(filetree, tmp_path, tmp_path)
310 id_ = 'foo/bar'
311 for k, v in expected.items():
312 expected[k] = Path(tmp_path / v)
313 # Test
314 assert get_symlink_dirs(id_, cylc_run_dir / id_) == expected
315
316
317 @pytest.mark.parametrize(
318 'flow_file_exists, suiterc_exists, expected_file',
319 [(True, False, WorkflowFiles.FLOW_FILE),
320 (True, True, None),
321 (False, True, WorkflowFiles.SUITE_RC)]
322 )
323 def test_check_flow_file(
324 flow_file_exists: bool, suiterc_exists: bool, expected_file: str,
325 tmp_path: Path
326 ) -> None:
327 """Test check_flow_file() returns the expected path.
328
329 Params:
330 flow_file_exists: Whether a flow.cylc file is found in the dir.
331 suiterc_exists: Whether a suite.rc file is found in the dir.
332 expected_file: Which file's path should get returned.
333 """
334 if flow_file_exists:
335 tmp_path.joinpath(WorkflowFiles.FLOW_FILE).touch()
336 if suiterc_exists:
337 tmp_path.joinpath(WorkflowFiles.SUITE_RC).touch()
338 if expected_file is None:
339 with pytest.raises(WorkflowFilesError) as exc:
340 check_flow_file(tmp_path)
341 assert str(exc.value) == (
342 "Both flow.cylc and suite.rc files are present in "
343 f"{tmp_path}. Please remove one and try again. "
344 "For more information visit: "
345 "https://cylc.github.io/cylc-doc/stable/html/7-to-8/summary.html"
346 "#backward-compatibility"
347 )
348
349 else:
350 assert check_flow_file(tmp_path) == tmp_path.joinpath(expected_file)
351
352
353 def test_detect_both_flow_and_suite(tmp_path):
354 """Test flow.cylc and suite.rc (as files) together in dir raises error."""
355 tmp_path.joinpath(WorkflowFiles.FLOW_FILE).touch()
356 tmp_path.joinpath(WorkflowFiles.SUITE_RC).touch()
357
358 forbidden = is_forbidden(tmp_path / WorkflowFiles.FLOW_FILE)
359 assert forbidden is True
360 with pytest.raises(WorkflowFilesError) as exc:
361 detect_both_flow_and_suite(tmp_path)
362 assert str(exc.value) == (
363 f"Both flow.cylc and suite.rc files are present in {tmp_path}. Please "
364 "remove one and try again. For more information visit: "
365 "https://cylc.github.io/cylc-doc/stable/html/7-to-8/"
366 "summary.html#backward-compatibility"
367 )
368
369
370 def test_detect_both_flow_and_suite_symlinked(tmp_path):
371 """Test flow.cylc symlinked to suite.rc together in dir is permitted."""
372 (tmp_path / WorkflowFiles.SUITE_RC).touch()
373 flow_file = tmp_path.joinpath(WorkflowFiles.FLOW_FILE)
374 flow_file.symlink_to(WorkflowFiles.SUITE_RC)
375 detect_both_flow_and_suite(tmp_path)
376
377
378 def test_flow_symlinked_elsewhere_and_suite_present(tmp_path: Path):
379 """flow.cylc symlinked to suite.rc elsewhere, and suite.rc in dir raises"""
380 tmp_path.joinpath('some_other_dir').mkdir(exist_ok=True)
381 suite_file = tmp_path.joinpath('some_other_dir', WorkflowFiles.SUITE_RC)
382 suite_file.touch()
383 run_dir = tmp_path.joinpath('run_dir')
384 run_dir.mkdir(exist_ok=True)
385 flow_file = (run_dir / WorkflowFiles.FLOW_FILE)
386 flow_file.symlink_to(suite_file)
387 forbidden_external = is_forbidden(flow_file)
388 assert forbidden_external is False
389 (run_dir / WorkflowFiles.SUITE_RC).touch()
390 forbidden = is_forbidden(flow_file)
391 assert forbidden is True
392 with pytest.raises(WorkflowFilesError) as exc:
393 detect_both_flow_and_suite(run_dir)
394 assert str(exc.value).startswith(
395 "Both flow.cylc and suite.rc files are present in "
396 f"{run_dir}. Please remove one and try again."
397 )
398
399
400 def test_is_forbidden_symlink_returns_false_for_non_symlink(tmp_path):
401 """Test sending a non symlink path is not marked as forbidden"""
402 flow_file = (tmp_path / WorkflowFiles.FLOW_FILE)
403 flow_file.touch()
404 forbidden = is_forbidden(Path(flow_file))
405 assert forbidden is False
406
407
408 @pytest.mark.parametrize(
409 'flow_file_target, suiterc_exists, err, expected_file',
410 [
411 pytest.param(
412 WorkflowFiles.SUITE_RC, True, None, WorkflowFiles.FLOW_FILE,
413 id="flow.cylc symlinked to suite.rc"
414 ),
415 pytest.param(
416 WorkflowFiles.SUITE_RC, False, WorkflowFilesError, None,
417 id="flow.cylc symlinked to non-existent suite.rc"
418 ),
419 pytest.param(
420 'inside.cylc', True, WorkflowFilesError, None,
421 id="flow.cylc symlinked to file in run dir, suite.rc exists"
422 ),
423 pytest.param(
424 'inside.cylc', False, None, WorkflowFiles.FLOW_FILE,
425 id="flow.cylc symlinked to file in run dir, no suite.rc"
426 ),
427 pytest.param(
428 '../outside.cylc', True, WorkflowFilesError, None,
429 id="flow.cylc symlinked to file outside, suite.rc exists"
430 ),
431 pytest.param(
432 '../outside.cylc', False, None, WorkflowFiles.FLOW_FILE,
433 id="flow.cylc symlinked to file outside, no suite.rc"
434 ),
435 pytest.param(
436 None, True, None, WorkflowFiles.SUITE_RC,
437 id="No flow.cylc, suite.rc exists"
438 ),
439 pytest.param(
440 None, False, WorkflowFilesError, None,
441 id="No flow.cylc, no suite.rc"
442 ),
443 ]
444 )
445 def test_check_flow_file_symlink(
446 flow_file_target: Optional[str],
447 suiterc_exists: bool,
448 err: Optional[Type[Exception]],
449 expected_file: Optional[str],
450 tmp_path: Path
451 ) -> None:
452 """Test check_flow_file() when flow.cylc is a symlink or doesn't exist.
453
454 Params:
455 flow_file_target: Relative path of the flow.cylc symlink's target,
456 or None if the symlink doesn't exist.
457 suiterc_exists: Whether there is a suite.rc file in the dir.
458 err: Type of exception if expected to get raised.
459 expected_file: Which file's path should get returned, when
460 symlink_suiterc_arg is FALSE (otherwise it will always be
461 flow.cylc, assuming no exception occurred).
462 """
463 run_dir = tmp_path / 'espresso'
464 flow_file = run_dir / WorkflowFiles.FLOW_FILE
465 suiterc = run_dir / WorkflowFiles.SUITE_RC
466 run_dir.mkdir()
467 (run_dir / '../outside.cylc').touch()
468 (run_dir / 'inside.cylc').touch()
469 if suiterc_exists:
470 suiterc.touch()
471 if flow_file_target:
472 flow_file.symlink_to(flow_file_target)
473
474 if err:
475 with pytest.raises(err):
476 check_flow_file(run_dir)
477 else:
478 assert expected_file is not None # otherwise test is wrong
479 result = check_flow_file(run_dir)
480 assert result == run_dir / expected_file
481
482
483 @pytest.mark.parametrize(
484 'id_, installed, named, expected',
485 [('reg1/run1', True, True, True),
486 ('reg2', True, False, True),
487 ('reg3', False, False, False)]
488 )
489 def test_is_installed(tmp_run_dir: Callable, id_, installed, named, expected):
490 """Test is_installed correctly identifies presence of _cylc-install dir"""
491 cylc_run_dir: Path = tmp_run_dir(id_, installed=installed, named=named)
492 actual = is_installed(cylc_run_dir)
493 assert actual == expected
494
495
496 def test_validate_abort_if_flow_file_in_path():
497 assert abort_if_flow_file_in_path(Path("path/to/wflow")) is None
498 with pytest.raises(InputError) as exc_info:
499 abort_if_flow_file_in_path(Path("path/to/wflow/flow.cylc"))
500 assert "Not a valid workflow ID or source directory" in str(exc_info.value)