Debian Codegraph @

tests/unit/test_id_cli.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 import os
19 from pathlib import Path
20 import pytest
21 from shutil import copytree, rmtree
22
23 from cylc.flow import CYLC_LOG
24 from cylc.flow.async_util import pipe
25 from cylc.flow.exceptions import InputError, WorkflowFilesError
26 from cylc.flow.id import detokenise, tokenise, Tokens
27 from cylc.flow.id_cli import (
28 _expand_workflow_tokens,
29 _parse_src_path,
30 _validate_constraint,
31 _validate_workflow_ids,
32 _validate_number,
33 cli_tokenise,
34 parse_ids_async,
35 )
36 from cylc.flow.pathutil import get_cylc_run_dir
37 from cylc.flow.workflow_files import WorkflowFiles
38
39
40 @pytest.fixture
41 def mock_exists(monkeypatch: pytest.MonkeyPatch):
42 monkeypatch.setattr('pathlib.Path.exists', lambda *a, **k: True)
43
44
45 @pytest.fixture(scope='module')
46 def abc_src_dir(tmp_path_factory):
47 """Src dir containing three workflows, a, b & c."""
48 cwd_before = Path.cwd()
49 tmp_path = tmp_path_factory.getbasetemp()
50 os.chdir(tmp_path)
51 for name in ('a', 'b', 'c'):
52 Path(tmp_path, name).mkdir()
53 Path(tmp_path, name, WorkflowFiles.FLOW_FILE).touch()
54 yield tmp_path
55 os.chdir(cwd_before)
56
57
58 @pytest.mark.parametrize(
59 'ids_in,ids_out',
60 [
61 (('a//',), ['a']),
62 (('a//', 'a//'), ['a']),
63 (('a//', 'b//'), ['a', 'b']),
64 ]
65 )
66 async def test_parse_ids_workflows(ids_in, ids_out, mock_exists):
67 """It should parse workflows & tasks."""
68 workflows, _ = await parse_ids_async(*ids_in, constraint='workflows')
69 assert list(workflows) == ids_out
70 assert list(workflows.values()) == [[] for _ in workflows]
71
72
73 @pytest.mark.parametrize(
74 'ids_in,ids_out',
75 [
76 (('./a',), ['a']),
77 ]
78 )
79 async def test_parse_ids_workflows_src(ids_in, ids_out, abc_src_dir):
80 """It should parse src workflows."""
81 workflows, _ = await parse_ids_async(
82 *ids_in,
83 src=True,
84 constraint='workflows',
85 )
86 assert list(workflows) == ids_out
87 assert list(workflows.values()) == [[] for _ in workflows]
88
89
90 @pytest.mark.parametrize(
91 'ids_in,ids_out',
92 [
93 (
94 ('a//i',),
95 {'a': ['//i']},
96 ),
97 (
98 ('a//i', 'a//j'),
99 {'a': ['//i', '//j']},
100 ),
101 (
102 ('a//i', 'b//i'),
103 {'a': ['//i'], 'b': ['//i']},
104 ),
105 (
106 ('a//', '//i', 'b//', '//i'),
107 {'a': ['//i'], 'b': ['//i']},
108 ),
109 ]
110 )
111 async def test_parse_ids_tasks(mock_exists, ids_in, ids_out):
112 """It should parse workflow tasks in two formats."""
113 workflows, _ = await parse_ids_async(*ids_in, constraint='tasks')
114 assert {
115 workflow_id: [detokenise(tokens) for tokens in tokens_list]
116 for workflow_id, tokens_list in workflows.items()
117 } == ids_out
118
119
120 @pytest.mark.parametrize(
121 'ids_in,ids_out',
122 [
123 (
124 ('./a', '//i'),
125 {'a': ['//i']}
126 ),
127 (
128 ('./a', '//i', '//j', '//k'),
129 {'a': ['//i', '//j', '//k']}
130 ),
131 ]
132 )
133 async def test_parse_ids_tasks_src(mock_exists, ids_in, ids_out, abc_src_dir):
134 """It should parse workflow tasks for src workflows."""
135 workflows, _ = await parse_ids_async(
136 *ids_in, constraint='tasks', src=True)
137 assert {
138 workflow_id: [detokenise(tokens) for tokens in tokens_list]
139 for workflow_id, tokens_list in workflows.items()
140 } == ids_out
141
142
143 @pytest.mark.parametrize(
144 'ids_in,ids_out',
145 [
146 (('a//',), {'a': []}),
147 (
148 ('a//', 'b//', 'c//'),
149 {'a': [], 'b': [], 'c': []}
150 ),
151 (('a//i',), {'a': ['//i']}),
152 (('a//', '//i'), {'a': ['//i']}),
153 (
154 ('a//', '//i', '//j', '//k'),
155 {'a': ['//i', '//j', '//k']},
156 ),
157 (('a//', '//i', 'b//'), {'a': ['//i'], 'b': []}),
158 ]
159 )
160 async def test_parse_ids_mixed(ids_in, ids_out, mock_exists):
161 """It should parse mixed workflows & tasks."""
162 workflows, _ = await parse_ids_async(*ids_in, constraint='mixed')
163 assert {
164 workflow_id: [detokenise(tokens) for tokens in tokens_list]
165 for workflow_id, tokens_list in workflows.items()
166 } == ids_out
167
168
169 @pytest.mark.parametrize(
170 'ids_in,ids_out',
171 [
172 (('./a',), {'a': []}),
173 (('./a', '//i'), {'a': ['//i']}),
174 (('./a', '//i', '//j', '//k'), {'a': ['//i', '//j', '//k']}),
175 ]
176 )
177 async def test_parse_ids_mixed_src(ids_in, ids_out, abc_src_dir, mock_exists):
178 """It should parse mixed workflows & tasks from src workflows."""
179
180 workflows, _ = await parse_ids_async(
181 *ids_in, constraint='mixed', src=True
182 )
183 assert {
184 workflow_id: [detokenise(tokens) for tokens in tokens_list]
185 for workflow_id, tokens_list in workflows.items()
186 } == ids_out
187
188
189 @pytest.mark.parametrize(
190 'ids_in,errors',
191 [
192 (('a//',), False),
193 (('a//', 'b//'), False),
194 (('a//', 'b//', 'c//'), True),
195 ]
196 )
197 async def test_parse_ids_max_workflows(ids_in, errors, mock_exists):
198 """It should validate input against the max_workflows constraint."""
199 try:
200 await parse_ids_async(
201 *ids_in, constraint='workflows', max_workflows=2)
202 except InputError:
203 if not errors:
204 raise
205 else:
206 if errors:
207 raise Exception('Should have raised InputError')
208
209
210 @pytest.mark.parametrize(
211 'ids_in,errors',
212 [
213 (('a//', '//i'), False),
214 (('a//', '//i', '//j'), False),
215 (('a//', '//i', '//j', '//k'), True),
216 ]
217 )
218 async def test_parse_ids_max_tasks(ids_in, errors, mock_exists):
219 """It should validate input against the max_tasks constraint."""
220 try:
221 await parse_ids_async(*ids_in, constraint='tasks', max_tasks=2)
222 except InputError:
223 if not errors:
224 raise
225 else:
226 if errors:
227 raise Exception('Should have raised InputError')
228
229
230 async def test_parse_ids_infer_run_name(tmp_run_dir):
231 """It should infer the run name for auto-numbered installations."""
232 # it doesn't do anything for a named run
233 tmp_run_dir('foo/bar', named=True, installed=True)
234 workflows, *_ = await parse_ids_async('foo//', constraint='workflows')
235 assert list(workflows) == ['foo']
236
237 # it correctly identifies the latest run
238 tmp_run_dir('bar/run1')
239 workflows, *_ = await parse_ids_async('bar//', constraint='workflows')
240 assert list(workflows) == ['bar/run1']
241 tmp_run_dir('bar/run2')
242 workflows, *_ = await parse_ids_async('bar//', constraint='workflows')
243 assert list(workflows) == ['bar/run2']
244
245 # it leaves the ID alone if infer_latest_runs = False
246 workflows, *_ = await parse_ids_async(
247 'bar//',
248 constraint='workflows',
249 infer_latest_runs=False,
250 )
251 assert list(workflows) == ['bar']
252
253 # Now test we can see workflows in alternate cylc-run directories
254 # e.g. for `cylc workflow-state` or xtriggers targetting another user.
255 cylc_run_dir = get_cylc_run_dir()
256 alt_cylc_run_dir = cylc_run_dir + "_alt"
257
258 # copy the cylc-run dir to alt location and delete the original.
259 copytree(cylc_run_dir, alt_cylc_run_dir, symlinks=True)
260 rmtree(cylc_run_dir)
261
262 # It can no longer parse IDs in the original cylc-run location.
263 with pytest.raises(InputError):
264 workflows, *_ = await parse_ids_async(
265 'bar//',
266 constraint='workflows',
267 infer_latest_runs=True,
268 )
269
270 # But it can if we specify the alternate location.
271 workflows, *_ = await parse_ids_async(
272 'bar//',
273 constraint='workflows',
274 infer_latest_runs=True,
275 alt_run_dir=alt_cylc_run_dir
276 )
277 assert list(workflows) == ['bar/run2']
278
279
280 @pytest.fixture
281 def patch_expand_workflow_tokens(monkeypatch):
282 """Define the output of scan events."""
283
284 def _patch_expand_workflow_tokens(_ids):
285
286 async def _expand_workflow_tokens_impl(tokens, match_active=True):
287 for id_ in _ids:
288 yield tokens.duplicate(workflow=id_)
289
290 monkeypatch.setattr(
291 'cylc.flow.id_cli._expand_workflow_tokens_impl',
292 _expand_workflow_tokens_impl,
293 )
294
295 _patch_expand_workflow_tokens(['xxx'])
296 return _patch_expand_workflow_tokens
297
298
299 @pytest.mark.parametrize(
300 'ids_in,ids_out,multi_mode',
301 [
302 # multi mode should be True if multiple workflows are defined
303 (['a//'], ['a'], False),
304 (['a//', 'b//'], ['a', 'b'], True),
305 # or if pattern matching is used, irrespective of the number of matches
306 (['*//'], ['xxx'], True),
307 ]
308 )
309 async def test_parse_ids_multi_mode(
310 patch_expand_workflow_tokens,
311 ids_in,
312 ids_out,
313 multi_mode,
314 mock_exists
315 ):
316 """It should glob for workflows.
317
318 Note:
319 More advanced tests for this in the integration tests.
320
321 """
322
323 workflows, _multi_mode = await parse_ids_async(
324 *ids_in,
325 constraint='workflows',
326 match_workflows=True,
327 )
328 assert list(workflows) == ids_out
329 assert _multi_mode == multi_mode
330
331
332 @pytest.fixture
333 def src_dir(tmp_path):
334 """A src dir containing a workflow called "a"."""
335 cwd_before = Path.cwd()
336 src_dir = (tmp_path / 'a')
337 src_dir.mkdir()
338 src_file = src_dir / 'flow.cylc'
339 src_file.touch()
340
341 other_dir = (tmp_path / 'blargh')
342 other_dir.mkdir()
343 other_file = other_dir / 'nugget'
344 other_file.touch()
345
346 os.chdir(tmp_path)
347 yield src_dir
348 os.chdir(cwd_before)
349
350
351 def test_parse_src_path(src_dir, monkeypatch):
352 """It should locate src dirs."""
353 # valid absolute path
354 workflow_id, src_path, src_file_path = _parse_src_path(
355 str(src_dir.resolve())
356 )
357 assert workflow_id == 'a'
358 assert src_path == src_dir
359 assert src_file_path == src_dir / 'flow.cylc'
360
361 # broken absolute path
362 with pytest.raises(InputError):
363 workflow_id, src_path, src_file_path = _parse_src_path(
364 str(src_dir.resolve()) + 'xyz'
365 )
366
367 # valid ./relative path
368 workflow_id, src_path, src_file_path = _parse_src_path('./a')
369 assert workflow_id == 'a'
370 assert src_path == src_dir
371 assert src_file_path == src_dir / 'flow.cylc'
372
373 # broken relative path
374 with pytest.raises(InputError):
375 _parse_src_path('./xxx')
376
377 # relative '.' dir (invalid)
378 with pytest.raises(WorkflowFilesError) as exc_ctx:
379 workflow_id, src_path, src_file_path = _parse_src_path('.')
380 assert 'No flow.cylc or suite.rc in' in str(exc_ctx.value)
381
382 # relative 'invalid/<flow-file>' (invalid)
383 with pytest.raises(InputError) as exc_ctx:
384 _parse_src_path('xxx/flow.cylc')
385 assert 'Not a valid workflow ID or source directory' in str(exc_ctx.value)
386
387 # Might be a workflow ID
388 res = _parse_src_path('the/quick/brown/fox')
389 assert res is None
390
391 # Might be a workflow ID, even though there's a matching relative path
392 res = _parse_src_path('a')
393 assert res is None
394
395 # Not a src directory (dir)
396 with pytest.raises(WorkflowFilesError) as exc_ctx:
397 _parse_src_path('./blargh')
398 assert 'No flow.cylc or suite.rc in' in str(exc_ctx.value)
399
400 # Not a src directory (file)
401 with pytest.raises(InputError) as exc_ctx:
402 _parse_src_path('./blargh/nugget')
403 assert 'Path is not a source directory' in str(exc_ctx.value)
404
405 # move into the src dir
406 monkeypatch.chdir(src_dir)
407
408 # relative '.' dir (valid)
409 workflow_id, src_path, src_file_path = _parse_src_path('.')
410 assert workflow_id == 'a'
411 assert src_path == src_dir
412 assert src_file_path == src_dir / 'flow.cylc'
413
414 # relative './<flow-file>' (invalid)
415 with pytest.raises(InputError) as exc_ctx:
416 _parse_src_path('./flow.cylc')
417 assert 'Not a valid workflow ID or source directory' in str(exc_ctx.value)
418
419 # suite.rc & flow.cylc both present:
420 (src_dir / 'suite.rc').touch()
421 with pytest.raises(WorkflowFilesError) as exc_ctx:
422 _parse_src_path(str(src_dir))
423 assert 'Both flow.cylc and suite.rc files' in str(exc_ctx.value)
424
425
426 async def test_parse_ids_src_path(src_dir):
427 workflows, src_path = await parse_ids_async(
428 './a',
429 src=True,
430 constraint='workflows',
431 )
432 assert workflows == {'a': []}
433
434
435 @pytest.mark.parametrize(
436 'ids_in,error_msg',
437 [
438 (
439 ['/home/me/whatever'],
440 'Invalid ID: /home/me/whatever',
441 ),
442 (
443 ['foo/..'],
444 'cannot be a path that points to the cylc-run directory or above',
445 ),
446 (
447 ['~alice/foo'],
448 "Operating on other users' workflows is not supported",
449 ),
450 ]
451 )
452 async def test_parse_ids_invalid_ids(
453 ids_in, error_msg, monkeypatch: pytest.MonkeyPatch
454 ):
455 """It should error for invalid IDs."""
456 monkeypatch.setattr('cylc.flow.id_cli.get_user', lambda: 'rincewind')
457 with pytest.raises(Exception) as exc_ctx:
458 await parse_ids_async(
459 *ids_in,
460 constraint='workflows',
461 )
462 assert error_msg in str(exc_ctx.value)
463
464
465 async def test_parse_ids_current_user(
466 monkeypatch: pytest.MonkeyPatch, mock_exists
467 ):
468 """It should work if the user in the ID is the current user."""
469 monkeypatch.setattr('cylc.flow.id_cli.get_user', lambda: 'rincewind')
470 await parse_ids_async('~rincewind/luggage', constraint='workflows')
471
472
473 async def test_parse_ids_file(tmp_run_dir):
474 """It should reject IDs that are paths to files."""
475 tmp_path = tmp_run_dir('x')
476 tmp_file = tmp_path / 'tmpfile'
477 tmp_file.touch()
478 (tmp_path / WorkflowFiles.FLOW_FILE).touch()
479 # using a directory should work
480 await parse_ids_async(
481 str(tmp_path.relative_to(get_cylc_run_dir())),
482 constraint='workflows',
483 )
484 with pytest.raises(Exception) as exc_ctx:
485 # using a file should not
486 await parse_ids_async(
487 str(tmp_file.relative_to(get_cylc_run_dir())),
488 constraint='workflows',
489 )
490 assert 'Workflow ID cannot be a file' in str(exc_ctx.value)
491
492
493 async def test_parse_ids_constraint(mock_exists):
494 """It should validate input against the constraint."""
495 # constraint: workflows
496 await parse_ids_async('a//', constraint='workflows')
497 with pytest.raises(InputError):
498 await parse_ids_async('a//b', constraint='workflows')
499 # constraint: tasks
500 await parse_ids_async('a//b', constraint='tasks')
501 with pytest.raises(InputError):
502 await parse_ids_async('a//', constraint='tasks')
503 # constraint: mixed
504 await parse_ids_async('a//', constraint='mixed')
505 await parse_ids_async('a//b', constraint='mixed')
506 # constraint: invalid
507 with pytest.raises(ValueError):
508 await parse_ids_async('foo', constraint='bar')
509
510
511 async def test_parse_ids_src_run(abc_src_dir, tmp_run_dir):
512 """It should locate the flow file when src=True."""
513 # locate flow file for a src workflow
514 workflows, flow_file_path = await parse_ids_async(
515 './a',
516 src=True,
517 constraint='workflows',
518 )
519 assert list(workflows) == ['a']
520 assert flow_file_path == abc_src_dir / 'a' / WorkflowFiles.FLOW_FILE
521
522 # locate flow file for a run workflow
523 run_dir = tmp_run_dir('b')
524 workflows, flow_file_path = await parse_ids_async(
525 'b',
526 src=True,
527 constraint='workflows',
528 )
529 assert list(workflows) == ['b']
530 assert flow_file_path == run_dir / WorkflowFiles.FLOW_FILE
531
532
533 def test_validate_constraint():
534 """It should validate tokens against the constraint."""
535 # constraint=workflows
536 _validate_constraint(Tokens(workflow='a'), constraint='workflows')
537 with pytest.raises(InputError):
538 _validate_constraint(Tokens(cycle='a'), constraint='workflows')
539 with pytest.raises(InputError):
540 _validate_constraint(Tokens(), constraint='workflows')
541 # constraint=tasks
542 _validate_constraint(Tokens(cycle='a'), constraint='tasks')
543 with pytest.raises(InputError):
544 _validate_constraint(Tokens(workflow='a'), constraint='tasks')
545 with pytest.raises(InputError):
546 _validate_constraint(Tokens(), constraint='tasks')
547 # constraint=mixed
548 _validate_constraint(Tokens(workflow='a'), constraint='mixed')
549 _validate_constraint(Tokens(cycle='a'), constraint='mixed')
550 with pytest.raises(InputError):
551 _validate_constraint(Tokens(), constraint='mixed')
552
553
554 def test_validate_workflow_ids_basic(tmp_run_dir):
555 _validate_workflow_ids(Tokens('workflow'), src_path='')
556 with pytest.raises(InputError):
557 _validate_workflow_ids(Tokens('~alice/workflow'), src_path='')
558 run_dir = tmp_run_dir('b')
559 with pytest.raises(InputError):
560 _validate_workflow_ids(
561 Tokens('workflow'),
562 src_path=run_dir / 'flow.cylc',
563 )
564
565
566 def test_validate_workflow_ids_warning(caplog):
567 """It should warn when the run number is provided as a cycle point."""
568 caplog.set_level(logging.WARN, CYLC_LOG)
569 _validate_workflow_ids(Tokens('workflow/run1//cycle/task'), src_path='')
570 assert caplog.messages == []
571
572 _validate_workflow_ids(Tokens('workflow//run1'), src_path='')
573 assert caplog.messages == ['Did you mean: workflow/run1']
574
575 caplog.clear()
576 _validate_workflow_ids(Tokens('workflow//run1/cycle/task'), src_path='')
577 assert caplog.messages == ['Did you mean: workflow/run1//cycle/task']
578
579
580 def test_validate_number():
581 _validate_number(Tokens('a'), max_workflows=1)
582 with pytest.raises(InputError):
583 _validate_number(Tokens('a'), Tokens('b'), max_workflows=1)
584 t1 = Tokens(cycle='1')
585 t2 = Tokens(cycle='2')
586 _validate_number(t1, max_tasks=1)
587 with pytest.raises(InputError):
588 _validate_number(t1, t2, max_tasks=1)
589 _validate_number(t1, max_tasks=1)
590 _validate_number(Tokens('a//1'), Tokens('a//2'), max_workflows=1)
591 _validate_number(
592 Tokens('a'), Tokens('//2'), Tokens('//3'), max_workflows=1
593 )
594 with pytest.raises(InputError):
595 _validate_number(Tokens('a//1'), Tokens('b//1'), max_workflows=1)
596 _validate_number(Tokens('a//1'), Tokens('b//1'), max_workflows=2)
597
598
599 @pytest.fixture
600 def no_scan(monkeypatch):
601 """Disable the filesystem part of scan."""
602
603 @pipe
604 async def _scan():
605 # something that looks like scan but doesn't do anything
606 yield
607
608 monkeypatch.setattr('cylc.flow.network.scan.scan', _scan)
609
610
611 async def test_expand_workflow_tokens_impl_selector(no_scan):
612 """It should reject filters it can't handle."""
613 tokens = tokenise('~user/*')
614 await _expand_workflow_tokens([tokens])
615 tokens = tokens.duplicate(workflow_sel='stopped')
616 with pytest.raises(InputError):
617 await _expand_workflow_tokens([tokens])
618
619
620 @pytest.mark.parametrize('identifier, expected', [
621 (
622 '//2024-01-01T00:fail/a',
623 {'cycle': '2024-01-01T00', 'cycle_sel': 'fail', 'task': 'a'}
624 ),
625 (
626 '//2024-01-01T00:00Z/a',
627 {'cycle': '2024-01-01T00:00Z', 'task': 'a'}
628 ),
629 (
630 '//2024-01-01T00:00Z:fail/a',
631 {'cycle': '2024-01-01T00:00Z', 'cycle_sel': 'fail', 'task': 'a'}
632 ),
633 (
634 '//2024-01-01T00:00:00+05:30/a',
635 {'cycle': '2024-01-01T00:00:00+05:30', 'task': 'a'}
636 ),
637 (
638 '//2024-01-01T00:00:00+05:30:f/a',
639 {'cycle': '2024-01-01T00:00:00+05:30', 'cycle_sel': 'f', 'task': 'a'}
640 ),
641 (
642 # Nonsensical example, but whatever...
643 '//2024-01-01T00:00Z:00Z/a',
644 {'cycle': '2024-01-01T00:00Z', 'cycle_sel': '00Z', 'task': 'a'}
645 )
646 ])
647 def test_iso_long_fmt(identifier, expected):
648 assert {
649 k: v for k, v in cli_tokenise(identifier).items()
650 if v is not None
651 } == expected