Debian Codegraph @

tests/u/test_graph_parser.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 """Unit tests for the GraphParser."""
17
18 import logging
19 from typing import Dict, List
20 import pytest
21 from itertools import product
22 from pytest import param
23 from types import SimpleNamespace
24
25 from cylc.flow import CYLC_LOG
26 from cylc.flow.exceptions import GraphParseError, ParamExpandError
27 from cylc.flow.graph_parser import GraphParser
28 from cylc.flow.task_outputs import (
29 TASK_OUTPUT_SUBMITTED,
30 TASK_OUTPUT_STARTED,
31 TASK_OUTPUT_SUCCEEDED,
32 TASK_OUTPUT_FAILED
33 )
34
35
36 @pytest.mark.parametrize(
37 'graph',
38 [
39 't1 => & t2',
40 't1 => t2 &',
41 '& t1 => t2',
42 't1 & => t2',
43 't1 => => t2'
44 ]
45 )
46 def test_parse_graph_fails_null_task_name(graph):
47 """Test fail null task names."""
48 with pytest.raises(GraphParseError) as cm:
49 GraphParser().parse_graph(graph)
50 assert "Null task name in graph:" in str(cm.value)
51
52
53 @pytest.mark.parametrize('seq', ('&', '|', '=>'))
54 @pytest.mark.parametrize(
55 'graph, expected_err',
56 [
57 [
58 "{0} b",
59 "Leading {0}"
60 ],
61 [
62 "a {0}",
63 "Dangling {0}"
64 ],
65 [
66 "{0} b {0} c",
67 "Leading {0}"
68 ],
69 [
70 "a {0} b {0}",
71 "Dangling {0}"
72 ]
73 ]
74 )
75 def test_graph_syntax_errors_2(seq, graph, expected_err):
76 """Test various graph syntax errors."""
77 graph = graph.format(seq)
78 expected_err = expected_err.format(seq)
79 with pytest.raises(GraphParseError) as cm:
80 GraphParser().parse_graph(graph)
81 assert (
82 expected_err in str(cm.value)
83 )
84
85
86 @pytest.mark.parametrize(
87 'graph, expected_err',
88 [
89 (
90 "a b => c",
91 "Bad graph node format"
92 ),
93 (
94 "a => b c",
95 "Bad graph node format"
96 ),
97 (
98 "!foo => bar",
99 "Suicide markers must be on the right of a trigger:"
100 ),
101 (
102 "( foo & bar => baz",
103 'Mismatched parentheses in: "(foo&bar"'
104 ),
105 (
106 "a => b & c)",
107 'Mismatched parentheses in: "b&c)"'
108 ),
109 (
110 "(a => b & c)",
111 'Mismatched parentheses in: "(a"'
112 ),
113 (
114 "(a => b[+P1]",
115 'Mismatched parentheses in: "(a"'
116 ),
117 (
118 """(a | b & c) => d
119 foo => bar
120 (a | b & c) => !d""",
121 "can't trigger both d and !d"
122 ),
123 (
124 "a => b | c",
125 "Illegal OR on right side"
126 ),
127 (
128 "foo && bar => baz",
129 "The graph AND operator is '&'"
130 ),
131 (
132 "foo || bar => baz",
133 "The graph OR operator is '|'"
134 ),
135 param(
136 # See https://github.com/cylc/cylc-flow/issues/5844
137 "foo => bar[1649]",
138 'Invalid cycle point offsets only on right',
139 id='no-cycle-point-RHS'
140 ),
141 # See https://github.com/cylc/cylc-flow/issues/6523
142 # For the next 4 tests:
143 # NB "foo:succeeded" now explicit on the right (this used to test
144 # inferred "foo:succeeded" from "=> foo", which we no longer infer).
145 param(
146 # Yes I know it's circular, but it's here to
147 # demonstrate that the test below is broken:
148 "foo:finished => foo:succeeded",
149 'Output foo:succeeded can\'t be both required and optional',
150 id='finish-implies-success-optional'
151 ),
152 param(
153 "foo[-P1]:finish => foo:succeeded",
154 'Output foo:succeeded can\'t be both required and optional',
155 id='finish-implies-success-optional-offset'
156 ),
157 param(
158 "foo[-P1]:succeeded | foo[-P1]:failed => bar",
159 # order of outputs varies in the error message
160 'must both be optional if both are used',
161 id='succeed-or-failed-mustbe-optional'
162 ),
163 param(
164 "foo[-P1]:succeeded? | foo[-P1]:failed? => foo:succeeded",
165 'Output foo:succeeded can\'t be both required and optional',
166 id='succeed-or-failed-implies-success-optional'
167 ),
168 ]
169 )
170 def test_graph_syntax_errors(graph, expected_err):
171 """Test various graph syntax errors."""
172 with pytest.raises(GraphParseError) as cm:
173 GraphParser().parse_graph(graph)
174 assert expected_err in str(cm.value)
175
176
177 def test_parse_graph_simple():
178 """Test parsing graphs."""
179 # added white spaces and comments to show that these change nothing
180
181 gp = GraphParser()
182 gp.parse_graph('a => b\n \n# this is a comment\n')
183
184 original = gp.original
185 triggers = gp.triggers
186 families = gp.family_map
187
188 assert (
189 original == {'a': {'': ''}, 'b': {'a:succeeded': 'a:succeeded'}}
190 )
191
192 assert (
193 triggers == {
194 'a': {'': ([], False)},
195 'b': {'a:succeeded': (['a:succeeded'], False)}
196 }
197 )
198 assert not families
199
200
201 @pytest.mark.parametrize(
202 'graph, expect',
203 [
204 param(
205 'a => b\n=> c',
206 SimpleNamespace(
207 original={
208 'c': {'b:succeeded': 'b:succeeded'},
209 'b': {'a:succeeded': 'a:succeeded'},
210 'a': {'': ''}
211 },
212 triggers={
213 'c': {'b:succeeded': (['b:succeeded'], False)},
214 'b': {'a:succeeded': (['a:succeeded'], False)},
215 'a': {'': ([], False)}
216 },
217 families={}
218 ),
219 id='line break on =>'
220 ),
221 param(
222 'a & b\n& c',
223 SimpleNamespace(
224 original={'b': {'': ''}, 'a': {'': ''}, 'c': {'': ''}},
225 triggers={
226 'b': {'': ([], False)},
227 'a': {'': ([], False)},
228 'c': {'': ([], False)}
229 },
230 families={}
231 ),
232 id='line break on &'
233 ),
234 param(
235 'a | b\n| c',
236 SimpleNamespace(
237 original={'b': {'': ''}, 'c': {'': ''}, 'a': {'': ''}},
238 triggers={
239 'b': {'': ([], False)},
240 'c': {'': ([], False)},
241 'a': {'': ([], False)}
242 },
243 families={}
244 ),
245 id='line break on |'
246 )
247 ]
248 )
249 def test_parse_graph_simple_with_break_line_01(graph, expect):
250 """Test parsing graphs."""
251 parser = GraphParser()
252 parser.parse_graph(graph)
253 assert parser.original == expect.original
254 assert parser.triggers == expect.triggers
255 assert not parser.family_map
256
257
258 def test_parse_graph_simple_with_break_line_02():
259 """Test parsing graphs."""
260 gp = GraphParser()
261 gp.parse_graph(
262 'a => b\n'
263 '=> c =>\n'
264 'd'
265 )
266 original = gp.original
267 triggers = gp.triggers
268 families = gp.family_map
269
270 assert original['a'] == {'': ''}
271 assert original['b'] == {'a:succeeded': 'a:succeeded'}
272 assert original['c'] == {'b:succeeded': 'b:succeeded'}
273 assert original['d'] == {'c:succeeded': 'c:succeeded'}
274
275 assert triggers['a'] == {'': ([], False)}
276 assert triggers['b'] == {'a:succeeded': (['a:succeeded'], False)}
277 assert triggers['c'] == {'b:succeeded': (['b:succeeded'], False)}
278 assert triggers['d'] == {'c:succeeded': (['c:succeeded'], False)}
279
280 assert not families
281
282
283 def test_parse_graph_with_parameters():
284 """Test parsing graphs with parameters."""
285 parameterized_parser = GraphParser(
286 None, ({'city': ['la_paz']}, {'city': '_%(city)s'}))
287 parameterized_parser.parse_graph('a => b<city>')
288 original = parameterized_parser.original
289 triggers = parameterized_parser.triggers
290 families = parameterized_parser.family_map
291 assert (
292 original == {'a': {'': ''}, 'b_la_paz': {'a:succeeded': 'a:succeeded'}}
293 )
294 assert (
295 triggers == {
296 'a': {'': ([], False)},
297 'b_la_paz': {'a:succeeded': (['a:succeeded'], False)}
298 }
299 )
300 assert not families
301
302
303 def test_parse_graph_with_invalid_parameters():
304 """Test parsing graphs with invalid parameters."""
305 parameterized_parser = GraphParser(
306 None, ({'city': ['la_paz']}, {'city': '_%(city)s'}))
307 with pytest.raises(ParamExpandError):
308 # no state in the parameters list
309 parameterized_parser.parse_graph('a => b<state>')
310
311
312 def test_inter_workflow_dependence_simple():
313 """Test invalid inter-workflow dependence"""
314 gp = GraphParser()
315 gp.parse_graph(
316 """
317 a<WORKFLOW::TASK:fail> => b
318 c<WORKFLOW::TASK> => d
319 """
320 )
321 assert (
322 gp.original ==
323 {
324 'a': {'': ''},
325 'b': {'a:succeeded': 'a:succeeded'},
326 'c': {'': ''},
327 'd': {'c:succeeded': 'c:succeeded'}
328 }
329 )
330 assert (
331 gp.triggers == {
332 'a': {'': ([], False)},
333 'c': {'': ([], False)},
334 'b': {'a:succeeded': (['a:succeeded'], False)},
335 'd': {'c:succeeded': (['c:succeeded'], False)}
336 }
337 )
338 assert (
339 gp.workflow_state_polling_tasks == {
340 'a': (
341 'WORKFLOW', 'TASK', 'failed', '<WORKFLOW::TASK:fail>'
342 ),
343 # Default to "succeeded" is done in config module.
344 'c': (
345 'WORKFLOW', 'TASK', None, '<WORKFLOW::TASK>'
346 )
347 }
348 )
349 assert not gp.family_map
350
351
352 def test_line_continuation():
353 """Test syntax-driven line continuation."""
354 graph1 = "a => b => c"
355 graph2 = """a =>
356 b => c"""
357 graph3 = """a => b
358 => c"""
359 gp1 = GraphParser()
360 gp1.parse_graph(graph1)
361 gp2 = GraphParser()
362 gp2.parse_graph(graph2)
363 gp3 = GraphParser()
364 gp3.parse_graph(graph3)
365 res = {
366 'a': {'': ([], False)},
367 'c': {'b:succeeded': (['b:succeeded'], False)},
368 'b': {'a:succeeded': (['a:succeeded'], False)}
369 }
370 assert res == gp1.triggers
371 assert gp1.triggers == gp2.triggers
372 assert gp1.triggers == gp3.triggers
373 graph = """foo => bar
374 a => b =>"""
375 gp = GraphParser()
376 pytest.raises(GraphParseError, gp.parse_graph, graph)
377 graph = """ => a => b
378 foo => bar"""
379 gp = GraphParser()
380 pytest.raises(GraphParseError, gp.parse_graph, graph)
381
382
383 @pytest.mark.parametrize(
384 'graph1, graph2',
385 [
386 [
387 "foo => bar", # default trigger
388 "foo:succeed => bar"
389 ],
390 [
391 "foo => bar", # default trigger
392 "foo:succeeded => bar"
393 ],
394
395 [
396 "foo => bar", # repeat trigger
397 """foo => bar
398 foo => bar"""
399 ],
400 [
401 "foo:finished => bar", # finish trigger
402 "(foo:succeed? | foo:fail?) => bar"
403 ],
404 [
405 """
406 bar
407 foo => bar:succeed => baz # ignore qualifier on RHS
408 """,
409 """
410 foo => bar
411 bar:succeed => baz
412 """
413 ],
414 [
415 """
416 foo => bar[1649] => baz
417 """,
418 """
419 foo => bar[1649]
420 bar[1649] => baz
421 """
422 ],
423 ]
424 )
425 def test_trigger_equivalence(graph1, graph2):
426 gp1 = GraphParser()
427 gp1.parse_graph(graph1)
428 gp2 = GraphParser()
429 gp2.parse_graph(graph2)
430 assert gp1.triggers == gp2.triggers
431
432
433 @pytest.mark.parametrize(
434 'fam_map, fam_graph, member_graph',
435 [
436 [
437 {'FAM': ['m1', 'm2'], 'BAM': ['b1', 'b2']},
438 "FAM:succeed-all => BAM",
439 """(m1 & m2) => b1
440 (m1 & m2) => b2"""
441 ],
442 [
443 {'FAM': ['m1', 'm2']},
444 "pre => FAM",
445 """pre => m1
446 pre => m2"""
447 ],
448 [
449 {'FAM': ['m1', 'm2']},
450 "FAM:succeed-all => post",
451 "(m1 & m2) => post"
452 ],
453 [
454 {'FAM': ['m1', 'm2']},
455 "FAM:succeed-any => post",
456 "(m1 | m2) => post",
457 ],
458 [
459 {'FAM': ['m1', 'm2'], 'BAM': ['b1', 'b2']},
460 "FAM:fail-any => BAM",
461 """(m1:fail | m2:fail) => b1
462 (m1:fail | m2:fail) => b2"""
463 ],
464 [
465 {'FAM': ['m1', 'm2']},
466 "FAM:finish-all => post",
467 "((m1? | m1:fail?) & (m2? | m2:fail?)) => post"
468 ]
469 ]
470 )
471 def test_family_trigger_equivalence(fam_map, fam_graph, member_graph):
472 """Test family trigger semantics."""
473 gp1 = GraphParser(fam_map)
474 gp1.parse_graph(fam_graph)
475 gp2 = GraphParser()
476 gp2.parse_graph(member_graph)
477 assert gp1.triggers == gp2.triggers
478
479
480 def test_parameter_expand():
481 """Test graph parameter expansion."""
482 fam_map = {
483 'FAM_m0': ['fa_m0', 'fb_m0'],
484 'FAM_m1': ['fa_m1', 'fb_m1'],
485 }
486 params = {'m': ['0', '1'], 'n': ['0', '1']}
487 templates = {'m': '_m%(m)s', 'n': '_n%(n)s'}
488 gp1 = GraphParser(fam_map, (params, templates))
489 gp1.parse_graph("""
490 pre => foo<m,n> => bar<n>
491 bar<n=0> => baz # specific case
492 bar<n-1> => bar<n> # inter-chunk
493 """)
494 gp2 = GraphParser()
495 gp2.parse_graph("""
496 pre => foo_m0_n0 => bar_n0
497 pre => foo_m0_n1 => bar_n1
498 pre => foo_m1_n0 => bar_n0
499 pre => foo_m1_n1 => bar_n1
500 bar_n0 => baz
501 bar_n0 => bar_n1
502 """)
503 assert gp1.triggers == gp2.triggers
504
505
506 def test_parameter_specific():
507 """Test graph parameter expansion with a specific value."""
508 params = {'i': ['0', '1'], 'j': ['0', '1', '2']}
509 templates = {'i': '_i%(i)s', 'j': '_j%(j)s'}
510 gp1 = GraphParser(family_map=None, parameters=(params, templates))
511 gp1.parse_graph("bar<i-1,j> => baz<i,j>\nfoo<i=1,j> => qux")
512 gp2 = GraphParser()
513 gp2.parse_graph("""
514 foo_i1_j0 => qux
515 foo_i1_j1 => qux
516 foo_i1_j2 => qux
517 bar_i0_j0 => baz_i1_j0
518 bar_i0_j1 => baz_i1_j1
519 bar_i0_j2 => baz_i1_j2""")
520 assert gp1.triggers == gp2.triggers
521
522
523 def test_parameter_offset():
524 """Test graph parameter expansion with an offset."""
525 params = {'i': ['0', '1'], 'j': ['0', '1', '2']}
526 templates = {'i': '_i%(i)s', 'j': '_j%(j)s'}
527 gp1 = GraphParser(family_map=None, parameters=(params, templates))
528 gp1.parse_graph("bar<i-1,j> => baz<i,j>")
529 gp2 = GraphParser()
530 gp2.parse_graph("""
531 bar_i0_j0 => baz_i1_j0
532 bar_i0_j1 => baz_i1_j1
533 bar_i0_j2 => baz_i1_j2""")
534 assert gp1.triggers == gp2.triggers
535
536
537 def test_conditional():
538 """Test generation of conditional triggers."""
539 gp1 = GraphParser()
540 gp1.parse_graph("(foo:start | bar) => baz")
541 res = {
542 'baz': {
543 '(foo:started|bar:succeeded)': (
544 ['foo:started', 'bar:succeeded'], False)
545 },
546 'foo': {
547 '': ([], False)
548 },
549 'bar': {
550 '': ([], False)
551 }
552 }
553 assert res == gp1.triggers == res
554
555
556 @pytest.mark.parametrize(
557 'graph',
558 [
559 "foo[-P1Y]<m,n> => bar",
560 "foo:fail<m,n> => bar",
561 "foo:fail[-P1Y] => bar",
562 "foo[-P1Y]:fail<m,n> => bar",
563 "foo[-P1Y]<m,n>:fail => bar",
564 "foo<m,n>:fail[-P1Y] => bar",
565 "foo:fail<m,n>[-P1Y] => bar",
566 "<m,n>:fail[-P1Y] => bar",
567 "[-P1Y]<m,n> => bar",
568 "[-P1Y]<m,n>:fail => bar",
569 "bar => foo:fail<m,n>[-P1Y]",
570 "foo[-P1Y]baz => bar"
571 ]
572 )
573 def test_bad_node_syntax(graph):
574 """Test that badly formatted graph nodes are detected.
575
576 The correct format is:
577 NAME(<PARAMS>)([CYCLE-POINT-OFFSET])(:TRIGGER-TYPE)")
578 """
579 params = {'m': ['0', '1'], 'n': ['0', '1']}
580 templates = {'m': '_m%(m)s', 'n': '_n%(n)s'}
581 gp = GraphParser(parameters=(params, templates))
582 with pytest.raises(GraphParseError) as cm:
583 gp.parse_graph(graph)
584 assert "Bad graph node format" in str(cm.value)
585
586
587 def test_spaces_between_tasks_fails():
588 """Test that <task> <task> is rejected (i.e. no & or | in between)"""
589 gp = GraphParser()
590 pytest.raises(
591 GraphParseError, gp.parse_graph, "foo bar=> baz")
592 pytest.raises(
593 GraphParseError, gp.parse_graph, "foo&bar=> ba z")
594 pytest.raises(
595 GraphParseError, gp.parse_graph, "foo 123=> bar")
596 pytest.raises(
597 GraphParseError, gp.parse_graph, "foo - 123 baz=> bar")
598
599
600 def test_spaces_between_parameters_fails():
601 """Test that <param param> are rejected (i.e. no comma)"""
602 gp = GraphParser()
603 pytest.raises(
604 GraphParseError, gp.parse_graph, "<foo bar> => baz")
605 pytest.raises(
606 GraphParseError, gp.parse_graph, "<foo=a _bar> => baz")
607 pytest.raises(
608 GraphParseError, gp.parse_graph, "<foo=a_ bar> => baz")
609
610
611 def test_spaces_between_parameters_passes():
612 """Test that <param-1> works, with spaces around the -+ signs"""
613 params = {'m': ['0', '1', '2']}
614 templates = {'m': '_m%(m)s'}
615 gp = GraphParser(parameters=(params, templates))
616 gp.parse_graph("<m- 1> => <m>")
617 gp.parse_graph("<m -1> => <m>")
618 gp.parse_graph("<m - 1> => <m>")
619 gp.parse_graph("<m+ 1> => <m>")
620 gp.parse_graph("<m +1> => <m>")
621 gp.parse_graph("<m + 1> => <m>")
622
623
624 def test_spaces_in_trigger_fails():
625 """Test that 'task:a- b' are rejected"""
626 gp = GraphParser()
627 pytest.raises(
628 GraphParseError, gp.parse_graph, "FOO:custom -trigger => baz")
629 pytest.raises(
630 GraphParseError, gp.parse_graph, "FOO:custom- trigger => baz")
631 pytest.raises(
632 GraphParseError, gp.parse_graph, "FOO:custom - trigger => baz")
633
634
635 def test_parameter_graph_mixing_offset_and_conditional():
636 """Test for bug reported in issue #2608 on GitHub:
637 https://github.com/cylc/cylc-flow/issues/2608"""
638 params = {'m': ["cat", "dog"]}
639 templates = {'m': '_%(m)s'}
640 gp = GraphParser(parameters=(params, templates))
641 gp.parse_graph("foo<m-1> & baz => foo<m>")
642 triggers = {
643 'foo_cat': {
644 '': (
645 [], False
646 ),
647 'baz:succeeded': (
648 ['baz:succeeded'], False
649 )
650 },
651 'foo_dog': {
652 'foo_cat:succeeded': (
653 ['foo_cat:succeeded'], False
654 ),
655 'baz:succeeded': (
656 ['baz:succeeded'], False
657 )
658 },
659 'baz': {
660 '': ([], False)
661 }
662 }
663 assert gp.triggers == triggers
664
665
666 def test_param_expand_graph_parser():
667 """Test to validate that the graph parser removes out-of-edge nodes:
668 https://github.com/cylc/cylc-flow/pull/3452#issuecomment-677165000"""
669 params = {'m': ["cat"]}
670 templates = {'m': '_%(m)s'}
671 gp = GraphParser(parameters=(params, templates))
672 gp.parse_graph("foo => bar<m-1> => baz")
673 triggers = {
674 'foo': {
675 '': ([], False)
676 }
677 }
678 assert gp.triggers == triggers
679
680
681 @pytest.mark.parametrize(
682 'expect', ('&', '|', '=>')
683 )
684 def test_parse_graph_fails_with_continuation_at_last_line(expect):
685 """Fails if last line contains a continuation char.
686 """
687 parser = GraphParser()
688 with pytest.raises(GraphParseError) as raised:
689 parser.parse_graph(f't1 => t2 {expect}')
690 assert isinstance(raised.value, GraphParseError)
691 assert f'Dangling {expect}' in raised.value.args[0]
692
693
694 @pytest.mark.parametrize(
695 'before, after',
696 product(['&', '|', '=>'], repeat=2)
697 )
698 def test_parse_graph_fails_with_too_many_continuations(before, after):
699 """Fails if one line ends with continuation char and the next line
700 _also_ starts with one.
701 """
702 parser = GraphParser()
703 with pytest.raises(GraphParseError) as raised:
704 parser.parse_graph(f'foo & bar {before}\n{after}baz')
705 assert isinstance(raised.value, GraphParseError)
706 assert 'Consecutive lines end and start' in raised.value.args[0]
707
708
709 def test_task_optional_outputs():
710 """Test optional outputs are correctly parsed from graph.
711
712 This checks "task_output_opt" dict which holds output optionality inferred
713 from the graph. Note since https://github.com/cylc/cylc-flow/pull/6999
714 we no longer infer optionality from *implicit* outputs on RHS of triggers,
715 i.e. "a => b" does not imply b:succeeded is a required output.
716
717 """
718 OPTIONAL = True
719 REQUIRED = False
720 gp = GraphParser()
721 gp.parse_graph(
722 """
723 a1 => b1 # does not imply b1:succeeded ...
724 a2:succeed => b2:succeeded
725 a3:succeed => b3:succeed
726
727 c1? => d1?
728 c2:succeed? => d2?
729 c3:succeed? => d3:succeed?
730
731 x:fail? => y
732
733 foo:finish => bar
734 """
735 )
736 for i in range(1, 4):
737 for task in (f'a{i}', f'b{i}'):
738 if task != "b1":
739 assert (
740 gp.task_output_opt[(task, TASK_OUTPUT_SUCCEEDED)]
741 == (REQUIRED, False, True)
742 )
743
744 for task in (f'c{i}', f'd{i}'):
745 assert (
746 gp.task_output_opt[(task, TASK_OUTPUT_SUCCEEDED)]
747 == (OPTIONAL, True, True)
748 )
749
750 assert (
751 gp.task_output_opt[('x', TASK_OUTPUT_FAILED)]
752 == (OPTIONAL, True, True)
753 )
754
755 assert (
756 gp.task_output_opt[('foo', TASK_OUTPUT_SUCCEEDED)]
757 == (OPTIONAL, True, True)
758 )
759
760 assert (
761 gp.task_output_opt[('foo', TASK_OUTPUT_FAILED)]
762 == (OPTIONAL, True, True)
763 )
764
765
766 @pytest.mark.parametrize(
767 'qual, task_output',
768 [
769 ('start', TASK_OUTPUT_STARTED),
770 ('succeed', TASK_OUTPUT_SUCCEEDED),
771 ('fail', TASK_OUTPUT_FAILED),
772 ('submit', TASK_OUTPUT_SUBMITTED),
773 ]
774 )
775 def test_family_optional_outputs(qual, task_output):
776 """Test member output optionality inferred from family triggers."""
777 fam_map = {
778 'FAM': ['f1', 'f2'],
779 'BAM': ['b1', 'b2'],
780 }
781 gp = GraphParser(fam_map)
782 gp.parse_graph(
783 f"""
784 # required
785 FAM:{qual}-all => foo
786 # optional member
787 f2:{task_output}?
788
789 # required
790 BAM:{qual}-any => bar
791 """
792 )
793 # -all
794 for member in ['f1', 'f2']:
795 optional = (member == 'f2')
796 assert gp.task_output_opt[(member, task_output)][0] == optional
797 # -any
798 optional = False
799 for member in ['b1', 'b2']:
800 assert gp.task_output_opt[(member, task_output)][0] == optional
801
802
803 def test_cannot_be_required():
804 """Is should not allow :expired or :submit-failed to be required.
805
806 See proposal point 4:
807 https://cylc.github.io/cylc-admin/proposal-optional-output-extension.html#proposal
808 """
809 gp = GraphParser({})
810
811 # outputs can be optional
812 gp.parse_graph('a:expired? => b')
813 gp.parse_graph('a:submit-failed? => b')
814
815 # but cannot be required
816 with pytest.raises(GraphParseError, match='must be optional'):
817 gp.parse_graph('a:expired => b')
818 with pytest.raises(GraphParseError, match='must be optional'):
819 gp.parse_graph('a:submit-failed => b')
820
821
822 @pytest.mark.parametrize(
823 'graph, error',
824 [
825 [
826 """FAM:succeed-all => foo
827 FAM:fail-all => foo""",
828 ("must both be optional if both are used (via family trigger"
829 " defaults")
830 ],
831 [
832 """FAM:succeed-all => foo
833 FAM:succeed-any? => bar""",
834 ("can't default to both optional and required (via family trigger"
835 " defaults)")
836 ],
837 [
838 "FAM:blargh-all => foo", # LHS
839 "Illegal family trigger"
840 ],
841 [
842 "foo => FAM:blargh-all", # RHS
843 "Illegal family trigger"
844 ],
845 [
846 "FAM => foo", # bare family on LHS
847 "Family trigger required: FAM => foo"
848 ],
849 [
850 "FAM:expire-all => foo",
851 "must be optional"
852 ],
853 ]
854 )
855 def test_family_trigger_errors(graph, error):
856 """Test errors via bad family triggers and member output optionality."""
857 fam_map = {
858 'FAM': ['f1', 'f2']
859 }
860 gp = GraphParser(fam_map)
861
862 with pytest.raises(GraphParseError) as cm:
863 gp.parse_graph(graph)
864 assert error in str(cm.value)
865
866
867 @pytest.mark.parametrize(
868 'graph, c8error',
869 [
870 [
871 """a:x => b
872 a:x? => c""",
873 "Output a:x can't be both required and optional",
874 ],
875 [
876 """a? => c
877 a => b""",
878 "Output a:succeeded can't be both required and optional",
879 ],
880 [
881 """a => c
882 a:fail => b""",
883 ("must both be optional if both are used"),
884 ],
885 [
886 """a:fail? => b
887 a => c""",
888 ("must both be optional if both are used"),
889 ],
890 [
891 "a:finish? => b",
892 "Pseudo-output a:finished can't be optional",
893 ],
894 [
895 "a:expire => b",
896 "must be optional",
897 ],
898 ]
899 )
900 def test_task_optional_output_errors_order(
901 graph, c8error,
902 caplog: pytest.LogCaptureFixture,
903 monkeypatch: pytest.MonkeyPatch
904 ):
905 """Test optional output errors are raised as expected."""
906 gp = GraphParser()
907 with pytest.raises(GraphParseError) as cm:
908 gp.parse_graph(graph)
909 assert c8error in str(cm.value)
910
911 # In Cylc 7 back compat mode these graphs should all pass with no warnings.
912 monkeypatch.setattr('cylc.flow.flags.cylc7_back_compat', True)
913 caplog.set_level(logging.WARNING, CYLC_LOG)
914 gp = GraphParser()
915 gp.parse_graph(graph)
916
917 # No warnings logged:
918 assert not caplog.messages
919
920 # After graph parsing all Cylc 7 back compat outputs should be optional.
921 # (Success outputs are set to required later, in taskdef processing.)
922 for (optional, _, _) in gp.task_output_opt.values():
923 assert optional
924
925
926 @pytest.mark.parametrize(
927 'ftrig',
928 GraphParser.fam_to_mem_trigger_map.keys()
929 )
930 def test_fail_family_triggers_on_tasks(ftrig):
931 gp = GraphParser()
932 with pytest.raises(GraphParseError) as cm:
933 gp.parse_graph(f"foo:{ftrig} => bar")
934 assert (
935 str(cm.value).startswith(
936 "family trigger on non-family namespace"
937 )
938 )
939
940
941 @pytest.mark.parametrize(
942 'graph, expected_triggers',
943 [
944 param(
945 'a => b & c',
946 {'a': [''], 'b': ['a:succeeded'], 'c': ['a:succeeded']},
947 id="simple"
948 ),
949 param(
950 'a => (b & c)',
951 {'a': [''], 'b': ['a:succeeded'], 'c': ['a:succeeded']},
952 id="simple w/ parentheses"
953 ),
954 param(
955 'a => (b & (c & d))',
956 {
957 'a': [''],
958 'b': ['a:succeeded'],
959 'c': ['a:succeeded'],
960 'd': ['a:succeeded'],
961 },
962 id="more parentheses"
963 ),
964 ]
965 )
966 def test_RHS_AND(graph: str, expected_triggers: Dict[str, List[str]]):
967 """Test '&' operator on right hand side of trigger expression."""
968 gp = GraphParser()
969 gp.parse_graph(graph)
970 triggers = {
971 task: list(trigs.keys())
972 for task, trigs in gp.triggers.items()
973 }
974 assert triggers == expected_triggers
975
976
977 @pytest.mark.parametrize(
978 'args, err',
979 (
980 # No error if offset in NON-terminal RHS:
981 param((('a', 'b[-P42M]'), {}, set(), set()), None),
982 # Check the left hand side if this has a non-terminal RHS:
983 param(
984 (('a &', 'b[-P42M]'), {}, set(), set()), 'Null task name in graph'
985 ),
986 ),
987 )
988 def test_proc_dep_pair(args, err):
989 """
990 Unit tests for _proc_dep_pair.
991 """
992 gp = GraphParser()
993 if err:
994 with pytest.raises(GraphParseError, match=err):
995 gp._proc_dep_pair(*args)
996 else:
997 assert gp._proc_dep_pair(*args) is None