Debian Codegraph @

tests/u/test_config.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 contextlib import suppress
18 import logging
19 from optparse import Values
20 import os
21 from pathlib import Path
22 from textwrap import dedent
23 from types import SimpleNamespace
24 from typing import (
25 Any,
26 Callable,
27 Dict,
28 List,
29 Optional,
30 Tuple,
31 Type,
32 )
33 from unittest.mock import Mock
34
35 import pytest
36
37 from cylc.flow import (
38 CYLC_LOG,
39 flags,
40 )
41 from cylc.flow.config import WorkflowConfig
42 from cylc.flow.cycling import loader
43 from cylc.flow.cycling.iso8601 import ISO8601Point
44 from cylc.flow.cycling.loader import (
45 INTEGER_CYCLING_TYPE,
46 ISO8601_CYCLING_TYPE,
47 )
48 from cylc.flow.exceptions import (
49 GraphParseError,
50 InputError,
51 PointParsingError,
52 WorkflowConfigError,
53 XtriggerConfigError,
54 )
55 from cylc.flow.parsec.exceptions import (
56 Jinja2Error,
57 )
58 from cylc.flow.scheduler_cli import RunOptions
59 from cylc.flow.scripts.validate import ValidateOptions
60 from cylc.flow.task_outputs import (
61 TASK_OUTPUT_SUBMITTED,
62 TASK_OUTPUT_SUCCEEDED,
63 )
64 from cylc.flow.wallclock import (
65 get_utc_mode,
66 set_utc_mode,
67 )
68 from cylc.flow.workflow_files import WorkflowFiles
69
70
71 Fixture = Any
72
73
74 param = pytest.param
75
76
77 class TestWorkflowConfig:
78 """Test class for the Cylc WorkflowConfig object."""
79
80 def test_xfunction_imports(
81 self, mock_glbl_cfg: 'Fixture', tmp_path: 'Path'):
82 """Test for a workflow configuration with valid xtriggers"""
83 mock_glbl_cfg(
84 'cylc.flow.platforms.glbl_cfg',
85 '''
86 [platforms]
87 [[localhost]]
88 hosts = localhost
89 '''
90 )
91 python_dir = tmp_path / "lib" / "python"
92 python_dir.mkdir(parents=True)
93 name_a_tree_file = python_dir / "name_a_tree.py"
94 # NB: we are not returning a lambda, instead we have a scalar
95 name_a_tree_file.write_text("""name_a_tree = lambda: 'jacaranda'""")
96 flow_file = tmp_path / WorkflowFiles.FLOW_FILE
97 flow_config = """
98 [scheduler]
99 allow implicit tasks = True
100 [scheduling]
101 initial cycle point = 2018-01-01
102 [[xtriggers]]
103 tree = name_a_tree()
104 [[graph]]
105 R1 = '@tree => qux'
106 """
107 flow_file.write_text(flow_config)
108 workflow_config = WorkflowConfig(
109 workflow="name_a_tree", fpath=flow_file, options=SimpleNamespace()
110 )
111 assert 'tree' in workflow_config.xtrigger_collator.functx_map
112
113 def test_xfunction_import_error(self, mock_glbl_cfg, tmp_path):
114 """Test for error when a xtrigger function cannot be imported."""
115 mock_glbl_cfg(
116 'cylc.flow.platforms.glbl_cfg',
117 '''
118 [platforms]
119 [[localhost]]
120 hosts = localhost
121 '''
122 )
123 python_dir = tmp_path / "lib" / "python"
124 python_dir.mkdir(parents=True)
125 caiman_file = python_dir / "caiman.py"
126 # NB: we are not returning a lambda, instead we have a scalar
127 caiman_file.write_text("""caiman = lambda: True""")
128 flow_file = tmp_path / WorkflowFiles.FLOW_FILE
129 flow_config = """
130 [scheduling]
131 initial cycle point = 2018-01-01
132 [[xtriggers]]
133 oopsie = piranha()
134 [[graph]]
135 R1 = '@oopsie => qux'
136 """
137 flow_file.write_text(flow_config)
138 with pytest.raises(XtriggerConfigError) as excinfo:
139 WorkflowConfig(
140 workflow="caiman_workflow",
141 fpath=flow_file,
142 options=SimpleNamespace()
143 )
144 assert "No module named 'piranha'" in str(excinfo.value)
145
146 def test_xfunction_attribute_error(self, mock_glbl_cfg, tmp_path):
147 """Test for error when a xtrigger function cannot be imported."""
148 mock_glbl_cfg(
149 'cylc.flow.platforms.glbl_cfg',
150 '''
151 [platforms]
152 [[localhost]]
153 hosts = localhost
154 '''
155 )
156 python_dir = tmp_path / "lib" / "python"
157 python_dir.mkdir(parents=True)
158 capybara_file = python_dir / "capybara.py"
159 # NB: we are not returning a lambda, instead we have a scalar
160 capybara_file.write_text("""toucan = lambda: True""")
161 flow_file = tmp_path / WorkflowFiles.FLOW_FILE
162 flow_config = """
163 [scheduling]
164 initial cycle point = 2018-01-01
165 [[xtriggers]]
166 oopsie = capybara()
167 [[graph]]
168 R1 = '@oopsie => qux'
169 """
170 flow_file.write_text(flow_config)
171 with pytest.raises(XtriggerConfigError) as excinfo:
172 WorkflowConfig(workflow="capybara_workflow", fpath=flow_file,
173 options=SimpleNamespace())
174 assert "module 'capybara' has no attribute 'capybara'" in str(
175 excinfo.value)
176
177 def test_xfunction_not_callable(self, mock_glbl_cfg, tmp_path):
178 """Test for error when a xtrigger function is not callable."""
179 mock_glbl_cfg(
180 'cylc.flow.platforms.glbl_cfg',
181 '''
182 [platforms]
183 [[localhost]]
184 hosts = localhost
185 '''
186 )
187 python_dir = tmp_path / "lib" / "python"
188 python_dir.mkdir(parents=True)
189 not_callable_file = python_dir / "not_callable.py"
190 # NB: we are not returning a lambda, instead we have a scalar
191 not_callable_file.write_text("""not_callable = 42""")
192 flow_file = tmp_path / WorkflowFiles.FLOW_FILE
193 flow_config = """
194 [scheduling]
195 initial cycle point = 2018-01-01
196 [[xtriggers]]
197 oopsie = not_callable()
198 [[graph]]
199 R1 = '@oopsie => qux'
200 """
201 flow_file.write_text(flow_config)
202 with pytest.raises(XtriggerConfigError) as excinfo:
203 WorkflowConfig(
204 workflow="workflow_with_not_callable",
205 fpath=flow_file,
206 options=SimpleNamespace()
207 )
208 assert "callable" in str(excinfo.value)
209
210
211 @pytest.mark.parametrize(
212 'fam_txt',
213 [pytest.param('"SOMEFAM"', id="double quoted"),
214 pytest.param('\'SOMEFAM\'', id="single quoted"),
215 pytest.param('SOMEFAM', id="unquoted")]
216 )
217 def test_family_inheritance_and_quotes(
218 fam_txt: str,
219 mock_glbl_cfg: Callable, tmp_flow_config: Callable
220 ) -> None:
221 """Test that inheritance does not ignore items, if not all quoted.
222
223 For example:
224
225 inherit = 'MAINFAM<major, minor>', SOMEFAM
226 inherit = 'BIGFAM', SOMEFAM
227
228 See bug #2700 for more/
229 """
230 mock_glbl_cfg(
231 'cylc.flow.platforms.glbl_cfg',
232 '''
233 [platforms]
234 [[localhost]]
235 hosts = localhost
236 '''
237 )
238 id_ = 'test'
239 file_path = tmp_flow_config(id_, f'''
240 [scheduler]
241 allow implicit tasks = True
242 [task parameters]
243 major = 1..5
244 minor = 10..20
245 [scheduling]
246 [[graph]]
247 R1 = """hello => MAINFAM<major, minor>
248 hello => SOMEFAM"""
249 [runtime]
250 [[root]]
251 script = true
252 [[MAINFAM<major, minor>]]
253 [[SOMEFAM]]
254 [[ goodbye_0<major, minor> ]]
255 inherit = 'MAINFAM<major, minor>', {fam_txt}
256 ''')
257 config = WorkflowConfig(
258 id_, file_path, template_vars={}, options=Values()
259 )
260 assert ('goodbye_0_major1_minor10' in
261 config.runtime['descendants']['MAINFAM_major1_minor10'])
262 assert ('goodbye_0_major1_minor10' in
263 config.runtime['descendants']['SOMEFAM'])
264
265
266 @pytest.mark.parametrize(
267 ('cycling_type', 'scheduling_cfg', 'expected_icp', 'expected_err'),
268 [
269 pytest.param(
270 ISO8601_CYCLING_TYPE,
271 {'initial cycle point': None},
272 None,
273 (WorkflowConfigError, "requires an initial cycle point"),
274 id="Lack of icp"
275 ),
276 pytest.param(
277 INTEGER_CYCLING_TYPE,
278 {'initial cycle point': None},
279 '1',
280 None,
281 id="Default icp for integer cycling type"
282 ),
283 pytest.param(
284 INTEGER_CYCLING_TYPE,
285 {'initial cycle point': "now"},
286 None,
287 (PointParsingError, "invalid literal for int()"),
288 id="Non-integer ICP for integer cycling type"
289 ),
290 pytest.param(
291 INTEGER_CYCLING_TYPE,
292 {'initial cycle point': "20500808T0000Z"},
293 None,
294 (PointParsingError, "invalid literal for int()"),
295 id="More non-integer ICP for integer cycling type"
296 ),
297 pytest.param(
298 ISO8601_CYCLING_TYPE,
299 {'initial cycle point': "1"},
300 None,
301 (PointParsingError, "Invalid ISO 8601 date representation"),
302 id="Non-ISO8601 ICP for ISO8601 cycling type"
303 ),
304 pytest.param(
305 ISO8601_CYCLING_TYPE,
306 {'initial cycle point': 'now'},
307 '20050102T0615+0530',
308 None,
309 id="ICP = now"
310 ),
311 pytest.param(
312 ISO8601_CYCLING_TYPE,
313 {'initial cycle point': 'previous(T00)'},
314 '20050102T0000+0530',
315 None,
316 id="ICP = prev"
317 ),
318 pytest.param(
319 ISO8601_CYCLING_TYPE,
320 {
321 'initial cycle point': '2013',
322 'initial cycle point constraints': ['T00', 'T12']
323 },
324 '20130101T0000+0530',
325 None,
326 id="Constraints"
327 ),
328 pytest.param(
329 ISO8601_CYCLING_TYPE,
330 {
331 'initial cycle point': '2021-01-20',
332 'initial cycle point constraints': ['--01-19', '--01-21']
333 },
334 None,
335 (WorkflowConfigError, "does not meet the constraints"),
336 id="Violated constraints"
337 ),
338 pytest.param(
339 ISO8601_CYCLING_TYPE,
340 {
341 'initial cycle point': 'a',
342 },
343 None,
344 (WorkflowConfigError, 'Invalid ISO 8601 date representation: a'),
345 id="invalid"
346 ),
347 ]
348 )
349 def test_process_icp(
350 cycling_type: str,
351 scheduling_cfg: Dict[str, Any],
352 expected_icp: Optional[str],
353 expected_err: Optional[Tuple[Type[Exception], str]],
354 monkeypatch: pytest.MonkeyPatch, set_cycling_type: 'Fixture'
355 ) -> None:
356 """Test WorkflowConfig.process_initial_cycle_point().
357
358 "now" is assumed to be 2005-01-02T06:15+0530
359
360 Params:
361 cycling_type: Workflow cycling type.
362 scheduling_cfg: 'scheduling' section of workflow config.
363 expected_icp: The expected icp value that gets set.
364 expected_err: Exception class expected to be raised plus the message.
365 """
366 set_cycling_type(cycling_type, time_zone="+0530")
367 mocked_config = SimpleNamespace(
368 cycling_type=cycling_type,
369 options=SimpleNamespace(icp=None),
370 cfg={
371 'scheduling': {
372 'initial cycle point constraints': [],
373 **scheduling_cfg
374 },
375 },
376 )
377 monkeypatch.setattr('cylc.flow.config.get_current_time_string',
378 lambda: '20050102T0615+0530')
379
380 if expected_err:
381 err, msg = expected_err
382 with pytest.raises(err) as exc:
383 WorkflowConfig.process_initial_cycle_point(mocked_config)
384 assert msg in str(exc.value)
385 else:
386 WorkflowConfig.process_initial_cycle_point(mocked_config)
387 assert mocked_config.cfg[
388 'scheduling']['initial cycle point'] == expected_icp
389 assert str(mocked_config.initial_point) == expected_icp
390
391
392 @pytest.mark.parametrize(
393 'cycling_type, options, expected, expected_err',
394 [
395 (
396 ISO8601_CYCLING_TYPE,
397 SimpleNamespace(startcp='20210120T1700+0530'),
398 '20210120T1700+0530',
399 None,
400 ),
401 (
402 ISO8601_CYCLING_TYPE,
403 SimpleNamespace(startcp='now'),
404 '20050102T0615+0530',
405 None,
406 ),
407 (
408 ISO8601_CYCLING_TYPE,
409 SimpleNamespace(startcp='previous(T00)'),
410 '20050102T0000+0530',
411 None,
412 ),
413 (
414 ISO8601_CYCLING_TYPE,
415 SimpleNamespace(startcp=None),
416 '18990501T0000+0530',
417 None,
418 ),
419 (
420 ISO8601_CYCLING_TYPE,
421 SimpleNamespace(
422 starttask=['20090802T0615+0530/foo', '20090802T0515+0530/bar']
423 ),
424 '20090802T0515+0530',
425 None,
426 ),
427 (
428 ISO8601_CYCLING_TYPE,
429 SimpleNamespace(
430 startcp='20210120T1700+0530',
431 starttask=['20090802T0615+0530/foo'],
432 ),
433 None,
434 (
435 InputError,
436 "--start-cycle-point and --start-task are mutually exclusive",
437 ),
438 ),
439 (
440 INTEGER_CYCLING_TYPE,
441 SimpleNamespace(startcp='10'),
442 '10',
443 None,
444 )
445 ],
446 )
447 def test_process_startcp(
448 cycling_type: str,
449 options: SimpleNamespace,
450 expected: str,
451 expected_err: Optional[Tuple[Type[Exception], str]],
452 monkeypatch: pytest.MonkeyPatch, set_cycling_type: 'Fixture'
453 ) -> None:
454 """Test WorkflowConfig.process_start_cycle_point().
455
456 An icp of 1899-05-01T00+0530 is assumed, and "now" is assumed to be
457 2005-01-02T06:15+0530
458
459 Params:
460 options: SimpleNamespace with startcp and starttask attributes.
461 expected: The expected startcp value that gets set.
462 expected_err: Expected exception.
463 """
464 set_cycling_type(cycling_type, time_zone='+0530')
465 mocked_config = Mock(
466 spec=WorkflowConfig,
467 cycling_type=cycling_type,
468 initial_point='18990501T0000+0530',
469 options=options,
470 )
471 monkeypatch.setattr('cylc.flow.config.get_current_time_string',
472 lambda: '20050102T0615+0530')
473 if expected_err is not None:
474 err, msg = expected_err
475 with pytest.raises(err) as exc:
476 WorkflowConfig.process_start_cycle_point(mocked_config)
477 assert msg in str(exc.value)
478 else:
479 WorkflowConfig.process_start_cycle_point(mocked_config)
480 assert str(mocked_config.start_point) == expected
481
482
483 @pytest.mark.parametrize(
484 'cycling_type, scheduling_cfg, options_fcp, expected_fcp, expected_err',
485 [
486 pytest.param(
487 ISO8601_CYCLING_TYPE,
488 {
489 'initial cycle point': '2021',
490 'final cycle point': None,
491 },
492 None,
493 None,
494 None,
495 id="No fcp"
496 ),
497 pytest.param(
498 ISO8601_CYCLING_TYPE,
499 {
500 'initial cycle point': '2021',
501 'final cycle point': '',
502 },
503 None,
504 None,
505 None,
506 id="Empty fcp in cfg"
507 # This test is needed because fcp is treated as string by parsec,
508 # unlike other cycle point settings (allows for e.g. '+P1Y')
509 ),
510 pytest.param(
511 ISO8601_CYCLING_TYPE,
512 {
513 'initial cycle point': '2016',
514 'final cycle point': '2021',
515 },
516 None,
517 '20210101T0000+0530',
518 None,
519 id="fcp in cfg"
520 ),
521 pytest.param(
522 ISO8601_CYCLING_TYPE,
523 {
524 'initial cycle point': '2016',
525 'final cycle point': '2021',
526 },
527 '2019',
528 '20190101T0000+0530',
529 None,
530 id="Overriden by cli option"
531 ),
532 pytest.param(
533 ISO8601_CYCLING_TYPE,
534 {
535 'initial cycle point': '2017-02-11',
536 'final cycle point': '+P4D',
537 },
538 None,
539 '20170215T0000+0530',
540 None,
541 id="Relative fcp"
542 ),
543 pytest.param(
544 ISO8601_CYCLING_TYPE,
545 {
546 'initial cycle point': '2017-02-11',
547 'final cycle point': '+P4D+PT3H-PT2H',
548 },
549 None,
550 '20170215T0100+0530',
551 None,
552 id="Relative fcp chained"
553 ),
554 pytest.param(
555 ISO8601_CYCLING_TYPE,
556 {
557 'initial cycle point': '2017-02-11',
558 'final cycle point': '---04',
559 },
560 None,
561 '20170215T0000+0530',
562 None,
563 id="Relative truncated fcp", marks=pytest.mark.xfail
564 # https://github.com/metomi/isodatetime/issues/80
565 ),
566 pytest.param(
567 INTEGER_CYCLING_TYPE,
568 {
569 'initial cycle point': '1',
570 'final cycle point': '4',
571 },
572 None,
573 '4',
574 None,
575 id="Integer cycling"
576 ),
577 pytest.param(
578 INTEGER_CYCLING_TYPE,
579 {
580 'initial cycle point': '1',
581 'final cycle point': '+P2',
582 },
583 None,
584 '3',
585 None,
586 id="Relative fcp, integer cycling"
587 ),
588 pytest.param(
589 ISO8601_CYCLING_TYPE,
590 {
591 'initial cycle point': '2013',
592 'final cycle point': '2009',
593 },
594 None,
595 None,
596 (WorkflowConfigError,
597 "initial cycle point:20130101T0000+0530 is after the "
598 "final cycle point"),
599 id="fcp before icp"
600 ),
601 pytest.param(
602 ISO8601_CYCLING_TYPE,
603 {
604 'initial cycle point': '2013',
605 'final cycle point': '-PT1S',
606 },
607 None,
608 None,
609 (WorkflowConfigError,
610 "initial cycle point:20130101T0000+0530 is after the "
611 "final cycle point"),
612 id="Negative relative fcp"
613 ),
614 pytest.param(
615 ISO8601_CYCLING_TYPE,
616 {
617 'initial cycle point': '2013',
618 'final cycle point': '2021',
619 'final cycle point constraints': ['T00', 'T12']
620 },
621 None,
622 '20210101T0000+0530',
623 None,
624 id="Constraints"
625 ),
626 pytest.param(
627 ISO8601_CYCLING_TYPE,
628 {
629 'initial cycle point': '2013',
630 'final cycle point': '2021-01-19',
631 'final cycle point constraints': ['--01-19', '--01-21']
632 },
633 '2021-01-20',
634 None,
635 (WorkflowConfigError, "does not meet the constraints"),
636 id="Violated constraints"
637 ),
638 pytest.param(
639 ISO8601_CYCLING_TYPE,
640 {
641 'initial cycle point': '2013',
642 'final cycle point': '2021',
643 },
644 'reload',
645 '20210101T0000+0530',
646 None,
647 id="--fcp=reload"
648 ),
649 ]
650 )
651 def test_process_fcp(
652 cycling_type: str,
653 scheduling_cfg: dict,
654 options_fcp: Optional[str],
655 expected_fcp: Optional[str],
656 expected_err: Optional[Tuple[Type[Exception], str]],
657 set_cycling_type: 'Fixture'
658 ) -> None:
659 """Test WorkflowConfig.process_final_cycle_point().
660
661 Params:
662 cycling_type: Workflow cycling type.
663 scheduling_cfg: 'scheduling' section of workflow config.
664 options_fcp: The fcp set by cli option.
665 expected_fcp: The expected fcp value that gets set.
666 expected_err: Exception class expected to be raised plus the message.
667 """
668 set_cycling_type(cycling_type, time_zone='+0530')
669 mocked_config = SimpleNamespace(
670 cycling_type=cycling_type,
671 cfg={
672 'scheduling': {
673 'final cycle point constraints': [],
674 **scheduling_cfg,
675 },
676 },
677 initial_point=loader.get_point(
678 scheduling_cfg['initial cycle point']
679 ).standardise(),
680 final_point=None,
681 options=SimpleNamespace(fcp=options_fcp),
682 )
683
684 if expected_err:
685 err, msg = expected_err
686 with pytest.raises(err) as exc:
687 WorkflowConfig.process_final_cycle_point(mocked_config)
688 assert msg in str(exc.value)
689 else:
690 WorkflowConfig.process_final_cycle_point(mocked_config)
691 assert mocked_config.cfg[
692 'scheduling']['final cycle point'] == expected_fcp
693 assert str(mocked_config.final_point) == str(expected_fcp)
694
695
696 @pytest.mark.parametrize(
697 ('cfg_stopcp', 'options_stopcp', 'expected_value',
698 'expected_options_value', 'expected_warning'),
699 [
700 pytest.param(
701 None, None, None, None, None,
702 id="no-stopcp"
703 ),
704 pytest.param(
705 '1993', None, '1993', None, None,
706 id="stopcp"
707 ),
708 pytest.param(
709 '1993', '1066', '1066', '1066', None,
710 id="stop-cp-and-cli-option"
711 ),
712 pytest.param(
713 '1993', 'reload', '1993', None, None,
714 id="stop-cp-and-cli-reload-option"
715 ),
716 pytest.param(
717 '3000', None, None, None,
718 "will have no effect as it is after the final cycle point",
719 id="stopcp-beyond-fcp"
720 ),
721 pytest.param(
722 '+P12Y -P2Y', None, '2000', None, None,
723 id="stopcp-relative-to-icp"
724 ),
725 ]
726 )
727 def test_process_stop_cycle_point(
728 cfg_stopcp: Optional[str],
729 options_stopcp: Optional[str],
730 expected_value: Optional[str],
731 expected_options_value: Optional[str],
732 expected_warning: Optional[str],
733 set_cycling_type: Callable,
734 caplog: pytest.LogCaptureFixture
735 ):
736 """Test WorkflowConfig.process_stop_cycle_point().
737
738 Params:
739 cfg_stopcp: [scheduling]stop after cycle point
740 options_stopcp: The stopcp from cli option / database.
741 expected_value: The expected stopcp value that gets set.
742 expected_options_value: The expected options.stopcp that gets set.
743 expected_warning: Expected warning message, if any.
744 """
745 set_cycling_type(ISO8601_CYCLING_TYPE, dump_format='CCYY')
746 caplog.set_level(logging.WARNING, CYLC_LOG)
747 fcp = loader.get_point('2012').standardise()
748 mock_config = SimpleNamespace(
749 cfg={
750 'scheduling': {
751 'stop after cycle point': cfg_stopcp
752 }
753 },
754 initial_point=ISO8601Point('1990'),
755 final_point=fcp,
756 stop_point=None,
757 options=RunOptions(stopcp=options_stopcp),
758 )
759
760 WorkflowConfig.process_stop_cycle_point(mock_config)
761 assert str(mock_config.stop_point) == str(expected_value)
762 assert mock_config.cfg['scheduling']['stop after cycle point'] == (
763 expected_value
764 )
765 assert mock_config.options.stopcp == expected_options_value
766 if expected_warning:
767 assert expected_warning in caplog.text
768 else:
769 assert not caplog.record_tuples
770
771
772 @pytest.mark.parametrize(
773 'cfg_fcp, cfg_stopcp, opts, warning_expected',
774 [
775 pytest.param(
776 '2005', '2017', {}, True,
777 id="cfg stopcp > fcp bad"
778 ),
779 pytest.param(
780 '2017', '2017', {}, False,
781 id="cfg stopcp == fcp ok"
782 ),
783 pytest.param(
784 '', '', {'fcp': '2005', 'stopcp': '2017'}, True,
785 id="options stopcp > fcp bad"
786 ),
787 pytest.param(
788 '', '', {'fcp': '2017', 'stopcp': '2017'}, False,
789 id="options stopcp == fcp ok"
790 ),
791 pytest.param(
792 '2017', '2005', {'stopcp': '2022'}, True,
793 id="options stopcp > cfg fcp bad"
794 ),
795 pytest.param(
796 '2017', '2005', {'stopcp': '2022'}, True,
797 id="options stopcp > cfg fcp bad"
798 ),
799 pytest.param(
800 '2022', '2017', {'fcp': '2005'}, True,
801 id="cfg stopcp > options fcp bad"
802 ),
803 pytest.param(
804 '', '2022', {}, False,
805 id="no fcp"
806 ),
807 ]
808 )
809 def test_stopcp_after_fcp(
810 cfg_fcp: str,
811 cfg_stopcp: str,
812 opts: Dict[str, str],
813 warning_expected: bool,
814 tmp_flow_config: Callable,
815 caplog: pytest.LogCaptureFixture,
816 ):
817 """Test that setting a stop after cycle point that is beyond the final
818 cycle point is handled correctly."""
819 caplog.set_level(logging.WARNING, CYLC_LOG)
820 id_ = 'cassini'
821 flow_file: 'Path' = tmp_flow_config(id_, f"""
822 [scheduler]
823 allow implicit tasks = True
824 [scheduling]
825 initial cycle point = 1997
826 final cycle point = {cfg_fcp}
827 stop after cycle point = {cfg_stopcp}
828 [[graph]]
829 P1Y = huygens
830 """)
831 cfg = WorkflowConfig(id_, flow_file, options=RunOptions(**opts))
832 msg = "will have no effect as it is after the final cycle point"
833 if warning_expected:
834 assert msg in caplog.text
835 assert cfg.stop_point is None
836 else:
837 assert msg not in caplog.text
838 if cfg_stopcp or opts.get('stopcp'):
839 assert cfg.stop_point
840
841
842 @pytest.mark.parametrize(
843 'scheduling_cfg, scheduling_expected, expected_err',
844 [
845 pytest.param(
846 {
847 'graph': {}
848 },
849 None,
850 (WorkflowConfigError, "No workflow dependency graph defined"),
851 id="Empty graph"
852 ),
853 pytest.param(
854 {
855 'graph': {'R1': 'foo'}
856 },
857 {
858 'cycling mode': 'integer',
859 'initial cycle point': '1',
860 'final cycle point': '1',
861 'graph': {'R1': 'foo'}
862 },
863 None,
864 id="Pure acyclic graph"
865 ),
866 pytest.param(
867 {
868 'cycling mode': "",
869 'graph': {'R1': 'foo'}
870 },
871 {
872 'cycling mode': "",
873 'graph': {'R1': 'foo'}
874 },
875 None,
876 id="Pure acyclic graph but datetime cycling"
877 ),
878 pytest.param(
879 {
880 'graph': {'R1': 'foo', 'R2': 'bar'}
881 },
882 {
883 'graph': {'R1': 'foo', 'R2': 'bar'}
884 },
885 None,
886 id="Acyclic graph with >1 recurrence"
887 ),
888 ]
889 )
890 def test_prelim_process_graph(
891 scheduling_cfg: Dict[str, Any],
892 scheduling_expected: Optional[Dict[str, Any]],
893 expected_err: Optional[Tuple[Type[Exception], str]]):
894 """Test WorkflowConfig.prelim_process_graph().
895
896 Params:
897 scheduling_cfg: 'scheduling' section of workflow config.
898 scheduling_expected: The expected scheduling section after preliminary
899 processing.
900 expected_err: Exception class expected to be raised plus the message.
901 """
902 mock_config = SimpleNamespace(cfg={
903 'scheduling': scheduling_cfg
904 })
905
906 if expected_err:
907 err, msg = expected_err
908 with pytest.raises(err) as exc:
909 WorkflowConfig.prelim_process_graph(mock_config)
910 assert msg in str(exc.value)
911 else:
912 WorkflowConfig.prelim_process_graph(mock_config)
913 assert mock_config.cfg['scheduling'] == scheduling_expected
914
915
916 def test_utc_mode(caplog, mock_glbl_cfg):
917 """Test that UTC mode is handled correctly."""
918 caplog.set_level(logging.WARNING, CYLC_LOG)
919
920 def _test(utc_mode, expected, expected_warnings=0):
921 mock_glbl_cfg(
922 'cylc.flow.config.glbl_cfg',
923 f'''
924 [scheduler]
925 UTC mode = {utc_mode['glbl']}
926 '''
927 )
928 mock_config = SimpleNamespace(
929 cfg={
930 'scheduler': {
931 'UTC mode': utc_mode['workflow']
932 }
933 },
934 options=SimpleNamespace(utc_mode=utc_mode['stored']),
935 )
936
937 WorkflowConfig.process_utc_mode(mock_config)
938 assert mock_config.cfg['scheduler']['UTC mode'] is expected
939 assert get_utc_mode() is expected
940 assert len(caplog.record_tuples) == expected_warnings
941 caplog.clear()
942
943 tests = [
944 {
945 'utc_mode': {'glbl': True, 'workflow': None, 'stored': None},
946 'expected': True
947 },
948 {
949 'utc_mode': {'glbl': True, 'workflow': False, 'stored': None},
950 'expected': False
951 },
952 {
953 # On restart
954 'utc_mode': {'glbl': False, 'workflow': None, 'stored': True},
955 'expected': True
956 },
957 {
958 # Changed config value between restarts
959 'utc_mode': {'glbl': False, 'workflow': False, 'stored': True},
960 'expected': True,
961 'expected_warnings': 1
962 }
963 ]
964 for case in tests:
965 _test(**case)
966
967
968 def test_cycle_point_tz(caplog, monkeypatch):
969 """Test that `[scheduler]cycle point time zone` is handled correctly."""
970 caplog.set_level(logging.WARNING, CYLC_LOG)
971
972 local_tz = '-0230'
973 monkeypatch.setattr(
974 'cylc.flow.config.get_local_time_zone_format',
975 lambda: local_tz
976 )
977
978 def _test(cp_tz, utc_mode, expected, expected_warnings=0):
979 set_utc_mode(utc_mode)
980 mock_config = SimpleNamespace(
981 cfg={
982 'scheduler': {
983 'cycle point time zone': cp_tz['workflow'],
984 },
985 },
986 options=SimpleNamespace(cycle_point_tz=cp_tz['stored']),
987 )
988
989 WorkflowConfig.process_cycle_point_tz(mock_config)
990 assert mock_config.cfg['scheduler'][
991 'cycle point time zone'] == expected
992 assert len(caplog.record_tuples) == expected_warnings
993 caplog.clear()
994
995 tests = [
996 {
997 'cp_tz': {'workflow': None, 'stored': None},
998 'utc_mode': True,
999 'expected': 'Z'
1000 },
1001 {
1002 'cp_tz': {'workflow': None, 'stored': None},
1003 'utc_mode': False,
1004 'expected': 'Z'
1005 },
1006 {
1007 'cp_tz': {'workflow': '+0530', 'stored': None},
1008 'utc_mode': True,
1009 'expected': '+0530'
1010 },
1011 {
1012 # On restart
1013 'cp_tz': {'workflow': None, 'stored': '+0530'},
1014 'utc_mode': True,
1015 'expected': '+0530',
1016 'expected_warnings': 1
1017 },
1018 {
1019 # Changed config value between restarts
1020 'cp_tz': {'workflow': '+0530', 'stored': '-0030'},
1021 'utc_mode': True,
1022 'expected': '-0030',
1023 'expected_warnings': 1
1024 },
1025 {
1026 'cp_tz': {'workflow': 'Z', 'stored': 'Z'},
1027 'utc_mode': False,
1028 'expected': 'Z'
1029 }
1030 ]
1031 for case in tests:
1032 _test(**case)
1033
1034
1035 def test_rsync_includes_will_not_accept_sub_directories(tmp_flow_config):
1036 id_ = 'rsynctest'
1037 flow_file = tmp_flow_config(id_, """
1038 [scheduling]
1039 initial cycle point = 2020-01-01
1040 [[dependencies]]
1041 graph = "blah => deeblah"
1042 [scheduler]
1043 install = /, /foo, /foo/, foo/bar, foo/bar/
1044 """)
1045
1046 with pytest.raises(WorkflowConfigError) as exc:
1047 WorkflowConfig(
1048 workflow=id_, fpath=flow_file, options=Values()
1049 )
1050 assert '"/" - Paths cannot be absolute.' in str(exc.value)
1051 assert '"/foo" - Paths cannot be absolute.' in str(exc.value)
1052 assert (
1053 '"foo/bar" - Only top-level files/directories can be configured.'
1054 in str(exc.value)
1055 )
1056 assert (
1057 '"foo/bar/" - Only top-level files/directories can be configured.'
1058 in str(exc.value)
1059 )
1060
1061
1062 @pytest.mark.parametrize(
1063 'cylc_var, expected_err',
1064 [
1065 ["CYLC_WORKFLOW_NAME", None],
1066 ["CYLC_BEEF_WELLINGTON", (Jinja2Error, "is undefined")],
1067 ]
1068 )
1069 def test_jinja2_cylc_vars(tmp_flow_config, cylc_var, expected_err):
1070 """Defined CYLC_ variables should be available to Jinja2 during parsing.
1071
1072 This test is not located in the jinja2_support unit test module because
1073 CYLC_ variables are only defined during workflow config parsing.
1074 """
1075 reg = 'nodule'
1076 flow_file = tmp_flow_config(reg, """#!Jinja2
1077 # {{""" + cylc_var + """}}
1078 [scheduler]
1079 allow implicit tasks = True
1080 [scheduling]
1081 [[graph]]
1082 R1 = foo
1083 """)
1084 if expected_err is None:
1085 WorkflowConfig(workflow=reg, fpath=flow_file, options=Values())
1086 else:
1087 with pytest.raises(expected_err[0]) as exc:
1088 WorkflowConfig(workflow=reg, fpath=flow_file, options=Values())
1089 assert expected_err[1] in str(exc)
1090
1091
1092 def test_valid_rsync_includes_returns_correct_list(tmp_flow_config):
1093 """Test that the rsync includes in the correct """
1094 id_ = 'rsynctest'
1095 flow_file = tmp_flow_config(id_, """
1096 [scheduling]
1097 initial cycle point = 2020-01-01
1098 [[dependencies]]
1099 graph = "blah => deeblah"
1100 [scheduler]
1101 install = dir/, dir2/, file1, file2
1102 allow implicit tasks = True
1103 """)
1104
1105 config = WorkflowConfig(
1106 workflow=id_, fpath=flow_file, options=Values()
1107 )
1108
1109 rsync_includes = WorkflowConfig.get_validated_rsync_includes(config)
1110 assert rsync_includes == ['dir/', 'dir2/', 'file1', 'file2']
1111
1112
1113 @pytest.mark.parametrize(
1114 'cycling_type, runahead_limit, valid',
1115 [
1116 (INTEGER_CYCLING_TYPE, 'P14', True),
1117 (ISO8601_CYCLING_TYPE, 'P14', True),
1118 (ISO8601_CYCLING_TYPE, 'PT12H', True),
1119 (ISO8601_CYCLING_TYPE, 'P7D', True),
1120 (ISO8601_CYCLING_TYPE, 'P2W', True),
1121 (ISO8601_CYCLING_TYPE, '4', True),
1122
1123 (INTEGER_CYCLING_TYPE, 'PT12H', False),
1124 (INTEGER_CYCLING_TYPE, 'P7D', False),
1125 (INTEGER_CYCLING_TYPE, '4', False),
1126 (ISO8601_CYCLING_TYPE, '', False),
1127 (ISO8601_CYCLING_TYPE, 'asdf', False)
1128 ]
1129 )
1130 def test_process_runahead_limit(
1131 cycling_type: str, runahead_limit: str, valid: bool,
1132 set_cycling_type: Callable
1133 ) -> None:
1134 set_cycling_type(cycling_type)
1135 mock_config = SimpleNamespace(cycling_type=cycling_type)
1136 mock_config.cfg = {
1137 'scheduling': {
1138 'runahead limit': runahead_limit
1139 }
1140 }
1141 if valid:
1142 WorkflowConfig.process_runahead_limit(mock_config)
1143 else:
1144 with pytest.raises(WorkflowConfigError) as exc:
1145 WorkflowConfig.process_runahead_limit(mock_config)
1146 assert "bad runahead limit" in str(exc.value).lower()
1147
1148
1149 @pytest.mark.parametrize(
1150 'opt', [None, 'check_circular']
1151 )
1152 def test_check_circular(opt, monkeypatch, caplog, tmp_flow_config):
1153 """Test WorkflowConfig._check_circular()."""
1154 # ----- Setup -----
1155 caplog.set_level(logging.INFO, CYLC_LOG)
1156
1157 options = SimpleNamespace(is_validate=True)
1158 if opt:
1159 setattr(options, opt, True)
1160
1161 id_ = 'circular'
1162 flow_file = tmp_flow_config(id_, """
1163 [scheduling]
1164 cycling mode = integer
1165 [[graph]]
1166 R1 = "a => b => c => d => e => a"
1167 [runtime]
1168 [[a, b, c, d, e]]
1169 script = True
1170 """)
1171
1172 def WorkflowConfig__assert_err_raised():
1173 with pytest.raises(WorkflowConfigError) as exc:
1174 WorkflowConfig(workflow=id_, fpath=flow_file, options=options)
1175 assert "circular edges detected" in str(exc.value)
1176
1177 # ----- The actual test -----
1178 WorkflowConfig__assert_err_raised()
1179 # Now artificially lower the limit and re-test:
1180 monkeypatch.setattr(
1181 'cylc.flow.config.WorkflowConfig.CHECK_CIRCULAR_LIMIT', 4)
1182 if opt != 'check_circular':
1183 # Will no longer raise
1184 WorkflowConfig(workflow='circular', fpath=flow_file, options=options)
1185 msg = "will not check graph for circular dependencies"
1186 assert msg in caplog.text
1187 else:
1188 WorkflowConfig__assert_err_raised()
1189
1190
1191 @pytest.mark.parametrize(
1192 'graph', (('foo:x => bar'), ('foo:x'))
1193 )
1194 def test_undefined_custom_output(graph: str, tmp_flow_config: Callable):
1195 """Test error on undefined custom output referenced in graph."""
1196 id_ = 'custom_out1'
1197 flow_file = tmp_flow_config(id_, f"""
1198 [scheduling]
1199 [[graph]]
1200 R1 = "{graph}"
1201 [runtime]
1202 [[foo, bar]]
1203 """)
1204
1205 with pytest.raises(WorkflowConfigError) as cm:
1206 WorkflowConfig(workflow=id_, fpath=flow_file, options=Values())
1207 assert "Undefined custom output" in str(cm.value)
1208
1209
1210 def test_invalid_custom_output_msg(tmp_flow_config: Callable):
1211 """Test invalid output message (colon not allowed)."""
1212 id_ = 'invalid_output'
1213 flow_file = tmp_flow_config(id_, """
1214 [scheduling]
1215 [[graph]]
1216 R1 = "foo:x => bar"
1217 [runtime]
1218 [[bar]]
1219 [[foo]]
1220 [[[outputs]]]
1221 x = "the quick: brown fox"
1222 """)
1223
1224 with pytest.raises(WorkflowConfigError) as cm:
1225 WorkflowConfig(
1226 workflow=id_, fpath=flow_file, options=Values())
1227 assert (
1228 'Invalid task message "[runtime][foo][outputs]x = '
1229 'the quick: brown fox"'
1230 ) in str(cm.value)
1231
1232
1233 def test_c7_back_compat_optional_outputs(tmp_flow_config, monkeypatch):
1234 """Test optional and required outputs Cylc 7 back compat mode.
1235
1236 Success outputs should be required, others optional. Tested here because
1237 success is set to required after graph parsing, in taskdef processing.
1238
1239 """
1240 monkeypatch.setattr('cylc.flow.flags.cylc7_back_compat', True)
1241 id_ = 'custom_out2'
1242 flow_file = tmp_flow_config(id_, '''
1243 [scheduling]
1244 [[graph]]
1245 R1 = """
1246 foo:x => bar
1247 foo:fail = oops
1248 foo => spoo
1249 """
1250 [runtime]
1251 [[bar, oops, spoo]]
1252 [[foo]]
1253 [[[outputs]]]
1254 x = x
1255 ''')
1256
1257 cfg = WorkflowConfig(workflow=id_, fpath=flow_file, options=None)
1258
1259 for taskdef in cfg.taskdefs.values():
1260 for output, (_, required) in taskdef.outputs.items():
1261 if output in [TASK_OUTPUT_SUBMITTED, TASK_OUTPUT_SUCCEEDED]:
1262 assert required
1263 else:
1264 assert not required
1265
1266
1267 @pytest.mark.parametrize(
1268 'graph',
1269 [
1270 "foo:x => bar",
1271 "foo:start => bar",
1272 "foo:submit => bar",
1273 ]
1274 )
1275 def test_implicit_success_required(tmp_flow_config, graph):
1276 """Check foo:succeed is required if success/fail not used in the graph."""
1277 id_ = 'blargh'
1278 flow_file = tmp_flow_config(id_, f"""
1279 [scheduling]
1280 [[graph]]
1281 R1 = {graph}
1282 [runtime]
1283 [[bar]]
1284 [[foo]]
1285 [[[outputs]]]
1286 x = "the quick brown fox"
1287 """)
1288 cfg = WorkflowConfig(workflow=id_, fpath=flow_file, options=None)
1289 assert cfg.taskdefs['foo'].outputs[TASK_OUTPUT_SUCCEEDED][1]
1290
1291
1292 @pytest.mark.parametrize(
1293 'allow_implicit_tasks',
1294 [
1295 pytest.param(True, id="allow implicit tasks = True"),
1296 pytest.param(None, id="allow implicit tasks not set"),
1297 pytest.param(False, id="allow implicit tasks = False")
1298 ]
1299 )
1300 @pytest.mark.parametrize(
1301 'cylc7_compat, rose_suite_conf, expected_exc, extra_msg_expected',
1302 [
1303 pytest.param(
1304 False, False, WorkflowConfigError, True,
1305 id="Default"
1306 ),
1307 pytest.param(
1308 False, True, WorkflowConfigError, True,
1309 id="rose-suite.conf present"
1310 ),
1311 pytest.param(
1312 True, False, None, False,
1313 id="Cylc 7 back-compat"
1314 ),
1315 pytest.param(
1316 True, True, WorkflowConfigError, False,
1317 id="Cylc 7 back-compat, rose-suite.conf present"
1318 ),
1319 ]
1320 )
1321 def test_implicit_tasks(
1322 allow_implicit_tasks: Optional[bool],
1323 cylc7_compat: bool,
1324 rose_suite_conf: bool,
1325 expected_exc: Optional[Type[Exception]],
1326 extra_msg_expected: bool,
1327 caplog: pytest.LogCaptureFixture,
1328 log_filter: Callable,
1329 monkeypatch: pytest.MonkeyPatch,
1330 tmp_flow_config: Callable
1331 ):
1332 """Test that the prescence of implicit tasks in the config
1333 is handled correctly.
1334
1335 Params:
1336 allow_implicit_tasks: Value of "[scheduler]allow implicit tasks".
1337 cylc7_compat: Whether Cylc 7 backwards compatibility is turned on.
1338 rose_suite_conf: Whether a rose-suite.conf file is present in run dir.
1339 expected_exc: Exception expected to be raised only when
1340 "[scheduler]allow implicit tasks" is not set.
1341 extra_msg_expected: If True, there should be the note on how to allow
1342 implicit tasks in the err msg.
1343 """
1344 # Setup
1345 id_ = 'rincewind'
1346
1347 allow_implicit_tasks_text = (
1348 f'allow implicit tasks = {allow_implicit_tasks}'
1349 if allow_implicit_tasks is not None else ''
1350 )
1351 flow_file: 'Path' = tmp_flow_config(
1352 id_,
1353 dedent(f"""
1354 [scheduler]
1355 {allow_implicit_tasks_text}
1356 [scheduling]
1357 [[graph]]
1358 R1 = foo
1359 """)
1360 )
1361 monkeypatch.setattr('cylc.flow.flags.cylc7_back_compat', cylc7_compat)
1362 if rose_suite_conf:
1363 (flow_file.parent / 'rose-suite.conf').touch()
1364 caplog.set_level(logging.DEBUG, CYLC_LOG)
1365 if allow_implicit_tasks is True:
1366 expected_exc = None
1367 elif allow_implicit_tasks is False:
1368 expected_exc = WorkflowConfigError
1369 extra_msg_expected &= (allow_implicit_tasks is None)
1370 # Test
1371 args: dict = {'workflow': id_, 'fpath': flow_file, 'options': None}
1372 expected_msg = r"implicit tasks detected.*"
1373 if expected_exc:
1374 with pytest.raises(expected_exc, match=expected_msg) as excinfo:
1375 WorkflowConfig(**args)
1376 assert (
1377 "To allow implicit tasks" in str(excinfo.value)
1378 ) is extra_msg_expected
1379 else:
1380 WorkflowConfig(**args)
1381
1382
1383 @pytest.mark.parametrize('workflow_meta', [True, False])
1384 @pytest.mark.parametrize('url_type', ['good', 'bad', 'ugly', 'broken'])
1385 def test_process_urls(log_filter, workflow_meta, url_type):
1386
1387 if url_type == 'good':
1388 # valid cylc 8 syntax
1389 url = '%(workflow)s'
1390 elif url_type == 'bad':
1391 # no variable called "foo"
1392 url = '%(foo)s'
1393 elif url_type == 'broken':
1394 # invalid syntax (missing the trailing "s")
1395 url = '%(suite_name)'
1396 elif url_type == 'ugly':
1397 # valid cylc 7 syntax
1398 url = '%(suite_name)s'
1399
1400 config = SimpleNamespace()
1401 config.workflow = 'my-workflow'
1402 if workflow_meta:
1403 config.cfg = {
1404 'meta': {'URL': url},
1405 'runtime': {}
1406 }
1407 else:
1408 config.cfg = {
1409 'meta': {'URL': ''},
1410 'runtime': {'foo': {'meta': {'URL': url}}},
1411 }
1412
1413 if url_type == 'good':
1414 WorkflowConfig.process_metadata_urls(config)
1415 elif url_type in {'bad', 'broken'}:
1416 with pytest.raises(InputError):
1417 WorkflowConfig.process_metadata_urls(config)
1418 elif url_type == 'ugly':
1419 WorkflowConfig.process_metadata_urls(config)
1420 assert log_filter(
1421 contains='Detected deprecated template variables',
1422 )
1423
1424
1425 @pytest.mark.parametrize('opts', [ValidateOptions(), RunOptions()])
1426 @pytest.mark.parametrize(
1427 'recurrence, should_warn',
1428 [
1429 # Format 3:
1430 ('P0Y', True),
1431 ('R//P0Y', True),
1432 ('R2//P0Y', True),
1433 ('R1//P0Y', False),
1434 # Format 4:
1435 ('R/P0M', True),
1436 ('R1/P0M', False),
1437 # Format 1:
1438 ('R/2002-09-01/2002-09-01', True),
1439 ('R1/2002-09-01/2002-09-01', False),
1440 ('R/2002-08-31/2002-09-02', False),
1441 ]
1442 )
1443 def test_zero_interval(
1444 recurrence: str,
1445 should_warn: bool,
1446 opts: Values,
1447 tmp_flow_config: Callable,
1448 log_filter: Callable,
1449 ):
1450 """Test that a zero-duration recurrence with >1 repetition gets an
1451 appropriate warning."""
1452 id_ = 'ordinary'
1453 flow_file: 'Path' = tmp_flow_config(id_, f"""
1454 [scheduler]
1455 UTC mode = True
1456 allow implicit tasks = True
1457 [scheduling]
1458 initial cycle point = 2002-08-30
1459 final cycle point = 2002-09-14
1460 [[graph]]
1461 {recurrence} = slidescape36
1462 """)
1463 WorkflowConfig(id_, flow_file, options=opts)
1464 logged = log_filter(
1465 level=logging.WARNING,
1466 contains="Cannot have more than 1 repetition for zero-duration"
1467 )
1468 if should_warn:
1469 assert logged
1470 else:
1471 assert not logged
1472
1473
1474 @pytest.mark.parametrize(
1475 'icp, fcp_expr, expected_fcp',
1476 [
1477 ('2021-02-28', '+P1M+P1D', '2021-03-29'),
1478 ('2019-02-28', '+P1D+P1M', '2019-04-01'),
1479 ('2008-07-01', '+P1M-P1D', '2008-07-31'),
1480 ('2004-07-01', '-P1D+P1M', '2004-07-30'),
1481 ('1992-02-29', '+P1Y+P1M', '1993-03-28'),
1482 ('1988-02-29', '+P1M+P1Y', '1989-03-29'),
1483 ('1910-08-14', '+P2D-PT6H', '1910-08-15T18:00'),
1484 ('1850-04-10', '+P1M-P1D+PT1H', '1850-05-09T01:00'),
1485 ('1066-10-14', '+PT1H+PT1M', '1066-10-14T01:01'),
1486 ]
1487 )
1488 def test_chain_expr(
1489 icp: str, fcp_expr: str, expected_fcp: str, tmp_flow_config: Callable,
1490 ):
1491 """Test a "chain expression" final cycle point offset.
1492
1493 Note the order matters when "nominal" units (years, months) are used.
1494 """
1495 id_ = 'osgiliath'
1496 flow_file: 'Path' = tmp_flow_config(id_, f"""
1497 [scheduler]
1498 UTC mode = True
1499 allow implicit tasks = True
1500 [scheduling]
1501 initial cycle point = {icp}
1502 final cycle point = {fcp_expr}
1503 [[graph]]
1504 P1D = faramir
1505 """)
1506 cfg = WorkflowConfig(id_, flow_file, options=ValidateOptions())
1507 assert cfg.final_point == ISO8601Point(expected_fcp).standardise()
1508
1509
1510 @pytest.mark.parametrize(
1511 'runtime_cfg',
1512 (
1513 pytest.param(
1514 {'foo': {'remote': {'host': 'bar'}}},
1515 id='no-owners'
1516 ),
1517 pytest.param(
1518 {'foo': {'remote': {'owner': 'tim'}}},
1519 id='one-owner'
1520 ),
1521 pytest.param(
1522 {
1523 'foo': {'remote': {'owner': 'tim'}},
1524 'bar': {'remote': {'owner': 'oliver'}},
1525 'baz': {'remote': {'owner': 'ronnie'}},
1526 },
1527 id='3-owners'
1528 ),
1529 pytest.param(
1530 {
1531 'foo': {'remote': {'owner': 'tim'}},
1532 'bar': {'remote': {'owner': 'oliver'}},
1533 'baz': {'remote': {'owner': 'ronnie'}},
1534 'qux': {'remote': {'owner': 'tim'}},
1535 'aleph': {'remote': {'owner': 'oliver'}},
1536 'bet': {'remote': {'owner': 'ronnie'}},
1537
1538 },
1539 id='6-owners'
1540 ),
1541 )
1542 )
1543 def test_check_for_owner(runtime_cfg):
1544 """check_for_owner raises a list of [runtime][task][remote]owner set."""
1545 if 'owner' in str(runtime_cfg):
1546 with pytest.raises(WorkflowConfigError) as exc:
1547 WorkflowConfig.check_for_owner(runtime_cfg)
1548 # Assert is the correct error message:
1549 assert exc.match('owner\" is obsolete')
1550 # Assert error message has right number of lines:
1551 else:
1552 # Assert function doesn't raise if no owner set:
1553 assert WorkflowConfig.check_for_owner(runtime_cfg) is None
1554
1555
1556 @pytest.fixture(scope='module')
1557 def awe_config(mod_tmp_flow_config: Callable) -> WorkflowConfig:
1558 """Return a workflow config object."""
1559 id_ = 'awe'
1560 flow_file = mod_tmp_flow_config(id_, '''
1561 [scheduling]
1562 cycling mode = integer
1563 [[graph]]
1564 P1 = ordinary & sterling
1565 R1/2 = fra_mauro
1566 [runtime]
1567 [[USA, MOON]]
1568 [[ordinary, sterling]]
1569 inherit = USA
1570 [[fra_mauro]]
1571 inherit = MOON
1572 ''')
1573 return WorkflowConfig(
1574 workflow=id_, fpath=flow_file, options=ValidateOptions()
1575 )
1576
1577
1578 @pytest.mark.parametrize(
1579 'name, expected',
1580 [
1581 pytest.param(
1582 'ordinary', ['ordinary'], id="task name"
1583 ),
1584 pytest.param(
1585 'USA', ['ordinary', 'sterling'], id="family name"
1586 ),
1587 pytest.param(
1588 'fra*', ['fra_mauro'], id="glob task name"
1589 ),
1590 pytest.param(
1591 'U*', ['ordinary', 'sterling'], id="glob family name"
1592 ),
1593 pytest.param(
1594 '*', ['ordinary', 'sterling', 'fra_mauro'], id="glob everything"
1595 ),
1596 pytest.param(
1597 'butte', [], id="no match"
1598 ),
1599 ]
1600 )
1601 def test_find_taskdefs(
1602 name: str, expected: List[str], awe_config: WorkflowConfig
1603 ):
1604 assert sorted(
1605 t.name for t in awe_config.find_taskdefs(name)
1606 ) == sorted(expected)
1607
1608
1609 def test__warn_if_queues_have_implicit_tasks(caplog):
1610 """It Warns that queues imply tasks undefined in runtime.
1611 """
1612 config = {
1613 'scheduling': {'queues': {
1614 'q1': {'members': ['foo']},
1615 'q2': {'members': ['bar', 'baz']}
1616 }},
1617 'runtime': {}
1618 }
1619 taskdefs = {}
1620 max_warning_lines = 2
1621 WorkflowConfig._warn_if_queues_have_implicit_tasks(
1622 config, taskdefs, max_warning_lines)
1623 result = caplog.records[0].message
1624 assert "'foo' in queue 'q1'" in result
1625 assert "'bar' in queue 'q2'" in result
1626 assert "'baz'" not in result
1627 assert f"showing first {max_warning_lines}" in result
1628
1629
1630 @pytest.mark.parametrize(
1631 'installed, run_dir, cylc_vars',
1632 [
1633 pytest.param(
1634 False, # not installed (parsing a source dir)
1635 None, # no run directory passed to config object by scheduler
1636 {
1637 'CYLC_WORKFLOW_NAME': True, # expected environment variables
1638 'CYLC_WORKFLOW_ID': False,
1639 'CYLC_WORKFLOW_RUN_DIR': False,
1640 'CYLC_WORKFLOW_WORK_DIR': False,
1641 'CYLC_WORKFLOW_SHARE_DIR': False,
1642 'CYLC_WORKFLOW_LOG_DIR': False,
1643 },
1644 id="source-dir"
1645 ),
1646 pytest.param(
1647 True,
1648 None,
1649 {
1650 'CYLC_WORKFLOW_NAME': True,
1651 'CYLC_WORKFLOW_ID': True,
1652 'CYLC_WORKFLOW_RUN_DIR': True,
1653 'CYLC_WORKFLOW_WORK_DIR': False,
1654 'CYLC_WORKFLOW_SHARE_DIR': False,
1655 'CYLC_WORKFLOW_LOG_DIR': False,
1656 },
1657 id="run-dir"
1658 ),
1659 pytest.param(
1660 True,
1661 "/some/path",
1662 {
1663 'CYLC_WORKFLOW_NAME': True,
1664 'CYLC_WORKFLOW_ID': True,
1665 'CYLC_WORKFLOW_RUN_DIR': True,
1666 'CYLC_WORKFLOW_WORK_DIR': True,
1667 'CYLC_WORKFLOW_SHARE_DIR': True,
1668 'CYLC_WORKFLOW_LOG_DIR': True,
1669 },
1670 id="run-dir-from-scheduler"
1671 ),
1672 ]
1673 )
1674 def test_cylc_env_at_parsing(
1675 tmp_path: 'Path',
1676 monkeypatch: pytest.MonkeyPatch,
1677 installed,
1678 run_dir,
1679 cylc_vars
1680 ):
1681 """Check that CYLC_ environment vars exported during config file parsing
1682 are appropriate to the workflow context (source, installed, or running).
1683 """
1684
1685 # Purge environment from previous tests.
1686 for key in cylc_vars.keys():
1687 with suppress(KeyError):
1688 del os.environ[key]
1689
1690 flow_file = tmp_path / WorkflowFiles.FLOW_FILE
1691 flow_config = """
1692 [scheduler]
1693 allow implicit tasks = True
1694 [scheduling]
1695 [[graph]]
1696 R1 = 'foo'
1697 """
1698
1699 flow_file.write_text(flow_config)
1700
1701 # Make it look as if path is relative to cylc-run (i.e. installed).
1702 monkeypatch.setattr(
1703 'cylc.flow.config.is_relative_to',
1704 lambda _a, _b: installed
1705 )
1706
1707 # Parse the workflow config then check the environment.
1708 WorkflowConfig(
1709 workflow="name", fpath=flow_file, options=SimpleNamespace(),
1710 run_dir=run_dir
1711 )
1712
1713 cylc_env = [k for k in os.environ.keys() if k.startswith('CYLC_')]
1714
1715 for var, expected in cylc_vars.items():
1716 if expected:
1717 assert var in cylc_env
1718 else:
1719 assert var not in cylc_env
1720
1721
1722 def test_force_workflow_compat_mode(tmp_path):
1723 fpath = (tmp_path / 'flow.cylc')
1724 fpath.write_text(dedent("""
1725 [scheduler]
1726 allow implicit tasks = true
1727 [scheduling]
1728 [[graph]]
1729 R1 = a:succeeded | a:failed => b
1730 """))
1731 # It fails without compat mode:
1732 with pytest.raises(GraphParseError, match='Opposite outputs'):
1733 WorkflowConfig('foo', str(fpath), {})
1734 # It succeeds with compat mode:
1735 WorkflowConfig('foo', str(fpath), {}, force_compat_mode=True)
1736
1737
1738 @pytest.mark.parametrize(
1739 'registered_outputs, tasks_and_outputs, fails',
1740 (
1741 param([], ['foo:x'], True, id='output-unregistered'),
1742 param([], ['foo:x?'], True, id='optional-output-unregistered'),
1743 param([], ['foo'], False, id='no-modifier-unregistered'),
1744 param(['x'], ['foo:x'], False, id='output-registered'),
1745 param([], ['foo:succeed'], False, id='alt-default-ok'),
1746 param([], ['foo:failed'], False, id='default-ok'),
1747 )
1748 )
1749 def test_check_outputs(tmp_path, registered_outputs, tasks_and_outputs, fails):
1750 (tmp_path / 'flow.cylc').write_text(dedent("""
1751 [scheduler]
1752 allow implicit tasks = true
1753 [scheduling]
1754 [[graph]]
1755 R1 = foo
1756 """))
1757 cfg = WorkflowConfig('', tmp_path / 'flow.cylc', '')
1758 cfg.cfg['runtime']['foo']['outputs'] = registered_outputs
1759 if fails:
1760 with pytest.raises(
1761 WorkflowConfigError, match='Undefined custom output'
1762 ):
1763 cfg.check_terminal_outputs(tasks_and_outputs)
1764 else:
1765 assert cfg.check_terminal_outputs(tasks_and_outputs) is None
1766
1767
1768 @pytest.mark.parametrize('back_compat', [True, False])
1769 def test_upg_wflow_event_names(back_compat, tmp_flow_config, log_filter):
1770 """Cylc 7 workflow handler/mail event names are upgraded."""
1771 flags.cylc7_back_compat = back_compat
1772 events = 'inactivity, abort, stalled'
1773 expected = ['inactivity timeout', 'abort', 'stall']
1774 flow_file = tmp_flow_config('foo', f"""
1775 [scheduler]
1776 allow implicit tasks = true
1777 [[events]]
1778 handler events = {events}
1779 mail events = {events}
1780 [scheduling]
1781 [[graph]]
1782 R1 = foo
1783 """)
1784 cfg = WorkflowConfig('foo', str(flow_file), ValidateOptions())
1785 for item in ('handler events', 'mail events'):
1786 assert cfg.cfg['scheduler']['events'][item] == expected
1787 if back_compat:
1788 assert not log_filter(logging.WARNING)
1789 else:
1790 assert log_filter(
1791 logging.WARNING,
1792 'Deprecated config items were automatically upgraded',
1793 )
1794
1795
1796 @pytest.mark.parametrize('item', ['handler events', 'mail events'])
1797 def test_val_wflow_event_names(item, tmp_flow_config, log_filter):
1798 """Any invalid workflow handler/mail events raise a warning."""
1799 flow_file = tmp_flow_config('foo', f"""
1800 [scheduler]
1801 allow implicit tasks = true
1802 [[events]]
1803 {item} = abort, badger, stall, alpaca
1804 [scheduling]
1805 [[graph]]
1806 R1 = foo
1807 """)
1808 WorkflowConfig('foo', str(flow_file), ValidateOptions())
1809 assert log_filter(contains=f"{item} = badger, alpaca")
1810
1811
1812 @pytest.mark.parametrize('item', ['handler events', 'mail events'])
1813 def test_check_task_event_names(item, tmp_flow_config, log_filter):
1814 """"Any invalid task handler events are warned about."""
1815 flow_file = tmp_flow_config('foo', f"""
1816 [scheduling]
1817 [[graph]]
1818 R1 = foo
1819 [runtime]
1820 [[foo]]
1821 [[[events]]]
1822 {item} = submitted, late, warning, custom,\
1823 execution timeout, badger, owl, retry, horse
1824 [[[outputs]]]
1825 owl = who
1826 """)
1827
1828 WorkflowConfig('foo', str(flow_file), ValidateOptions())
1829 assert log_filter(contains=(
1830 f"Invalid event name(s) for [runtime][foo][events]{item}: "
1831 "badger, horse"
1832 ))
1833
1834
1835 def test_jinja2_lib_python(tmp_flow_config):
1836 """Modules in lib/python are available in custom Jinja2."""
1837 flow_file: Path = tmp_flow_config((id_ := 'wflow'), r"""
1838 #!jinja2
1839 {% from 'my_module' import my_const %}
1840 [meta]
1841 x = {{ my_const }}
1842 [scheduler]
1843 allow implicit tasks = true
1844 [scheduling]
1845 [[graph]]
1846 R1 = {{ 'foo' | my_filter }}
1847 """)
1848
1849 (lib_dir := flow_file.parent / 'lib' / 'python').mkdir(parents=True)
1850 (lib_dir / 'my_module.py').write_text(
1851 r"my_const = 'bar'"
1852 )
1853
1854 (filters_dir := flow_file.parent / 'Jinja2Filters').mkdir()
1855 (filters_dir / 'my_filter.py').write_text(
1856 dedent(r"""
1857 from my_module import my_const
1858
1859 def my_filter(val):
1860 return f"{val}_{my_const}"
1861 """)
1862 )
1863
1864 conf = WorkflowConfig(id_, str(flow_file), ValidateOptions())
1865 assert conf.cfg['meta']['x'] == 'bar'
1866 assert conf.cfg['scheduling']['graph']['R1'] == 'foo_bar'