Debian Codegraph @

tests/unit/test_clean.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 from glob import iglob
18 import logging
19 import os
20 from pathlib import Path
21 import shutil
22 from subprocess import Popen
23 from typing import (
24 TYPE_CHECKING,
25 Any,
26 Callable,
27 Dict,
28 List,
29 Optional,
30 Set,
31 Tuple,
32 Type,
33 )
34 from unittest import mock
35
36 import pytest
37
38 from cylc.flow import (
39 CYLC_LOG,
40 clean as cylc_clean,
41 )
42 from cylc.flow.clean import (
43 _clean_using_glob,
44 _remote_clean_cmd,
45 clean,
46 glob_in_run_dir,
47 init_clean,
48 )
49 from cylc.flow.exceptions import (
50 CylcError,
51 InputError,
52 SchedulerAlive,
53 ServiceFileError,
54 WorkflowFilesError,
55 )
56 from cylc.flow.pathutil import parse_rm_dirs
57 from cylc.flow.scripts.clean import CleanOptions
58 from cylc.flow.workflow_files import (
59 WorkflowFiles,
60 get_symlink_dirs,
61 )
62
63 from .filetree import (
64 FILETREE_1,
65 FILETREE_2,
66 FILETREE_3,
67 FILETREE_4,
68 Symlink,
69 create_filetree,
70 get_filetree_as_list,
71 )
72
73
74 if TYPE_CHECKING:
75 from .conftest import MonkeyMock
76
77
78 NonCallableFixture = Any
79
80
81 # global.cylc[install]scan depth for these tests:
82 MAX_SCAN_DEPTH = 3
83
84
85 @pytest.fixture
86 def glbl_cfg_max_scan_depth(mock_glbl_cfg: Callable) -> None:
87 mock_glbl_cfg(
88 'cylc.flow.workflow_files.glbl_cfg',
89 f'''
90 [install]
91 max depth = {MAX_SCAN_DEPTH}
92 '''
93 )
94
95
96 @pytest.mark.parametrize(
97 'id_, stopped, err, err_msg',
98 [
99 ('foo/..', True, WorkflowFilesError,
100 "cannot be a path that points to the cylc-run directory or above"),
101 ('foo/../..', True, WorkflowFilesError,
102 "cannot be a path that points to the cylc-run directory or above"),
103 ('foo', False, ServiceFileError, "Cannot clean running workflow"),
104 ]
105 )
106 def test_clean_check__fail(
107 id_: str,
108 stopped: bool,
109 err: Type[Exception],
110 err_msg: str,
111 monkeypatch: pytest.MonkeyPatch,
112 tmp_path: Path,
113 ) -> None:
114 """Test that _clean_check() fails appropriately.
115
116 Params:
117 id_: Workflow name.
118 stopped: Whether the workflow is stopped when _clean_check() is called.
119 err: Expected error class.
120 err_msg: Message that is expected to be in the exception.
121 """
122 def mocked_detect_old_contact_file(*a, **k):
123 if not stopped:
124 raise SchedulerAlive('Mocked error')
125
126 monkeypatch.setattr(
127 'cylc.flow.clean.detect_old_contact_file',
128 mocked_detect_old_contact_file
129 )
130
131 with pytest.raises(err) as exc:
132 cylc_clean._clean_check(CleanOptions(), id_, tmp_path)
133 assert err_msg in str(exc.value)
134
135
136 @pytest.mark.parametrize(
137 'db_platforms, opts, clean_called, remote_clean_called',
138 [
139 pytest.param(
140 ['localhost', 'localhost'], {}, True, False,
141 id="Only platform in DB is localhost"
142 ),
143 pytest.param(
144 ['horse'], {}, True, True,
145 id="Remote platform in DB"
146 ),
147 pytest.param(
148 ['horse'], {'local_only': True}, True, False,
149 id="Local clean only"
150 ),
151 pytest.param(
152 ['horse'], {'remote_only': True}, False, True,
153 id="Remote clean only"
154 )
155 ]
156 )
157 def test_init_clean(
158 db_platforms: List[str],
159 opts: Dict[str, Any],
160 clean_called: bool,
161 remote_clean_called: bool,
162 monkeypatch: pytest.MonkeyPatch, monkeymock: 'MonkeyMock',
163 tmp_run_dir: Callable
164 ) -> None:
165 """Test the init_clean() function logic.
166
167 Params:
168 db_platforms: Platform names that would be loaded from the database.
169 opts: Any options passed to the cylc clean CLI.
170 clean_called: If a local clean is expected to go ahead.
171 remote_clean_called: If a remote clean is expected to go ahead.
172 """
173 id_ = 'foo/bar/'
174 rdir = tmp_run_dir(id_, installed=True)
175 Path(rdir, WorkflowFiles.Service.DIRNAME, WorkflowFiles.Service.DB).touch()
176 mock_clean = monkeymock('cylc.flow.clean.clean')
177 mock_remote_clean = monkeymock('cylc.flow.clean.remote_clean')
178 monkeypatch.setattr('cylc.flow.clean.get_platforms_from_db',
179 lambda x: set(db_platforms))
180
181 init_clean(id_, opts=CleanOptions(**opts))
182 assert mock_clean.called is clean_called
183 assert mock_remote_clean.called is remote_clean_called
184
185
186 def test_init_clean__no_dir(
187 monkeymock: 'MonkeyMock', tmp_run_dir: Callable,
188 caplog: pytest.LogCaptureFixture
189 ) -> None:
190 """Test init_clean() when the run dir doesn't exist"""
191 caplog.set_level(logging.INFO, CYLC_LOG)
192 mock_clean = monkeymock('cylc.flow.clean.clean')
193 mock_remote_clean = monkeymock('cylc.flow.clean.remote_clean')
194
195 init_clean('foo/bar', opts=CleanOptions())
196 assert "No directory to clean" in caplog.text
197 assert mock_clean.called is False
198 assert mock_remote_clean.called is False
199
200
201 def test_init_clean__no_db(
202 monkeymock: 'MonkeyMock', tmp_run_dir: Callable,
203 caplog: pytest.LogCaptureFixture
204 ) -> None:
205 """Test init_clean() when the workflow database doesn't exist"""
206 caplog.set_level(logging.INFO, CYLC_LOG)
207 tmp_run_dir('bespin')
208 mock_clean = monkeymock('cylc.flow.clean.clean')
209 mock_remote_clean = monkeymock('cylc.flow.clean.remote_clean')
210
211 init_clean('bespin', opts=CleanOptions())
212 assert (
213 "No workflow database for bespin - will only clean locally"
214 ) in caplog.text
215 assert mock_clean.called is True
216 assert mock_remote_clean.called is False
217
218
219 def test_init_clean__remote_only_no_db(
220 monkeymock: 'MonkeyMock', tmp_run_dir: Callable
221 ) -> None:
222 """Test remote-only init_clean() when the workflow DB doesn't exist"""
223 tmp_run_dir('hoth')
224 mock_clean = monkeymock('cylc.flow.clean.clean')
225 mock_remote_clean = monkeymock('cylc.flow.clean.remote_clean')
226
227 with pytest.raises(ServiceFileError) as exc:
228 init_clean('hoth', opts=CleanOptions(remote_only=True))
229 assert (
230 "No workflow database for hoth - cannot perform remote clean"
231 ) in str(exc.value)
232 assert mock_clean.called is False
233 assert mock_remote_clean.called is False
234
235
236 def test_init_clean__running_workflow(
237 monkeypatch: pytest.MonkeyPatch, tmp_run_dir: Callable
238 ) -> None:
239 """Test init_clean() fails when workflow is still running"""
240 def mock_err(*args, **kwargs):
241 raise SchedulerAlive("Mocked error")
242 monkeypatch.setattr('cylc.flow.clean.detect_old_contact_file',
243 mock_err)
244 tmp_run_dir('yavin')
245
246 with pytest.raises(ServiceFileError) as exc:
247 init_clean('yavin', opts=CleanOptions())
248 assert "Cannot clean running workflow" in str(exc.value)
249
250
251 @pytest.mark.parametrize(
252 'rm_dirs, expected_clean, expected_remote_clean',
253 [(None, None, []),
254 (["r2d2:c3po"], {"r2d2", "c3po"}, ["r2d2:c3po"])]
255 )
256 def test_init_clean__rm_dirs(
257 rm_dirs: Optional[List[str]],
258 expected_clean: Set[str],
259 expected_remote_clean: List[str],
260 monkeymock: 'MonkeyMock', monkeypatch: pytest.MonkeyPatch,
261 tmp_run_dir: Callable
262 ) -> None:
263 """Test init_clean() with the --rm option.
264
265 Params:
266 rm_dirs: Dirs given by --rm option.
267 expected_clean: The dirs that are expected to be passed to clean().
268 expected_remote_clean: The dirs that are expected to be passed to
269 remote_clean().
270 """
271 id_ = 'dagobah'
272 run_dir: Path = tmp_run_dir(id_)
273 Path(
274 run_dir, WorkflowFiles.Service.DIRNAME, WorkflowFiles.Service.DB
275 ).touch()
276 mock_clean = monkeymock('cylc.flow.clean.clean')
277 mock_remote_clean = monkeymock('cylc.flow.clean.remote_clean')
278 platforms = {'platform_one'}
279 monkeypatch.setattr('cylc.flow.clean.get_platforms_from_db',
280 lambda x: platforms)
281 opts = CleanOptions(rm_dirs=rm_dirs) if rm_dirs else CleanOptions()
282
283 init_clean(id_, opts=opts)
284 mock_clean.assert_called_with(id_, run_dir, expected_clean)
285 mock_remote_clean.assert_called_with(
286 id_, platforms, opts.remote_timeout, expected_remote_clean
287 )
288
289
290 @pytest.mark.parametrize(
291 'id_, symlink_dirs, rm_dirs, expected_deleted, expected_remaining',
292 [
293 pytest.param(
294 'foo/bar',
295 {},
296 None,
297 ['cylc-run/foo'],
298 ['cylc-run'],
299 id="Basic clean"
300 ),
301 pytest.param(
302 'foo/bar/baz',
303 {
304 'log': 'sym-log',
305 'share': 'sym-share',
306 'share/cycle': 'sym-cycle',
307 'work': 'sym-work'
308 },
309 None,
310 ['cylc-run/foo', 'sym-log/cylc-run/foo', 'sym-share/cylc-run/foo',
311 'sym-cycle/cylc-run/foo', 'sym-work/cylc-run/foo'],
312 ['cylc-run', 'sym-log/cylc-run', 'sym-share/cylc-run',
313 'sym-cycle/cylc-run', 'sym-work/cylc-run'],
314 id="Symlink dirs"
315 ),
316 pytest.param(
317 'foo',
318 {
319 'run': 'sym-run',
320 'log': 'sym-log',
321 'share': 'sym-share',
322 'share/cycle': 'sym-cycle',
323 'work': 'sym-work'
324 },
325 None,
326 ['cylc-run/foo', 'sym-run/cylc-run/foo', 'sym-log/cylc-run/foo',
327 'sym-share/cylc-run/foo', 'sym-cycle/cylc-run/foo',
328 'sym-work/cylc-run/foo'],
329 ['cylc-run', 'sym-run/cylc-run', 'sym-log/cylc-run',
330 'sym-share/cylc-run', 'sym-cycle/cylc-run',
331 'sym-work'],
332 id="Symlink dirs including run dir"
333 ),
334 pytest.param(
335 'foo',
336 {},
337 {'log', 'share'},
338 ['cylc-run/foo/log', 'cylc-run/foo/share'],
339 ['cylc-run/foo/work'],
340 id="Targeted clean"
341 ),
342 pytest.param(
343 'foo',
344 {'log': 'sym-log'},
345 {'log'},
346 ['cylc-run/foo/log', 'sym-log/cylc-run/foo'],
347 ['cylc-run/foo/work', 'cylc-run/foo/share/cycle',
348 'sym-log/cylc-run'],
349 id="Targeted clean with symlink dirs"
350 ),
351 pytest.param(
352 'foo',
353 {},
354 {'share/cy*'},
355 ['cylc-run/foo/share/cycle'],
356 ['cylc-run/foo/log', 'cylc-run/foo/work', 'cylc-run/foo/share'],
357 id="Targeted clean with glob"
358 ),
359 pytest.param(
360 'foo',
361 {'log': 'sym-log'},
362 {'w*', 'wo*', 'l*', 'lo*'},
363 ['cylc-run/foo/work', 'cylc-run/foo/log', 'sym-log/cylc-run/foo'],
364 ['cylc-run/foo/share', 'cylc-run/foo/share/cycle'],
365 id="Targeted clean with degenerate glob"
366 ),
367 ]
368 )
369 def test_clean(
370 id_: str,
371 symlink_dirs: Dict[str, str],
372 rm_dirs: Optional[Set[str]],
373 expected_deleted: List[str],
374 expected_remaining: List[str],
375 tmp_path: Path, tmp_run_dir: Callable
376 ) -> None:
377 """Test the clean() function.
378
379 Params:
380 id_: Workflow name.
381 symlink_dirs: As you would find in the global config
382 under [symlink dirs][platform].
383 rm_dirs: As passed to clean().
384 expected_deleted: Dirs (relative paths under tmp_path) that are
385 expected to be cleaned.
386 expected_remaining: Any dirs (relative paths under tmp_path) that are
387 not expected to be cleaned.
388 """
389 # --- Setup ---
390 run_dir: Path = tmp_run_dir(id_)
391
392 if 'run' in symlink_dirs:
393 target = tmp_path / symlink_dirs['run'] / 'cylc-run' / id_
394 target.mkdir(parents=True)
395 shutil.rmtree(run_dir)
396 run_dir.symlink_to(target)
397 symlink_dirs.pop('run')
398 for symlink_name, target_name in symlink_dirs.items():
399 target = tmp_path / target_name / 'cylc-run' / id_ / symlink_name
400 target.mkdir(parents=True)
401 symlink = run_dir / symlink_name
402 symlink.symlink_to(target)
403 for d_name in ('log', 'share', 'share/cycle', 'work'):
404 if d_name not in symlink_dirs:
405 (run_dir / d_name).mkdir()
406
407 for rel_path in [*expected_deleted, *expected_remaining]:
408 assert (tmp_path / rel_path).exists()
409
410 # --- The actual test ---
411 cylc_clean.clean(id_, run_dir, rm_dirs)
412 for rel_path in expected_deleted:
413 assert (tmp_path / rel_path).exists() is False
414 assert (tmp_path / rel_path).is_symlink() is False
415 for rel_path in expected_remaining:
416 assert (tmp_path / rel_path).exists()
417
418
419 def test_clean__broken_symlink_run_dir(
420 tmp_path: Path, tmp_run_dir: Callable
421 ) -> None:
422 """Test clean() successfully remove a run dir that is a broken symlink."""
423 # Setup
424 id_ = 'foo/bar'
425 run_dir: Path = tmp_run_dir(id_)
426 target = tmp_path.joinpath('rabbow/cylc-run', id_)
427 target.mkdir(parents=True)
428 shutil.rmtree(run_dir)
429 run_dir.symlink_to(target)
430 target.rmdir()
431 assert run_dir.parent.exists() is True # cylc-run/foo should exist
432 # Test
433 cylc_clean.clean(id_, run_dir)
434 assert run_dir.parent.exists() is False # cylc-run/foo should be gone
435 assert target.parent.exists() is False # rabbow/cylc-run/foo too
436
437
438 def test_clean__bad_symlink_dir_wrong_type(
439 tmp_path: Path, tmp_run_dir: Callable
440 ) -> None:
441 """Test clean() raises error when a symlink dir actually points to a file
442 instead of a dir"""
443 id_ = 'foo'
444 run_dir: Path = tmp_run_dir(id_)
445 symlink = run_dir.joinpath('log')
446 target = tmp_path.joinpath('sym-log', 'cylc-run', id_, 'meow.txt')
447 target.parent.mkdir(parents=True)
448 target.touch()
449 symlink.symlink_to(target)
450
451 with pytest.raises(WorkflowFilesError) as exc:
452 cylc_clean.clean(id_, run_dir)
453 assert "Invalid symlink at" in str(exc.value)
454 assert symlink.exists() is True
455
456
457 def test_clean__bad_symlink_dir_wrong_form(
458 tmp_path: Path, tmp_run_dir: Callable
459 ) -> None:
460 """Test clean() raises error when a symlink dir points to an
461 unexpected dir"""
462 run_dir: Path = tmp_run_dir('foo')
463 symlink = run_dir.joinpath('log')
464 target = tmp_path.joinpath('sym-log', 'oops', 'log')
465 target.mkdir(parents=True)
466 symlink.symlink_to(target)
467
468 with pytest.raises(WorkflowFilesError) as exc:
469 cylc_clean.clean('foo', run_dir)
470 assert 'should end with "cylc-run/foo/log"' in str(exc.value)
471 assert symlink.exists() is True
472
473
474 @pytest.mark.parametrize('pattern', ['thing/', 'thing/*'])
475 def test_clean__rm_dir_not_file(pattern: str, tmp_run_dir: Callable):
476 """Test clean() does not remove a file when the rm_dir glob pattern would
477 match a dir only."""
478 id_ = 'foo'
479 run_dir: Path = tmp_run_dir(id_)
480 a_file = run_dir.joinpath('thing')
481 a_file.touch()
482 rm_dirs = parse_rm_dirs([pattern])
483
484 cylc_clean.clean(id_, run_dir, rm_dirs)
485 assert a_file.exists()
486
487
488 @pytest.fixture
489 def filetree_for_testing_cylc_clean(tmp_path: Path):
490 """Fixture that creates a filetree from the given dict, and returns which
491 files are expected to be deleted and which aren't.
492
493 See tests/unit/filetree.py
494
495 Args:
496 id_: Workflow name.
497 initial_filetree: The filetree before cleaning.
498 filetree_left_behind: The filetree that is expected to be left behind
499 after cleaning, excluding the 'you-shall-not-pass/' directory,
500 which is always expected to be left behind.
501
502 Returns:
503 run_dir: Workflow run dir.
504 files_to_delete: List of files that are expected to be deleted.
505 files_not_to_delete: List of files that are not expected to be deleted.
506 """
507 def _filetree_for_testing_cylc_clean(
508 id_: str,
509 initial_filetree: Dict[str, Any],
510 filetree_left_behind: Dict[str, Any]
511 ) -> Tuple[Path, List[str], List[str]]:
512 create_filetree(initial_filetree, tmp_path, tmp_path)
513 files_not_to_delete = [
514 os.path.normpath(i) for i in
515 iglob(str(tmp_path / 'you-shall-not-pass/**'), recursive=True)
516 ]
517 files_not_to_delete.extend(
518 get_filetree_as_list(filetree_left_behind, tmp_path)
519 )
520 files_to_delete = list(
521 set(get_filetree_as_list(initial_filetree, tmp_path)).difference(
522 files_not_to_delete
523 )
524 )
525 run_dir = tmp_path / 'cylc-run' / id_
526 return run_dir, files_to_delete, files_not_to_delete
527 return _filetree_for_testing_cylc_clean
528
529
530 @pytest.mark.parametrize(
531 'pattern, initial_filetree, filetree_left_behind',
532 [
533 pytest.param(
534 '**',
535 FILETREE_1,
536 {
537 'cylc-run': {'foo': {}},
538 'sym': {'cylc-run': {'foo': {'bar': {}}}}
539 }
540 ),
541 pytest.param(
542 '*/**',
543 FILETREE_1,
544 {
545 'cylc-run': {'foo': {'bar': {
546 '.service': {'db': None},
547 'flow.cylc': None,
548 'rincewind.txt': Symlink('whatever')
549 }}},
550 'sym': {'cylc-run': {'foo': {'bar': {}}}}
551 }
552 ),
553 pytest.param(
554 '**/*.txt',
555 FILETREE_1,
556 {
557 'cylc-run': {'foo': {'bar': {
558 '.service': {'db': None},
559 'flow.cylc': None,
560 'log': Symlink('whatever'),
561 'mirkwood': Symlink('whatever')
562 }}},
563 'sym': {'cylc-run': {'foo': {'bar': {
564 'log': {
565 'darmok': Symlink('whatever'),
566 'bib': {}
567 }
568 }}}}
569 }
570 )
571 ]
572 )
573 def test__clean_using_glob(
574 pattern: str,
575 initial_filetree: Dict[str, Any],
576 filetree_left_behind: Dict[str, Any],
577 filetree_for_testing_cylc_clean: Callable
578 ) -> None:
579 """Test _clean_using_glob(), particularly that it does not follow and
580 delete symlinks (apart from the standard symlink dirs).
581
582 Params:
583 pattern: The glob pattern to test.
584 initial_filetree: The filetree to test against.
585 files_left_behind: The filetree expected to remain after
586 _clean_using_glob() is called (excluding
587 <tmp_path>/you-shall-not-pass, which is always expected to remain).
588 """
589 # --- Setup ---
590 run_dir: Path
591 files_to_delete: List[str]
592 files_not_to_delete: List[str]
593 run_dir, files_to_delete, files_not_to_delete = (
594 filetree_for_testing_cylc_clean(
595 'foo/bar', initial_filetree, filetree_left_behind)
596 )
597 # --- Test ---
598 _clean_using_glob(run_dir, pattern, symlink_dirs=['log'])
599 for file in files_not_to_delete:
600 assert os.path.exists(file) is True
601 for file in files_to_delete:
602 assert os.path.lexists(file) is False
603
604
605 @pytest.mark.parametrize(
606 'rm_dirs, initial_filetree, filetree_left_behind',
607 [
608 pytest.param(
609 {'**'},
610 FILETREE_1,
611 {
612 'cylc-run': {},
613 'sym': {'cylc-run': {}}
614 },
615 id="filetree1 **"
616 ),
617 pytest.param(
618 {'*/**'},
619 FILETREE_1,
620 {
621 'cylc-run': {'foo': {'bar': {
622 '.service': {'db': None},
623 'flow.cylc': None,
624 'rincewind.txt': Symlink('whatever')
625 }}},
626 'sym': {'cylc-run': {}}
627 },
628 id="filetree1 */**"
629 ),
630 pytest.param(
631 {'**/*.txt'},
632 FILETREE_1,
633 {
634 'cylc-run': {'foo': {'bar': {
635 '.service': {'db': None},
636 'flow.cylc': None,
637 'log': Symlink('whatever'),
638 'mirkwood': Symlink('whatever')
639 }}},
640 'sym': {'cylc-run': {'foo': {'bar': {
641 'log': {
642 'darmok': Symlink('whatever'),
643 'bib': {}
644 }
645 }}}}
646 },
647 id="filetree1 **/*.txt"
648 ),
649 pytest.param(
650 {'**/cycle'},
651 FILETREE_2,
652 {
653 'cylc-run': {'foo': {
654 'bar': Symlink('sym-run/cylc-run/foo/bar')
655 }},
656 'sym-run': {'cylc-run': {'foo': {'bar': {
657 '.service': {'db': None},
658 'flow.cylc': None,
659 'share': Symlink('sym-share/cylc-run/foo/bar/share')
660 }}}},
661 'sym-share': {'cylc-run': {'foo': {'bar': {
662 'share': {}
663 }}}},
664 'sym-cycle': {'cylc-run': {}}
665 },
666 id="filetree2 **/cycle"
667 ),
668 pytest.param(
669 {'share'},
670 FILETREE_2,
671 {
672 'cylc-run': {'foo': {
673 'bar': Symlink('sym-run/cylc-run/foo/bar')
674 }},
675 'sym-run': {'cylc-run': {'foo': {'bar': {
676 '.service': {'db': None},
677 'flow.cylc': None,
678 }}}},
679 'sym-share': {'cylc-run': {}},
680 'sym-cycle': {'cylc-run': {}},
681 },
682 id="filetree2 share"
683 ),
684 pytest.param(
685 {'**'},
686 FILETREE_2,
687 {
688 'cylc-run': {},
689 'sym-run': {'cylc-run': {}},
690 'sym-share': {'cylc-run': {}},
691 'sym-cycle': {'cylc-run': {}}
692 },
693 id="filetree2 **"
694 ),
695 pytest.param(
696 {'*'},
697 FILETREE_2,
698 {
699 'cylc-run': {'foo': {
700 'bar': Symlink('sym-run/cylc-run/foo/bar')
701 }},
702 'sym-run': {'cylc-run': {'foo': {'bar': {
703 '.service': {'db': None},
704 }}}},
705 'sym-share': {'cylc-run': {}},
706 'sym-cycle': {'cylc-run': {}},
707 },
708 id="filetree2 *"
709 ),
710 pytest.param( # Check https://bugs.python.org/issue35201 has no effect
711 {'non-exist/**'},
712 FILETREE_2,
713 FILETREE_2,
714 id="filetree2 non-exist/**"
715 ),
716 pytest.param(
717 {'**'},
718 FILETREE_3,
719 {
720 'cylc-run': {},
721 'sym-run': {'cylc-run': {}},
722 'sym-cycle': {'cylc-run': {}},
723 },
724 id="filetree3 **"
725 ),
726 pytest.param(
727 {'**'},
728 FILETREE_4,
729 {
730 'cylc-run': {},
731 'sym-cycle': {'cylc-run': {}},
732 },
733 id="filetree4 **"
734 )
735 ],
736 )
737 def test_clean__targeted(
738 rm_dirs: Set[str],
739 initial_filetree: Dict[str, Any],
740 filetree_left_behind: Dict[str, Any],
741 caplog: pytest.LogCaptureFixture, tmp_run_dir: Callable,
742 filetree_for_testing_cylc_clean: Callable
743 ) -> None:
744 """Test clean(), particularly that it does not follow and delete symlinks
745 (apart from the standard symlink dirs).
746
747 This is similar to test__clean_using_glob(), but the filetree expected to
748 remain after cleaning is different due to the tidy up of empty dirs.
749
750 Params:
751 rm_dirs: The glob patterns to test.
752 initial_filetree: The filetree to test against.
753 files_left_behind: The filetree expected to remain after
754 clean() is called (excluding <tmp_path>/you-shall-not-pass,
755 which is always expected to remain).
756 """
757 # --- Setup ---
758 caplog.set_level(logging.DEBUG, CYLC_LOG)
759 id_ = 'foo/bar'
760 run_dir: Path
761 files_to_delete: List[str]
762 files_not_to_delete: List[str]
763 run_dir, files_to_delete, files_not_to_delete = (
764 filetree_for_testing_cylc_clean(
765 id_, initial_filetree, filetree_left_behind)
766 )
767 # --- Test ---
768 cylc_clean.clean(id_, run_dir, rm_dirs)
769 for file in files_not_to_delete:
770 assert os.path.exists(file) is True
771 for file in files_to_delete:
772 assert os.path.lexists(file) is False
773
774
775 @pytest.mark.parametrize(
776 'rm_dirs',
777 [
778 [".."],
779 ["foo:.."],
780 ["foo/../../meow"]
781 ]
782 )
783 def test_init_clean__targeted_bad(
784 rm_dirs: List[str],
785 tmp_run_dir: Callable,
786 monkeymock: 'MonkeyMock'
787 ):
788 """Test init_clean() fails when abusing --rm option."""
789 tmp_run_dir('chalmers')
790 mock_clean = monkeymock('cylc.flow.clean.clean')
791 mock_remote_clean = monkeymock('cylc.flow.clean.remote_clean')
792 with pytest.raises(InputError) as exc_info:
793 init_clean('chalmers', opts=CleanOptions(rm_dirs=rm_dirs))
794 assert "cannot take paths that point to the run directory or above" in str(
795 exc_info.value
796 )
797 mock_clean.assert_not_called()
798 mock_remote_clean.assert_not_called()
799
800
801 PLATFORMS = {
802 'enterprise': {
803 'hosts': ['kirk', 'picard'],
804 'install target': 'picard',
805 'name': 'enterprise'
806 },
807 'voyager': {
808 'hosts': ['janeway'],
809 'install target': 'janeway',
810 'name': 'voyager'
811 },
812 'stargazer': {
813 'hosts': ['picard'],
814 'install target': 'picard',
815 'name': 'stargazer'
816 },
817 'exeter': {
818 'hosts': ['localhost'],
819 'install target': 'localhost',
820 'name': 'exeter'
821 }
822 }
823
824
825 @pytest.mark.parametrize(
826 ('platform_names', 'failed_platforms', 'expected_platforms',
827 'exc_expected', 'expected_err_msgs'),
828 [
829 pytest.param(
830 ['exeter'], None, None, False, [],
831 id="Only localhost install target - no remote clean"
832 ),
833 pytest.param(
834 ['exeter', 'enterprise'], None, ['enterprise'], False, [],
835 id="Localhost and remote install target"
836 ),
837 pytest.param(
838 ['enterprise', 'stargazer', 'voyager'],
839 None,
840 ['enterprise', 'voyager'],
841 False,
842 [],
843 id="Only remote install targets"
844 ),
845 pytest.param(
846 ['enterprise', 'stargazer', 'voyager'],
847 {'enterprise': 255},
848 ['enterprise', 'stargazer', 'voyager'],
849 False,
850 [],
851 id="Install target with 1 failed, 1 successful platform"
852 ),
853 pytest.param(
854 ['enterprise', 'stargazer', 'voyager'],
855 {'enterprise': 255, 'stargazer': 255},
856 ['enterprise', 'stargazer', 'voyager'],
857 True,
858 ["could not clean on these install target(s)", "[picard]"],
859 id="Install target with all failed platforms"
860 ),
861 pytest.param(
862 ['enterprise', 'voyager'],
863 {'enterprise': 255, 'voyager': 255},
864 ['enterprise', 'voyager'],
865 True,
866 ["could not clean on these install target(s)",
867 "[picard]", "[janeway]"],
868 id="All install targets have all failed platforms"
869 ),
870 pytest.param(
871 ['enterprise', 'stargazer'],
872 {'enterprise': 1},
873 ['enterprise'],
874 True,
875 ["could not clean on these install target(s)", "[picard]"],
876 id=("Remote clean cmd fails on a platform for non-SSH reason - "
877 "does not retry")
878 ),
879 ]
880 )
881 def test_remote_clean(
882 platform_names: list[str],
883 failed_platforms: dict[str, int] | None,
884 expected_platforms: list[str] | None,
885 exc_expected: bool,
886 expected_err_msgs: list[str],
887 monkeymock: 'MonkeyMock', monkeypatch: pytest.MonkeyPatch,
888 caplog: pytest.LogCaptureFixture, log_filter: Callable
889 ) -> None:
890 """Test remote_clean() logic.
891
892 Params:
893 platform_names: These platforms will be considered to exist.
894 failed_platforms: If specified, any platforms that clean will
895 artificially fail on in this test case. The key is the platform
896 name, the value is the remote clean cmd return code.
897 expected_platforms: If specified, all the platforms that the
898 remote clean cmd is expected to run on.
899 exc_expected: If a CylcError is expected to be raised.
900 expected_err_msgs: List of error messages expected to be in the log.
901 """
902 # ----- Setup -----
903 caplog.set_level(logging.DEBUG, CYLC_LOG)
904 monkeypatch.setattr(
905 'cylc.flow.clean.platform_from_name', lambda name: PLATFORMS[name]
906 )
907 # Remove randomness:
908 monkeymock('cylc.flow.clean.shuffle')
909
910 def mocked_remote_clean_cmd_side_effect(id_, platform, timeout, rm_dirs):
911 proc_ret_code = 0
912 if failed_platforms and platform['name'] in failed_platforms:
913 proc_ret_code = failed_platforms[platform['name']]
914 return mock.Mock(
915 poll=lambda: proc_ret_code,
916 communicate=lambda: ("Mocked stdout", "Mocked stderr"),
917 args=[]
918 )
919
920 mocked_remote_clean_cmd = monkeymock(
921 'cylc.flow.clean._remote_clean_cmd',
922 spec=_remote_clean_cmd,
923 side_effect=mocked_remote_clean_cmd_side_effect,
924 )
925 rm_dirs = ["whatever"]
926 # ----- Test -----
927 id_ = 'foo'
928 if exc_expected:
929 with pytest.raises(CylcError) as exc:
930 cylc_clean.remote_clean(
931 id_, platform_names, timeout='irrelevant', rm_dirs=rm_dirs
932 )
933 assert "Remote clean failed" in (exc_msg := str(exc.value))
934 for msg in expected_err_msgs:
935 assert msg in exc_msg
936 else:
937 cylc_clean.remote_clean(
938 id_, platform_names, timeout='irrelevant', rm_dirs=rm_dirs
939 )
940 for msg in expected_err_msgs:
941 assert log_filter(logging.ERROR, msg)
942 if expected_platforms:
943 for p_name in expected_platforms:
944 mocked_remote_clean_cmd.assert_any_call(
945 id_, PLATFORMS[p_name], rm_dirs, 'irrelevant'
946 )
947 else:
948 mocked_remote_clean_cmd.assert_not_called()
949
950
951 def test_remote_clean__timeout(
952 monkeymock: 'MonkeyMock',
953 monkeypatch: pytest.MonkeyPatch,
954 caplog: pytest.LogCaptureFixture,
955 ):
956 """Test remote_clean() gives a sensible error message for return code 124.
957 """
958 caplog.set_level(logging.ERROR, CYLC_LOG)
959 monkeymock(
960 'cylc.flow.clean._remote_clean_cmd',
961 spec=_remote_clean_cmd,
962 return_value=mock.Mock(
963 spec=Popen, poll=lambda: 124, communicate=lambda: ('', '')
964 )
965 )
966 monkeypatch.setattr(
967 'cylc.flow.clean.platform_from_name', lambda name: PLATFORMS[name]
968 )
969
970 with pytest.raises(CylcError) as e:
971 cylc_clean.remote_clean(
972 'blah', platform_names=['stargazer'], timeout='blah'
973 )
974 assert "cylc clean timed out" in str(e.value)
975 # No need to log the remote clean cmd etc. for timeout
976 assert "ssh" not in caplog.text.lower()
977 assert "stderr" not in caplog.text.lower()
978
979
980 @pytest.mark.parametrize(
981 'rm_dirs, expected_args',
982 [
983 (None, []),
984 (['holodeck', 'ten_forward'],
985 ['--rm', 'holodeck', '--rm', 'ten_forward'])
986 ]
987 )
988 def test_remote_clean_cmd(
989 rm_dirs: Optional[List[str]],
990 expected_args: List[str],
991 monkeymock: 'MonkeyMock'
992 ) -> None:
993 """Test _remote_clean_cmd()
994
995 Params:
996 rm_dirs: Argument passed to _remote_clean_cmd().
997 expected_args: Expected CLI arguments of the cylc clean command that
998 gets constructed.
999 """
1000 id_ = 'jean/luc/picard'
1001 platform = {
1002 'name': 'enterprise',
1003 'install target': 'mars',
1004 'hosts': ['Trill'],
1005 'selection': {'method': 'definition order'}
1006 }
1007 mock_construct_ssh_cmd = monkeymock(
1008 'cylc.flow.clean.construct_ssh_cmd', return_value=['blah'])
1009 monkeymock('cylc.flow.clean.Popen')
1010
1011 cylc_clean._remote_clean_cmd(id_, platform, rm_dirs, timeout='dunno')
1012 args, _kwargs = mock_construct_ssh_cmd.call_args
1013 constructed_cmd = args[0]
1014 assert constructed_cmd == [
1015 'clean', '--local-only', '--no-scan', id_, *expected_args
1016 ]
1017
1018
1019 def test_clean_top_level(tmp_run_dir: Callable):
1020 """Test that cleaning last remaining run dir inside a workflow dir removes
1021 the top level dir if it's empty (excluding _cylc-install)."""
1022 # Setup
1023 id_ = 'blue/planet/run1'
1024 run_dir: Path = tmp_run_dir(id_, installed=True, named=True)
1025 cylc_install_dir = run_dir.parent / WorkflowFiles.Install.DIRNAME
1026 assert cylc_install_dir.is_dir()
1027 runN_symlink = run_dir.parent / WorkflowFiles.RUN_N
1028 assert runN_symlink.exists()
1029 # Test
1030 clean(id_, run_dir)
1031 assert not run_dir.parent.parent.exists()
1032 # Now check that if the top level dir is not empty, it doesn't get removed
1033 run_dir: Path = tmp_run_dir(id_, installed=True, named=True)
1034 jellyfish_file = (run_dir.parent / 'jellyfish.txt')
1035 jellyfish_file.touch()
1036 clean(id_, run_dir)
1037 assert cylc_install_dir.is_dir()
1038 assert jellyfish_file.exists()
1039
1040
1041 @pytest.mark.parametrize(
1042 'pattern, filetree, expected_matches',
1043 [
1044 pytest.param(
1045 '**',
1046 FILETREE_1,
1047 ['cylc-run/foo/bar',
1048 'cylc-run/foo/bar/log'],
1049 id="filetree1 **"
1050 ),
1051 pytest.param(
1052 '*',
1053 FILETREE_1,
1054 ['cylc-run/foo/bar/flow.cylc',
1055 'cylc-run/foo/bar/log',
1056 'cylc-run/foo/bar/mirkwood',
1057 'cylc-run/foo/bar/rincewind.txt'],
1058 id="filetree1 *"
1059 ),
1060 pytest.param(
1061 '**/*.txt',
1062 FILETREE_1,
1063 ['cylc-run/foo/bar/log/bib/fortuna.txt',
1064 'cylc-run/foo/bar/log/temba.txt',
1065 'cylc-run/foo/bar/rincewind.txt'],
1066 id="filetree1 **/*.txt"
1067 ),
1068 pytest.param(
1069 '**',
1070 FILETREE_2,
1071 ['cylc-run/foo/bar',
1072 'cylc-run/foo/bar/share',
1073 'cylc-run/foo/bar/share/cycle'],
1074 id="filetree2 **"
1075 ),
1076 pytest.param(
1077 'share',
1078 FILETREE_2,
1079 ['cylc-run/foo/bar/share'],
1080 id="filetree2 share"
1081 ),
1082 pytest.param(
1083 '**',
1084 FILETREE_3,
1085 ['cylc-run/foo/bar',
1086 'cylc-run/foo/bar/share/cycle'],
1087 id="filetree3 **"
1088 ),
1089 pytest.param(
1090 '**/s*',
1091 FILETREE_3,
1092 ['cylc-run/foo/bar/share',
1093 'cylc-run/foo/bar/share/cycle/sokath.txt'],
1094 id="filetree3 **/s*"
1095 ),
1096 pytest.param(
1097 '**',
1098 FILETREE_4,
1099 ['cylc-run/foo/bar',
1100 'cylc-run/foo/bar/share/cycle'],
1101 id="filetree4 **"
1102 ),
1103 ]
1104 )
1105 def test_glob_in_run_dir(
1106 pattern: str,
1107 filetree: Dict[str, Any],
1108 expected_matches: List[str],
1109 tmp_path: Path, tmp_run_dir: Callable
1110 ) -> None:
1111 """Test that glob_in_run_dir() returns the minimal set of results with
1112 no redundant paths.
1113 """
1114 # Setup
1115 cylc_run_dir: Path = tmp_run_dir()
1116 id_ = 'foo/bar'
1117 run_dir = cylc_run_dir / id_
1118 create_filetree(filetree, tmp_path, tmp_path)
1119 symlink_dirs = [run_dir / i for i in get_symlink_dirs(id_, run_dir)]
1120 expected = [tmp_path / i for i in expected_matches]
1121 # Test
1122 assert glob_in_run_dir(run_dir, pattern, symlink_dirs) == expected