Debian Codegraph @

tests/u/test_pathutil.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 """Tests for "cylc.flow.pathutil"."""
17
18 import logging
19 import os
20 from pathlib import Path
21 import pytest
22 from pytest import param
23 from typing import Callable, Dict, Iterable, List, Set
24 from unittest.mock import Mock, patch, call
25
26 from cylc.flow.exceptions import InputError, WorkflowFilesError
27 from cylc.flow.pathutil import (
28 EXPLICIT_RELATIVE_PATH_REGEX,
29 expand_path,
30 get_dirs_to_symlink,
31 get_next_rundir_number,
32 get_remote_workflow_run_dir,
33 get_remote_workflow_run_job_dir,
34 get_workflow_run_dir,
35 get_workflow_run_job_dir,
36 get_workflow_run_scheduler_log_dir,
37 get_workflow_run_scheduler_log_path,
38 get_workflow_run_pub_db_path,
39 get_workflow_run_config_log_dir,
40 get_workflow_run_share_dir,
41 get_workflow_run_work_dir,
42 get_workflow_test_log_path,
43 is_relative_to,
44 make_localhost_symlinks,
45 make_workflow_run_tree,
46 parse_rm_dirs,
47 remove_dir_and_target,
48 remove_dir_or_file,
49 remove_empty_parents,
50 get_workflow_name_from_id
51 )
52
53 from .conftest import MonkeyMock
54
55
56 HOME = Path.home()
57
58
59 @pytest.mark.parametrize(
60 'string, match_expected',
61 [
62 ('./foo/bar', True),
63 ('../foo', True),
64 ('./', True),
65 ('../', True),
66 ('.', True),
67 ('..', True),
68 ('foo/bar', False),
69 ('.foo/bar', False),
70 ('foo/..', False),
71 ]
72 )
73 def test_explicit_relative_path_regex(string: str, match_expected: bool):
74 assert bool(EXPLICIT_RELATIVE_PATH_REGEX.match(string)) is match_expected
75
76
77 @pytest.mark.parametrize(
78 'path, expected',
79 [('~/moo', os.path.join(HOME, 'moo')),
80 ('$HOME/moo', os.path.join(HOME, 'moo')),
81 ('~/$FOO/moo', os.path.join(HOME, 'foo', 'bar', 'moo')),
82 ('$NON_EXIST/moo', '$NON_EXIST/moo')]
83 )
84 def test_expand_path(
85 path: str, expected: str,
86 monkeypatch: pytest.MonkeyPatch
87 ) -> None:
88 monkeypatch.setenv('FOO', 'foo/bar')
89 monkeypatch.delenv('NON_EXIST', raising=False)
90 assert expand_path(path) == expected
91
92
93 @pytest.mark.parametrize(
94 'func, extra_args, expected',
95 [
96 (get_remote_workflow_run_dir, (), "$HOME/cylc-run/foo"),
97 (
98 get_remote_workflow_run_dir,
99 ("comes", "true"),
100 "$HOME/cylc-run/foo/comes/true",
101 ),
102 (
103 get_remote_workflow_run_job_dir,
104 (),
105 "$HOME/cylc-run/foo/log/job"),
106 (
107 get_remote_workflow_run_job_dir,
108 ("comes", "true"),
109 "$HOME/cylc-run/foo/log/job/comes/true",
110 )
111 ]
112 )
113 def test_get_remote_workflow_run_dirs(
114 func: Callable, extra_args: Iterable[str], expected: str,
115 ) -> None:
116 """Tests for get_remote_workflow_run_[|job|work]_dir"""
117 if extra_args:
118 result = func('foo', *extra_args)
119 else:
120 result = func('foo')
121 assert result == expected
122
123
124 @pytest.mark.parametrize(
125 'func, tail1',
126 [(get_workflow_run_dir, ''),
127 (get_workflow_run_job_dir, '/log/job'),
128 (get_workflow_run_scheduler_log_dir, '/log/scheduler'),
129 (get_workflow_run_config_log_dir, '/log/config'),
130 (get_workflow_run_share_dir, '/share'),
131 (get_workflow_run_work_dir, '/work')]
132 )
133 @pytest.mark.parametrize(
134 'args, tail2',
135 [([], ''),
136 (['comes', 'true'], '/comes/true')]
137 )
138 def test_get_workflow_run_dirs(
139 func: Callable, tail1: str, args: List[str], tail2: str
140 ) -> None:
141 """Usage of get_workflow_run_*dir.
142
143 Params:
144 func: get_remote_* function to test
145 tail1: expected tail of return value from configuration
146 args: extra *args
147 tail2: expected tail of return value from extra args
148 """
149 homedir = os.getenv("HOME")
150
151 expected_result = f'{homedir}/cylc-run/my-workflow/dream{tail1}{tail2}'
152 assert func('my-workflow/dream', *args) == expected_result
153
154
155 @pytest.mark.parametrize(
156 'func, tail',
157 [(get_workflow_run_scheduler_log_path, '/log/scheduler/log'),
158 (get_workflow_run_pub_db_path, '/log/db'),
159 (get_workflow_test_log_path, '/log/scheduler/reftest.log')]
160 )
161 def test_get_workflow_run_names(func: Callable, tail: str) -> None:
162 """Usage of get_workflow_run_*name.
163
164 Params:
165 func: get_remote_* function to test
166 cfg: configuration used in mocked global configuration
167 tail: expected tail of return value from configuration
168 """
169 homedir = os.getenv("HOME")
170
171 assert (
172 func('my-workflow/dream') ==
173 f'{homedir}/cylc-run/my-workflow/dream{tail}'
174 )
175
176
177 def test_make_workflow_run_tree(
178 tmp_run_dir: Callable, caplog: pytest.LogCaptureFixture
179 ) -> None:
180 run_dir: Path = tmp_run_dir('my-workflow')
181 caplog.set_level(logging.DEBUG) # Only used for debugging test
182
183 make_workflow_run_tree('my-workflow')
184 # Check that directories have been created
185 for subdir in [
186 '',
187 'log/scheduler',
188 'log/job',
189 'log/config',
190 'share',
191 'work'
192 ]:
193 assert (run_dir / subdir).is_dir() is True
194
195
196 @pytest.mark.parametrize(
197 'mocked_glbl_cfg, output',
198 [
199 pytest.param( # basic
200 '''
201 [install]
202 [[symlink dirs]]
203 [[[the_matrix]]]
204 run = $DEE
205 work = $DAH
206 log = $DUH
207 log/job =$RAY
208 share = $DOH
209 share/cycle = $DAH
210 ''',
211 {
212 'run': '$DEE/cylc-run/morpheus',
213 'work': '$DAH/cylc-run/morpheus/work',
214 'log': '$DUH/cylc-run/morpheus/log',
215 'log/job': '$RAY/cylc-run/morpheus/log/job',
216 'share': '$DOH/cylc-run/morpheus/share',
217 'share/cycle': '$DAH/cylc-run/morpheus/share/cycle'
218 },
219 id="basic"
220 ),
221 pytest.param( # remove nested run symlinks
222 '''
223 [install]
224 [[symlink dirs]]
225 [[[the_matrix]]]
226 run = $DEE
227 work = $DAH
228 log = $DEE
229 share = $DOH
230 share/cycle = $DAH
231 ''',
232 {
233 'run': '$DEE/cylc-run/morpheus',
234 'work': '$DAH/cylc-run/morpheus/work',
235 'share': '$DOH/cylc-run/morpheus/share',
236 'share/cycle': '$DAH/cylc-run/morpheus/share/cycle'
237 },
238 id="remove nested run symlinks"
239 ),
240 pytest.param( # remove only nested run symlinks
241 '''
242 [install]
243 [[symlink dirs]]
244 [[[the_matrix]]]
245 run = $DOH
246 log = $DEE
247 share = $DEE
248 ''',
249 {
250 'run': '$DOH/cylc-run/morpheus',
251 'log': '$DEE/cylc-run/morpheus/log',
252 'share': '$DEE/cylc-run/morpheus/share'
253 },
254 id="remove only nested run symlinks"
255 ),
256 pytest.param( # blank entries
257 '''
258 [install]
259 [[symlink dirs]]
260 [[[the_matrix]]]
261 run =
262 log = ""
263 share =
264 work = " "
265 ''',
266 {},
267 id="blank entries"
268 )
269 ]
270 )
271 def test_get_dirs_to_symlink(
272 mocked_glbl_cfg: str,
273 output: Dict[str, str],
274 mock_glbl_cfg: Callable,
275 monkeypatch: pytest.MonkeyPatch
276 ) -> None:
277 # Set env var 'DEE', but we expect it to be unexpanded
278 monkeypatch.setenv('DEE', 'poiuytrewq')
279 mock_glbl_cfg('cylc.flow.pathutil.glbl_cfg', mocked_glbl_cfg)
280 dirs = get_dirs_to_symlink('the_matrix', 'morpheus')
281 assert dirs == output
282
283
284 @patch('cylc.flow.pathutil.get_workflow_run_dir')
285 @patch('cylc.flow.pathutil.get_dirs_to_symlink')
286 def test_make_localhost_symlinks_calls_make_symlink_for_each_key_value_dir(
287 mocked_dirs_to_symlink: Mock,
288 mocked_get_workflow_run_dir: Mock,
289 monkeypatch: pytest.MonkeyPatch, monkeymock: MonkeyMock
290 ) -> None:
291 mocked_dirs_to_symlink.return_value = {
292 'run': '$DOH/trinity',
293 'log': '$DEE/trinity/log',
294 'share': '$DEE/trinity/share'
295 }
296 mocked_get_workflow_run_dir.return_value = "rund"
297 for v in ('DOH', 'DEE'):
298 monkeypatch.setenv(v, 'expanded')
299 mocked_make_symlink = monkeymock('cylc.flow.pathutil.make_symlink_dir')
300
301 make_localhost_symlinks('rund', 'workflow')
302 mocked_make_symlink.assert_has_calls([
303 call('rund', 'expanded/trinity'),
304 call('rund/log', 'expanded/trinity/log'),
305 call('rund/share', 'expanded/trinity/share')
306 ])
307
308
309 @patch('cylc.flow.pathutil.get_workflow_run_dir')
310 @patch('cylc.flow.pathutil.make_symlink_dir')
311 @patch('cylc.flow.pathutil.get_dirs_to_symlink')
312 def test_incorrect_environment_variables_raise_error(
313 mocked_dirs_to_symlink,
314 mocked_make_symlink,
315 mocked_get_workflow_run_dir,
316 monkeypatch: pytest.MonkeyPatch
317 ):
318 monkeypatch.delenv('doh', raising=False)
319 mocked_dirs_to_symlink.return_value = {
320 'run': '$doh/cylc-run/test_workflow'}
321 mocked_get_workflow_run_dir.return_value = "rund"
322
323 with pytest.raises(WorkflowFilesError) as excinfo:
324 make_localhost_symlinks('rund', 'test_workflow')
325 assert (
326 "Can't symlink to $doh/cylc-run/test_workflow\n"
327 "Undefined variables, check global config: $doh"
328 ) in str(excinfo.value)
329
330
331 @pytest.mark.parametrize(
332 'filetype, expected_err',
333 [('dir', None),
334 ('file', NotADirectoryError),
335 (None, FileNotFoundError)]
336 )
337 def test_remove_dir_and_target(filetype, expected_err, tmp_path):
338 """Test that remove_dir_and_target() can delete nested dirs and handle
339 bad paths."""
340 test_path = tmp_path.joinpath('foo/bar')
341 if filetype == 'dir':
342 # Test removal of sub directories too
343 sub_dir = test_path.joinpath('baz')
344 sub_dir.mkdir(parents=True)
345 sub_dir_file = sub_dir.joinpath('meow')
346 sub_dir_file.touch()
347 elif filetype == 'file':
348 test_path = tmp_path.joinpath('meow')
349 test_path.touch()
350
351 if expected_err:
352 with pytest.raises(expected_err):
353 remove_dir_and_target(test_path)
354 else:
355 remove_dir_and_target(test_path)
356 assert test_path.exists() is False
357 assert test_path.is_symlink() is False
358
359
360 @pytest.mark.parametrize(
361 'target, expected_err',
362 [('dir', None),
363 ('file', NotADirectoryError),
364 (None, None)]
365 )
366 def test_remove_dir_and_target_symlinks(target, expected_err, tmp_path):
367 """Test that remove_dir_and_target() can delete symlinks, including
368 the target."""
369 target_path = tmp_path.joinpath('x/y')
370 target_path.mkdir(parents=True)
371
372 tmp_path.joinpath('a').mkdir()
373 symlink_path = tmp_path.joinpath('a/b')
374
375 if target == 'dir':
376 # Add a file into the the target dir to check it removes that ok
377 target_path.joinpath('meow').touch()
378 symlink_path.symlink_to(target_path)
379 elif target == 'file':
380 target_path = target_path.joinpath('meow')
381 target_path.touch()
382 symlink_path.symlink_to(target_path)
383 elif target is None:
384 symlink_path.symlink_to(target_path)
385 # Break symlink
386 target_path.rmdir()
387
388 if expected_err:
389 with pytest.raises(expected_err):
390 remove_dir_and_target(symlink_path)
391 else:
392 remove_dir_and_target(symlink_path)
393 for path in [symlink_path, target_path]:
394 assert path.exists() is False
395 assert path.is_symlink() is False
396
397
398 @pytest.mark.parametrize(
399 'func', [remove_dir_and_target, remove_dir_or_file]
400 )
401 def test_remove_relative(func: Callable, tmp_path: Path):
402 """Test that you cannot use remove_dir_and_target() or remove_dir_or_file()
403 on relative paths.
404
405 When removing a path, we want to be absolute-ly sure where it is!
406 """
407 # cd to temp dir in case we accidentally succeed in deleting the path
408 os.chdir(tmp_path)
409 with pytest.raises(ValueError) as cm:
410 func('foo/bar')
411 assert 'Path must be absolute' in str(cm.value)
412
413
414 def test_remove_dir_or_file(tmp_path: Path):
415 """Test remove_dir_or_file()"""
416 a_file = tmp_path.joinpath('fyle')
417 a_file.touch()
418 assert a_file.exists()
419 remove_dir_or_file(a_file)
420 assert a_file.exists() is False
421
422 a_symlink = tmp_path.joinpath('simlynk')
423 a_file.touch()
424 a_symlink.symlink_to(a_file)
425 assert a_symlink.is_symlink()
426 remove_dir_or_file(a_symlink)
427 assert a_symlink.is_symlink() is False
428 assert a_file.exists()
429
430 a_dir = tmp_path.joinpath('der')
431 # Add contents to check whole tree is removed
432 sub_dir = a_dir.joinpath('sub_der')
433 sub_dir.mkdir(parents=True)
434 sub_dir.joinpath('fyle').touch()
435 assert a_dir.exists()
436 remove_dir_or_file(a_dir)
437 assert a_dir.exists() is False
438
439
440 def test_remove_empty_parents(tmp_path: Path):
441 """Test that _remove_empty_parents() doesn't remove parents containing a
442 sibling."""
443 # -- Setup --
444 id_ = 'foo/bar/baz/qux'
445 path = tmp_path.joinpath(id_)
446 tmp_path.joinpath('foo/bar/baz').mkdir(parents=True)
447 # Note qux does not exist, but that shouldn't matter
448 sibling_reg = 'foo/darmok'
449 sibling_path = tmp_path.joinpath(sibling_reg)
450 sibling_path.mkdir()
451 # -- Test --
452 remove_empty_parents(path, id_)
453 assert tmp_path.joinpath('foo/bar').exists() is False
454 assert tmp_path.joinpath('foo').exists() is True
455 # Check it skips non-existent dirs, and stops at the right place too
456 tmp_path.joinpath('foo/bar').mkdir()
457 sibling_path.rmdir()
458 remove_empty_parents(path, id_)
459 assert tmp_path.joinpath('foo').exists() is False
460 assert tmp_path.exists() is True
461
462
463 @pytest.mark.parametrize(
464 'path, tail, exc_msg',
465 [
466 pytest.param(
467 'meow/foo/darmok', 'foo/darmok', "path must be absolute",
468 id="relative path"
469 ),
470 pytest.param(
471 '/meow/foo/darmok', '/foo/darmok',
472 "tail must not be an absolute path",
473 id="absolute tail"
474 ),
475 pytest.param(
476 '/meow/foo/darmok', 'foo/jalad',
477 "path '/meow/foo/darmok' does not end with 'foo/jalad'",
478 id="tail not in path"
479 )
480 ]
481 )
482 def test_remove_empty_parents_bad(path: str, tail: str, exc_msg: str):
483 """Test that _remove_empty_parents() fails appropriately with bad args."""
484 with pytest.raises(ValueError) as exc:
485 remove_empty_parents(path, tail)
486 assert exc_msg in str(exc.value)
487
488
489 @pytest.mark.parametrize(
490 'dirs, expected',
491 [
492 ([" "], set()),
493 (["foo", "bar"], {"foo", "bar"}),
494 (["foo:bar", "baz/*"], {"foo", "bar", "baz/*"}),
495 ([" :foo :bar:"], {"foo", "bar"}),
496 (["foo/:bar//baz "], {"foo/", "bar/baz"}),
497 ([".foo", "..bar", " ./gah"], {".foo", "..bar", "gah"})
498 # Note '..bar' is a valid filename (doesn't point to parent dir)
499 ]
500 )
501 def test_parse_rm_dirs(dirs: List[str], expected: Set[str]):
502 """Test parse_dirs()"""
503 assert parse_rm_dirs(dirs) == expected
504
505
506 @pytest.mark.parametrize(
507 'dirs, err_msg',
508 [
509 (["foo:/bar"],
510 "--rm option cannot take absolute paths"),
511 ([".."],
512 "cannot take paths that point to the run directory or above"),
513 (["foo:../bar"],
514 "cannot take paths that point to the run directory or above"),
515 (["foo:bar/../../gah"],
516 "cannot take paths that point to the run directory or above"),
517 ]
518 )
519 def test_parse_rm_dirs__bad(dirs: List[str], err_msg: str):
520 """Test parse_dirs() with bad inputs"""
521 with pytest.raises(InputError) as exc:
522 parse_rm_dirs(dirs)
523 assert err_msg in str(exc.value)
524
525
526 @pytest.mark.parametrize(
527 'expect, files, runN',
528 [
529 param(1, [], False, id='1st run (from filenames)'),
530 param(2, ['run1'], False, id='2nd run (from filenames)'),
531 param(
532 1000, ['run20', 'run400', 'run999'], False,
533 id='1000th run (from filenames)'
534 ),
535 param(
536 6, ['run1', 'run5'], False,
537 id='Non-sequential (from filenames)'),
538 param(2, ['run1'], True, id='2nd run (from symlink)'),
539 param(100, ['run1', 'run99'], True, id='100th run (from symlink)'),
540 param(42, ['foo', 'foo12', 'run41'], False, id='with dirs not runX')
541 ]
542 )
543 def test_get_next_rundir_number(tmp_path, expect, files, runN):
544 for file_ in files:
545 (tmp_path / file_).mkdir()
546 if runN:
547 (tmp_path / 'runN').symlink_to(tmp_path / files[-1])
548 assert get_next_rundir_number(tmp_path) == expect
549
550
551 @pytest.mark.parametrize(
552 'name, id_, src',
553 (
554 param('my_workflow1', 'my_workflow1', False, id='--no-run-name'),
555 param('my_workflow2', 'my_workflow2/run22', False, id='installed'),
556 param(
557 'my_workflow3', 'my_workflow3/foo', False, id='--run-name="foo"'),
558 param('my_workflow4', 'my_workflow4', True, id='not installed'),
559 )
560 )
561 def test_get_workflow_name_from_id(
562 tmp_path, monkeypatch,
563 name: str, id_: str, src: bool
564 ) -> None:
565 """It gets the correct name.
566
567 args:
568 name: Workflow name
569 id: Workflow id
570 src: Is this workflow a source or installed workflow.
571 """
572 monkeypatch.setattr(
573 'cylc.flow.pathutil.get_cylc_run_dir', lambda: tmp_path)
574
575 (tmp_path / name).mkdir(exist_ok=True)
576 if not src:
577 (tmp_path / name / '_cylc-install').mkdir(exist_ok=True)
578 (tmp_path / id_).mkdir(exist_ok=True)
579
580 result = get_workflow_name_from_id(id_)
581 assert result == name
582
583
584 @pytest.mark.parametrize('abs_path', [True, False])
585 @pytest.mark.parametrize('path1, path2, expected', [
586 param('/foo/bar/baz', '/foo/bar', True, id="child"),
587 param('/foo/bar', '/foo/bar/baz', False, id="parent"),
588 param('/foo/bar', '/foo/bar', True, id="same-path"),
589 param('/cat/dog', '/hat/bog', False, id="different"),
590 param('/a/b/c/../x/y', '/a/b/x', True, id="trickery"),
591 ])
592 def test_is_relative_to(abs_path, path1, path2, expected):
593 if not abs_path: # absolute & relative versions of same test
594 path1.lstrip('/')
595 path2.lstrip('/')
596 assert is_relative_to(path1, path2) == expected