Debian Codegraph @

tests/u/test_install.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 os
18 import shutil
19 from pathlib import Path
20 from typing import (
21 Any,
22 Callable,
23 Dict,
24 Optional,
25 Tuple,
26 Type,
27 Union,
28 )
29
30 import pytest
31
32 from cylc.flow.exceptions import (
33 InputError,
34 WorkflowFilesError,
35 )
36 from cylc.flow.workflow_files import (
37 WorkflowFiles,
38 get_workflow_source_dir,
39 )
40 from cylc.flow.install import (
41 NESTED_DIRS_MSG,
42 check_nested_dirs,
43 get_rsync_rund_cmd,
44 get_run_dir_info,
45 get_source_workflow_name,
46 install_workflow,
47 parse_cli_sym_dirs,
48 reinstall_workflow,
49 search_install_source_dirs,
50 validate_source_dir,
51 )
52
53 NonCallableFixture = Any
54
55
56 # global.cylc[install]scan depth for these tests:
57 MAX_SCAN_DEPTH = 3
58
59
60 @pytest.fixture
61 def glbl_cfg_max_scan_depth(mock_glbl_cfg: Callable) -> None:
62 mock_glbl_cfg(
63 'cylc.flow.install.glbl_cfg',
64 f'''
65 [install]
66 max depth = {MAX_SCAN_DEPTH}
67 '''
68 )
69
70
71 @pytest.mark.parametrize(
72 'workflow_name, err_expected',
73 [
74 ('foo/' * (MAX_SCAN_DEPTH - 1), False),
75 ('foo/' * MAX_SCAN_DEPTH, True) # /run1 takes it beyond max depth
76 ]
77 )
78 def test_install_workflow__max_depth(
79 workflow_name: str,
80 err_expected: bool,
81 tmp_run_dir: Callable,
82 tmp_src_dir: Callable,
83 glbl_cfg_max_scan_depth: NonCallableFixture,
84 prevent_symlinking,
85 ):
86 """Test that trying to install beyond max depth fails."""
87 src_dir = tmp_src_dir('bar')
88 if err_expected:
89 with pytest.raises(WorkflowFilesError) as exc_info:
90 install_workflow(src_dir, workflow_name)
91 assert "would exceed global.cylc[install]max depth" in str(
92 exc_info.value
93 )
94 else:
95 install_workflow(src_dir, workflow_name)
96
97
98 @pytest.mark.parametrize(
99 'flow_file, expected_exc',
100 [
101 (WorkflowFiles.FLOW_FILE, WorkflowFilesError),
102 (WorkflowFiles.SUITE_RC, WorkflowFilesError),
103 (None, None)
104 ]
105 )
106 def test_install_workflow__next_to_flow_file(
107 flow_file: Optional[str],
108 expected_exc: Optional[Type[Exception]],
109 tmp_run_dir: Callable,
110 tmp_src_dir: Callable,
111 prevent_symlinking,
112 ):
113 """Test that you can't install into a dir that contains a workflow file."""
114 # Setup
115 cylc_run_dir: Path = tmp_run_dir()
116 workflow_dir = cylc_run_dir / 'faden'
117 workflow_dir.mkdir()
118 src_dir: Path = tmp_src_dir('faden')
119 if flow_file:
120 (workflow_dir / flow_file).touch()
121 # Test
122 if expected_exc:
123 with pytest.raises(expected_exc) as exc_info:
124 install_workflow(src_dir, 'faden')
125 assert "Nested run directories not allowed" in str(exc_info.value)
126 else:
127 install_workflow(src_dir, 'faden')
128
129
130 def test_install_workflow__symlink_target_exists(
131 tmp_path: Path,
132 tmp_src_dir: Callable,
133 tmp_run_dir: Callable,
134 mock_glbl_cfg: Callable,
135 ):
136 """Test that you can't install workflow when run dir symlink dir target
137 already exists."""
138 id_ = 'smeagol'
139 src_dir: Path = tmp_src_dir(id_)
140 sym_run = tmp_path / 'sym-run'
141 sym_log = tmp_path / 'sym-log'
142 mock_glbl_cfg(
143 'cylc.flow.pathutil.glbl_cfg',
144 f'''
145 [install]
146 [[symlink dirs]]
147 [[[localhost]]]
148 run = {sym_run}
149 log = {sym_log}
150 '''
151 )
152 msg = "Symlink dir target already exists: .*{}"
153 # Test:
154 (sym_run / 'cylc-run' / id_ / 'run1').mkdir(parents=True)
155 with pytest.raises(WorkflowFilesError, match=msg.format(sym_run)):
156 install_workflow(src_dir)
157
158 shutil.rmtree(sym_run)
159 (
160 sym_log / 'cylc-run' / id_ / 'run1' / WorkflowFiles.LogDir.DIRNAME
161 ).mkdir(parents=True)
162 with pytest.raises(WorkflowFilesError, match=msg.format(sym_log)):
163 install_workflow(src_dir)
164
165
166 def test_check_nested_dirs(
167 tmp_run_dir: Callable,
168 glbl_cfg_max_scan_depth: NonCallableFixture
169 ):
170 """Test that check_nested_dirs() raises when a parent dir is a
171 workflow directory."""
172 cylc_run_dir: Path = tmp_run_dir()
173 test_dir = cylc_run_dir.joinpath('a/' * (MAX_SCAN_DEPTH + 3))
174 # note we check beyond max scan depth (because we're checking upwards)
175 test_dir.mkdir(parents=True)
176 # Parents are not run dirs - ok:
177 check_nested_dirs(test_dir)
178 # Parent contains a run dir but that run dir is not direct ancestor
179 # of our test dir - ok:
180 tmp_run_dir('a/Z')
181 check_nested_dirs(test_dir)
182 # Now make run dir out of parent - not ok:
183 tmp_run_dir('a')
184 with pytest.raises(WorkflowFilesError) as exc:
185 check_nested_dirs(test_dir)
186 assert str(exc.value) == NESTED_DIRS_MSG.format(
187 dir_type='run', dest=test_dir, existing=(cylc_run_dir / 'a')
188 )
189
190
191 @pytest.mark.parametrize(
192 'named_run', [True, False]
193 )
194 @pytest.mark.parametrize(
195 'test_install_path, existing_install_path',
196 [
197 pytest.param(
198 f'{"child/" * (MAX_SCAN_DEPTH + 3)}',
199 '',
200 id="Check parents (beyond max scan depth)"
201 ),
202 pytest.param(
203 '',
204 f'{"child/" * MAX_SCAN_DEPTH}',
205 id="Check children up to max scan depth"
206 )
207 ]
208 )
209 def test_check_nested_dirs_install_dirs(
210 tmp_run_dir: Callable,
211 glbl_cfg_max_scan_depth: NonCallableFixture,
212 test_install_path: str,
213 existing_install_path: str,
214 named_run: bool
215 ):
216 """Test that check nested dirs looks both up and down a tree for
217 WorkflowFiles.Install.DIRNAME.
218
219 Params:
220 test_install_path: Path relative to ~/cylc-run/thing where we are
221 trying to install a workflow.
222 existing_install_path: Path relative to ~/cylc-run/thing where there
223 is an existing install dir.
224 named_run: Whether the workflow we are trying to install has
225 named/numbered run.
226 """
227 cylc_run_dir: Path = tmp_run_dir()
228 existing_install: Path = tmp_run_dir(
229 f'thing/{existing_install_path}/run1', installed=True, named=True
230 ).parent
231 test_install_dir = cylc_run_dir / 'thing' / test_install_path
232 test_run_dir = test_install_dir / 'run1' if named_run else test_install_dir
233 with pytest.raises(WorkflowFilesError) as exc:
234 check_nested_dirs(test_run_dir, test_install_dir)
235 assert str(exc.value) == NESTED_DIRS_MSG.format(
236 dir_type='install', dest=test_run_dir, existing=existing_install
237 )
238
239
240 def test_get_workflow_source_dir_numbered_run(tmp_path):
241 """Test get_workflow_source_dir returns correct source for numbered run"""
242 cylc_install_dir = (
243 tmp_path /
244 "cylc-run" /
245 "flow-name" /
246 "_cylc-install")
247 cylc_install_dir.mkdir(parents=True)
248 run_dir = (tmp_path / "cylc-run" / "flow-name" / "run1")
249 run_dir.mkdir()
250 source_dir = (tmp_path / "cylc-source" / "flow-name")
251 source_dir.mkdir(parents=True)
252 assert get_workflow_source_dir(run_dir) == (None, None)
253 (cylc_install_dir / "source").symlink_to(source_dir)
254 assert get_workflow_source_dir(run_dir) == (
255 str(source_dir), cylc_install_dir / "source")
256
257
258 def test_get_workflow_source_dir_named_run(tmp_path):
259 """Test get_workflow_source_dir returns correct source for named run"""
260 cylc_install_dir = (
261 tmp_path /
262 "cylc-run" /
263 "flow-name" /
264 "_cylc-install")
265 cylc_install_dir.mkdir(parents=True)
266 source_dir = (tmp_path / "cylc-source" / "flow-name")
267 source_dir.mkdir(parents=True)
268 (cylc_install_dir / "source").symlink_to(source_dir)
269 assert get_workflow_source_dir(
270 cylc_install_dir.parent) == (
271 str(source_dir),
272 cylc_install_dir / "source")
273
274
275 def test_reinstall_workflow(tmp_path, capsys):
276
277 cylc_install_dir = (
278 tmp_path /
279 "cylc-run" /
280 "flow-name" /
281 "_cylc-install")
282 cylc_install_dir.mkdir(parents=True)
283 source_dir = (tmp_path / "cylc-source" / "flow-name")
284 source_dir.mkdir(parents=True)
285 (source_dir / "flow.cylc").touch()
286
287 (cylc_install_dir / "source").symlink_to(source_dir)
288 run_dir = cylc_install_dir.parent
289 reinstall_workflow(source_dir, "flow-name", run_dir)
290 assert capsys.readouterr().out == (
291 f"REINSTALLED flow-name from {source_dir}\n")
292
293
294 @pytest.mark.parametrize(
295 'filename, expected_err',
296 [('flow.cylc', None),
297 ('suite.rc', None),
298 ('fluff.txt', (WorkflowFilesError, "Could not find workflow 'baa/baa'"))]
299 )
300 def test_search_install_source_dirs(
301 filename: str, expected_err: Optional[Tuple[Type[Exception], str]],
302 tmp_path: Path, mock_glbl_cfg: Callable):
303 """Test search_install_source_dirs().
304
305 Params:
306 filename: A file to insert into one of the source dirs.
307 expected_err: Exception and message expected to be raised.
308 """
309 horse_dir = tmp_path / 'horse'
310 horse_dir.mkdir()
311 sheep_dir = tmp_path / 'sheep'
312 source_dir = sheep_dir / 'baa' / 'baa'
313 source_dir.mkdir(parents=True)
314 source_dir_file = source_dir / filename
315 source_dir_file.touch()
316 mock_glbl_cfg(
317 'cylc.flow.install.glbl_cfg',
318 f'''
319 [install]
320 source dirs = {horse_dir}, {sheep_dir}
321 '''
322 )
323 if expected_err:
324 err, msg = expected_err
325 with pytest.raises(err) as exc:
326 search_install_source_dirs('baa/baa')
327 assert msg in str(exc.value)
328 else:
329 ret = search_install_source_dirs('baa/baa')
330 assert ret == source_dir
331 assert ret.is_absolute()
332
333
334 def test_search_install_source_dirs_empty(mock_glbl_cfg: Callable):
335 """Test search_install_source_dirs() when no source dirs configured."""
336 mock_glbl_cfg(
337 'cylc.flow.install.glbl_cfg',
338 '''
339 [install]
340 source dirs =
341 '''
342 )
343 with pytest.raises(WorkflowFilesError) as exc:
344 search_install_source_dirs('foo')
345 assert str(exc.value) == (
346 "Cannot find workflow as 'global.cylc[install]source dirs' "
347 "does not contain any paths")
348
349
350 @pytest.mark.parametrize(
351 'path, expected',
352 [
353 ('~/isla/nublar/dennis/nedry', 'dennis/nedry'),
354 ('~/isla/sorna/paul/kirby', 'paul/kirby'),
355 ('~/mos/eisley/owen/skywalker', 'skywalker')
356 ]
357 )
358 def test_get_source_workflow_name(
359 path: str,
360 expected: str,
361 mock_glbl_cfg: Callable
362 ):
363 mock_glbl_cfg(
364 'cylc.flow.install.glbl_cfg',
365 '''
366 [install]
367 source dirs = ~/isla/nublar, ${HOME}/isla/sorna
368 '''
369 )
370 assert get_source_workflow_name(
371 Path(path).expanduser().resolve()) == expected
372
373
374 def test_get_rsync_rund_cmd(
375 tmp_src_dir: Callable,
376 tmp_run_dir: Callable
377 ):
378 """Test rsync command for cylc install/reinstall excludes cylc dirs.
379 """
380 src_dir = tmp_src_dir('foo')
381 cylc_run_dir: Path = tmp_run_dir('rsync_flow', installed=True, named=False)
382 for wdir in [
383 WorkflowFiles.WORK_DIR,
384 WorkflowFiles.SHARE_DIR,
385 WorkflowFiles.LogDir.DIRNAME,
386 ]:
387 cylc_run_dir.joinpath(wdir).mkdir(exist_ok=True)
388 actual_cmd = get_rsync_rund_cmd(src_dir, cylc_run_dir)
389 assert actual_cmd == [
390 'rsync', '-a', '--checksum', '--out-format=%o %n%L', '--no-t',
391 '--exclude=/log', '--exclude=/work', '--exclude=/share',
392 '--exclude=/_cylc-install', '--exclude=/.service',
393 f'{src_dir}/', f'{cylc_run_dir}/']
394
395
396 @pytest.mark.parametrize(
397 'args, expected_relink, expected_run_num, expected_run_dir',
398 [
399 (
400 ['{cylc_run}/numbered', None, False],
401 True, 1, '{cylc_run}/numbered/run1'
402 ),
403 (
404 ['{cylc_run}/named', 'dukat', False],
405 False, None, '{cylc_run}/named/dukat'
406 ),
407 (
408 ['{cylc_run}/unnamed', None, True],
409 False, None, '{cylc_run}/unnamed'
410 ),
411 ]
412 )
413 def test_get_run_dir_info(
414 args: list,
415 expected_relink: bool,
416 expected_run_num: Optional[int],
417 expected_run_dir: Union[Path, str],
418 tmp_run_dir: Callable
419 ):
420 """Test get_run_dir_info().
421
422 Params:
423 args: Input args to function.
424 expected_*: Expected return values.
425 """
426 # Setup
427 cylc_run_dir: Path = tmp_run_dir()
428 sub = lambda x: Path(x.format(cylc_run=cylc_run_dir)) # noqa: E731
429 args[0] = sub(args[0])
430 expected_run_dir = sub(expected_run_dir)
431 # Test
432 assert get_run_dir_info(*args) == (
433 expected_relink, expected_run_num, expected_run_dir
434 )
435 assert expected_run_dir.is_absolute()
436
437
438 def test_get_run_dir_info__increment_run_num(tmp_run_dir: Callable):
439 """Test that get_run_dir_info() increments run number and unlinks runN."""
440 # Setup
441 cylc_run_dir: Path = tmp_run_dir()
442 run_dir: Path = tmp_run_dir('gowron/run1')
443 runN = run_dir.parent / WorkflowFiles.RUN_N
444 assert os.path.lexists(runN)
445 # Test
446 assert get_run_dir_info(cylc_run_dir / 'gowron', None, False) == (
447 True, 2, cylc_run_dir / 'gowron' / 'run2'
448 )
449 assert not os.path.lexists(runN)
450
451
452 def test_get_run_dir_info__fail(tmp_run_dir: Callable):
453 # Test that you can't install named runs when numbered runs exist
454 cylc_run_dir: Path = tmp_run_dir()
455 run_dir: Path = tmp_run_dir('martok/run1')
456 with pytest.raises(WorkflowFilesError) as excinfo:
457 get_run_dir_info(run_dir.parent, 'targ', False)
458 assert "contains installed numbered runs" in str(excinfo.value)
459
460 # Test that you can install numbered run in an empty dir
461 base_dir = cylc_run_dir / 'odo'
462 base_dir.mkdir()
463 get_run_dir_info(base_dir, None, False)
464 # But not when named runs exist
465 tmp_run_dir('odo/meter')
466 with pytest.raises(WorkflowFilesError) as excinfo:
467 get_run_dir_info(base_dir, None, False)
468 assert "contains an installed workflow"
469
470
471 @pytest.mark.parametrize(
472 'symlink_dirs, err_msg, expected',
473 [
474 ('log=$shortbread, share= $bourbon,share/cycle= $digestive, ',
475 "There is an error in --symlink-dirs option:",
476 None
477 ),
478 ('log=$shortbread share= $bourbon share/cycle= $digestive ',
479 "There is an error in --symlink-dirs option:"
480 " log=$shortbread share= $bourbon share/cycle= $digestive . "
481 "Try entering option in the form --symlink-dirs="
482 "'log=$DIR, share=$DIR2, ...'",
483 None
484 ),
485 ('run=$NICE, log= $Garibaldi, share/cycle=$RichTea', None,
486 {'localhost': {
487 'run': '$NICE',
488 'log': '$Garibaldi',
489 'share/cycle': '$RichTea'
490 }}
491 ),
492 ('some_other_dir=$bourbon',
493 'some_other_dir not a valid entry for --symlink-dirs',
494 {'some_other_dir': '£bourbon'}
495 ),
496 ]
497 )
498 def test_parse_cli_sym_dirs(
499 symlink_dirs: str,
500 err_msg: str,
501 expected: Dict[str, Dict[str, Any]]
502 ):
503 """Test parse_cli_sym_dirs returns dict or correctly raises errors on cli
504 symlink dir options"""
505 if err_msg is not None:
506 with pytest.raises(InputError) as exc:
507 parse_cli_sym_dirs(symlink_dirs)
508 assert err_msg in str(exc)
509
510 else:
511 actual = parse_cli_sym_dirs(symlink_dirs)
512
513 assert actual == expected
514
515
516 def test_validate_source_dir(tmp_run_dir: Callable, tmp_src_dir: Callable):
517 cylc_run_dir: Path = tmp_run_dir()
518 src_dir: Path = tmp_src_dir('ludlow')
519 validate_source_dir(src_dir, 'ludlow')
520 # Test that src dir must have flow file
521 (src_dir / WorkflowFiles.FLOW_FILE).unlink()
522 with pytest.raises(WorkflowFilesError):
523 validate_source_dir(src_dir, 'ludlow')
524 # Test that reserved dirnames not allowed in src dir
525 src_dir = tmp_src_dir('roland')
526 (src_dir / 'log').mkdir()
527 with pytest.raises(WorkflowFilesError) as exc_info:
528 validate_source_dir(src_dir, 'roland')
529 assert "exists in source directory" in str(exc_info.value)
530 # Test that src dir is allowed to be inside ~/cylc-run
531 src_dir = cylc_run_dir / 'dieter'
532 src_dir.mkdir()
533 (src_dir / WorkflowFiles.FLOW_FILE).touch()
534 validate_source_dir(src_dir, 'dieter')
535 # Test that src dir is not allowed to be an installed dir.
536 src_dir = cylc_run_dir / 'ajay'
537 src_dir.mkdir()
538 (src_dir / WorkflowFiles.Install.DIRNAME).mkdir()
539 (src_dir / WorkflowFiles.FLOW_FILE).touch()
540 with pytest.raises(WorkflowFilesError) as exc_info:
541 validate_source_dir(src_dir, 'ajay')
542 assert "exists in source directory" in str(exc_info.value)
543
544
545 def test_install_workflow_failif_name_name(tmp_src_dir, tmp_run_dir):
546 """If a run_name is given validate_workflow_name is called on
547 the workflow and the run name in combination.
548 """
549 src_dir: Path = tmp_src_dir('ludlow')
550 # It only has a workflow name:
551 with pytest.raises(WorkflowFilesError, match='can only contain'):
552 install_workflow(src_dir, workflow_name='foo?')
553 # It only has a run name:
554 with pytest.raises(WorkflowFilesError, match='can only contain'):
555 install_workflow(src_dir, run_name='foo?')
556 # It has a legal workflow name, but an invalid run name:
557 with pytest.raises(WorkflowFilesError, match='can only contain'):
558 install_workflow(src_dir, workflow_name='foo', run_name='bar?')
559
560
561 def test_install_workflow_failif_reserved_name(tmp_src_dir, tmp_run_dir):
562 """Reserved names cause install validation failure.
563
564 n.b. manually defined to avoid test dependency on workflow_files.
565 """
566 src_dir = tmp_src_dir('ludlow')
567 is_reserved = '(that filename is reserved)'
568 reserved_names = {
569 'share',
570 'log',
571 'runN',
572 'suite.rc',
573 'work',
574 '_cylc-install',
575 'flow.cylc',
576 # .service fails because starting a workflow/run can't start with "."
577 # And that check fails first.
578 # '.service'
579 }
580 install_workflow(src_dir, workflow_name='ok', run_name='also_ok')
581 for name in reserved_names:
582 with pytest.raises(WorkflowFilesError, match=is_reserved):
583 install_workflow(src_dir, workflow_name='ok', run_name=name)
584 with pytest.raises(WorkflowFilesError, match=is_reserved):
585 install_workflow(src_dir, workflow_name=name)
586 with pytest.raises(WorkflowFilesError, match=is_reserved):
587 install_workflow(src_dir, workflow_name=name, run_name='ok')