Debian Codegraph @

tests/u/test_param_expand.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 unittest
18 import pytest
19 from pytest import param
20
21 from cylc.flow.exceptions import ParamExpandError
22 from cylc.flow.param_expand import NameExpander, GraphExpander
23
24
25 class TestParamExpand(unittest.TestCase):
26 """Unit tests for the parameter expansion module."""
27
28 def setUp(self):
29 """Create some parameters and templates for use in tests."""
30 params_map = {'a': [-3, -1], 'i': [0, 1], 'j': [0, 1, 2], 'k': [0, 1]}
31 # k has template is deliberately bad
32 templates = {
33 'a': '_a%(a)d', 'i': '_i%(i)d', 'j': '_j%(j)d', 'k': '_k%(z)d'}
34 self.name_expander = NameExpander((params_map, templates))
35 self.graph_expander = GraphExpander((params_map, templates))
36
37 def test_name_one_param(self):
38 """Test name expansion and returned value for a single parameter."""
39 self.assertEqual(
40 self.name_expander.expand('foo<j>'),
41 [('foo_j0', {'j': 0}),
42 ('foo_j1', {'j': 1}),
43 ('foo_j2', {'j': 2})]
44 )
45
46 def test_name_two_params(self):
47 """Test name expansion and returned values for two parameters."""
48 self.assertEqual(
49 self.name_expander.expand('foo<i,j>'),
50 [('foo_i0_j0', {'i': 0, 'j': 0}),
51 ('foo_i0_j1', {'i': 0, 'j': 1}),
52 ('foo_i0_j2', {'i': 0, 'j': 2}),
53 ('foo_i1_j0', {'i': 1, 'j': 0}),
54 ('foo_i1_j1', {'i': 1, 'j': 1}),
55 ('foo_i1_j2', {'i': 1, 'j': 2})]
56 )
57
58 def test_name_two_names(self):
59 """Test name expansion for two names."""
60 self.assertEqual(
61 self.name_expander.expand('foo<i>, bar<j>'),
62 [('foo_i0', {'i': 0}),
63 ('foo_i1', {'i': 1}),
64 ('bar_j0', {'j': 0}),
65 ('bar_j1', {'j': 1}),
66 ('bar_j2', {'j': 2})]
67 )
68
69 def test_name_specific_val_1(self):
70 """Test singling out a specific value, in name expansion."""
71 self.assertEqual(
72 self.name_expander.expand('foo<i=0>'),
73 [('foo_i0', {'i': 0})]
74 )
75
76 def test_name_specific_val_2(self):
77 """Test specific value in the first parameter of a pair."""
78 self.assertEqual(
79 self.name_expander.expand('foo<i=0,j>'),
80 [('foo_i0_j0', {'i': 0, 'j': 0}),
81 ('foo_i0_j1', {'i': 0, 'j': 1}),
82 ('foo_i0_j2', {'i': 0, 'j': 2})]
83 )
84
85 def test_name_specific_val_3(self):
86 """Test specific value in the second parameter of a pair."""
87 self.assertEqual(
88 self.name_expander.expand('foo<i,j=1>'),
89 [('foo_i0_j1', {'i': 0, 'j': 1}),
90 ('foo_i1_j1', {'i': 1, 'j': 1})]
91 )
92
93 def test_name_fail_bare_value(self):
94 """Test foo<0,j> fails."""
95 # It should be foo<i=0,j>.
96 self.assertRaises(ParamExpandError,
97 self.name_expander.expand, 'foo<0,j>')
98
99 def test_name_fail_undefined_param(self):
100 """Test that an undefined parameter gets failed."""
101 # m is not defined.
102 self.assertRaises(ParamExpandError,
103 self.name_expander.expand, 'foo<m,j>')
104
105 def test_name_fail_param_value_too_high(self):
106 """Test that an out-of-range parameter gets failed."""
107 # i stops at 3.
108 self.assertRaises(ParamExpandError,
109 self.name_expander.expand, 'foo<i=4,j>')
110
111 def test_name_multiple(self):
112 """Test expansion of two names, with one and two parameters."""
113 self.assertEqual(
114 self.name_expander.expand('foo<i>, bar<i,j>'),
115 [('foo_i0', {'i': 0}),
116 ('foo_i1', {'i': 1}),
117 ('bar_i0_j0', {'i': 0, 'j': 0}),
118 ('bar_i0_j1', {'i': 0, 'j': 1}),
119 ('bar_i0_j2', {'i': 0, 'j': 2}),
120 ('bar_i1_j0', {'i': 1, 'j': 0}),
121 ('bar_i1_j1', {'i': 1, 'j': 1}),
122 ('bar_i1_j2', {'i': 1, 'j': 2})]
123 )
124
125 def test_graph_expand_1(self):
126 """Test graph expansion with two parameters each side of an arrow."""
127 self.assertEqual(
128 self.graph_expander.expand("bar<i,j>=>baz<i,j>"),
129 set(["bar_i0_j1=>baz_i0_j1",
130 "bar_i1_j2=>baz_i1_j2",
131 "bar_i0_j2=>baz_i0_j2",
132 "bar_i1_j1=>baz_i1_j1",
133 "bar_i1_j0=>baz_i1_j0",
134 "bar_i0_j0=>baz_i0_j0"])
135 )
136
137 def test_graph_expand_2(self):
138 """Test graph expansion to 'branch and merge' a workflow."""
139 self.assertEqual(
140 self.graph_expander.expand("pre=>bar<i>=>baz<i,j>=>post"),
141 set(["pre=>bar_i0=>baz_i0_j1=>post",
142 "pre=>bar_i1=>baz_i1_j2=>post",
143 "pre=>bar_i0=>baz_i0_j2=>post",
144 "pre=>bar_i1=>baz_i1_j1=>post",
145 "pre=>bar_i1=>baz_i1_j0=>post",
146 "pre=>bar_i0=>baz_i0_j0=>post"])
147 )
148
149 def test_graph_expand_3(self):
150 """Test graph expansion -ve integers."""
151 self.assertEqual(
152 self.graph_expander.expand("bar<a>"),
153 set(["bar_a-1", "bar_a-3"]))
154
155 def test_graph_expand_offset_1(self):
156 """Test graph expansion with a -ve offset."""
157 self.assertEqual(
158 self.graph_expander.expand("bar<i-1,j>=>baz<i,j>"),
159 set(["bar_i-32768_j0=>baz_i0_j0",
160 "bar_i-32768_j1=>baz_i0_j1",
161 "bar_i-32768_j2=>baz_i0_j2",
162 "bar_i0_j0=>baz_i1_j0",
163 "bar_i0_j1=>baz_i1_j1",
164 "bar_i0_j2=>baz_i1_j2"])
165 )
166
167 def test_graph_expand_offset_2(self):
168 """Test graph expansion with a +ve offset."""
169 self.assertEqual(
170 self.graph_expander.expand("baz<i>=>baz<i+1>"),
171 set(["baz_i0=>baz_i1",
172 "baz_i1=>baz_i-32768"])
173 )
174
175 def test_graph_expand_specific(self):
176 """Test graph expansion with a specific value."""
177 self.assertEqual(
178 self.graph_expander.expand("bar<i=1,j>=>baz<i,j>"),
179 set(["bar_i1_j0=>baz_i0_j0",
180 "bar_i1_j1=>baz_i0_j1",
181 "bar_i1_j2=>baz_i0_j2",
182 "bar_i1_j0=>baz_i1_j0",
183 "bar_i1_j1=>baz_i1_j1",
184 "bar_i1_j2=>baz_i1_j2"])
185 )
186
187 def test_graph_fail_bare_value(self):
188 """Test that a bare parameter value fails in the graph."""
189 self.assertRaises(ParamExpandError,
190 self.graph_expander.expand, 'foo<0,j>=>bar<i,j>')
191
192 def test_graph_fail_undefined_param(self):
193 """Test that an undefined parameter value fails in the graph."""
194 self.assertRaises(ParamExpandError,
195 self.graph_expander.expand, 'foo<m,j>=>bar<i,j>')
196
197 def test_graph_fail_param_value_too_high(self):
198 """Test that an out-of-range parameter value fails in the graph."""
199 self.assertRaises(ParamExpandError,
200 self.graph_expander.expand, 'foo<i=4,j><i,j>')
201
202 def test_template_fail_missing_param(self):
203 """Test a template string specifying a non-existent parameter."""
204 self.assertRaises(
205 ParamExpandError, self.name_expander.expand, 'foo<k>')
206 self.assertRaises(
207 ParamExpandError, self.graph_expander.expand, 'foo<k>')
208
209 @staticmethod
210 def _param_expand_params():
211 """Test data for test_parameter_graph_mixing_offset_and_conditional.
212
213 params_map, templates, expanded_str, expanded_values
214 params_map : map of parameters used in the graph expression
215 templates : parameters template
216 expanded_str : graph string, using params/template
217 expanded_values: values expected to exist after params expanded
218 """
219 return (
220 # original case from #2608
221 (
222 {'m': ["cat", "dog"]},
223 {'m': '_%(m)s'},
224 "foo<m-1> & baz => foo<m>",
225 [
226 'foo_-32768 & baz => foo_cat',
227 'foo_cat & baz => foo_dog'
228 ]
229 ),
230 # cases from comments from #2608
231 # see cylc/cylc-flow/pull/3452#issuecomment-670782800
232 (
233 # single element, so bar<m-1> does not exist
234 {'m': ["cat"]},
235 {'m': '_%(m)s'},
236 "foo & bar<m-1> & baz => qux",
237 [
238 "foo & bar_-32768 & baz => qux"
239 ]
240 ),
241 # cases from comments from #2608
242 # see cylc/cylc-flow/pull/3452#issuecomment-670776749
243 (
244 {'m': ["1", "2"]},
245 {'m': '_%(m)s'},
246 "foo<m-1> => bar<m> => baz",
247 [
248 "foo_-32768 => bar_1 => baz",
249 "foo_1 => bar_2 => baz"
250 ]
251 ),
252 # cases from comments from #2608
253 # see cylc/cylc-flow/pull/3452#discussion_r430967867
254 (
255 {'m': ["cat", "dog"]},
256 {'m': '_%(m)s'},
257 "baz & foo<m-1> & pub => foo<m>",
258 [
259 "baz & foo_-32768 & pub => foo_cat",
260 "baz & foo_cat & pub => foo_dog"
261 ]
262 ),
263 (
264 {'m': ["cat", "dog"]},
265 {'m': '_%(m)s'},
266 "bar & foo<m-1> & pub<m-1> & qux => foo<m>",
267 [
268 "bar & foo_-32768 & pub_-32768 & qux => foo_cat",
269 "bar & foo_cat & pub_cat & qux => foo_dog"
270 ]
271 ),
272 # GraphParser strips spaces!
273 (
274 {'m': ["cat"]},
275 {'m': '_%(m)s'},
276 "foo&bar<m-1>&baz=>qux",
277 [
278 "foo&bar_-32768&baz=>qux"
279 ]
280 ),
281 (
282 {'m': ["cat", "dog"]},
283 {'m': '_%(m)s'},
284 "foo&bar<m-1>&baz=>qux",
285 [
286 "foo&bar_-32768&baz=>qux",
287 "foo&bar_cat&baz=>qux"
288 ]
289 ),
290 # must support & and | in graph expressions
291 (
292 {'m': ["cat", "dog"]},
293 {'m': '_%(m)s'},
294 "foo|bar<m-1>|baz=>qux",
295 [
296 "foo|bar_-32768|baz=>qux",
297 "foo|bar_cat|baz=>qux"
298 ]
299 ),
300 (
301 {'m': ["cat", "dog"]},
302 {'m': '_%(m)s'},
303 "foo&bar<m-1>|baz=>qux",
304 [
305 "foo&bar_-32768|baz=>qux",
306 "foo&bar_cat|baz=>qux"
307 ]
308 ),
309 (
310 {'m': ["cat", "dog"]},
311 {'m': '_%(m)s'},
312 "foo&bar<m-1>|baz=>qux",
313 [
314 "foo&bar_-32768|baz=>qux",
315 "foo&bar_cat|baz=>qux"
316 ]
317 ),
318 (
319 {'m': ["cat"]},
320 {'m': '_%(m)s'},
321 "foo => bar<m-1> => baz",
322 [
323 "foo=>bar_-32768=>baz"
324 ]
325 )
326 )
327
328 def test_parameter_graph_mixing_offset_and_conditional(self):
329 """Test for bug reported in issue #2608 on GitHub."""
330 for test_case in self._param_expand_params():
331 params_map, templates, expanded_str, expanded_values = \
332 test_case
333 graph_expander = GraphExpander((params_map, templates))
334 # Ignore white spaces.
335 expanded = [expanded.replace(' ', '') for expanded in
336 graph_expander.expand(expanded_str)]
337 self.assertEqual(
338 len(expanded_values),
339 len(expanded),
340 f"Invalid length for expected {expanded_values} and "
341 f"{expanded}")
342 # When testing, we don't really care for white spaces,as they
343 # are removed in the GraphParser anyway. That's why we have
344 # ''.replace(' ', '').
345 for expected in expanded_values:
346 self.assertTrue(
347 expected.replace(' ', '') in expanded,
348 f"Expected value {expected.replace(' ', '')} "
349 f"not in {expanded}")
350
351
352 class myParam():
353 def __init__(
354 self, raw_str,
355 parameter_values=None, templates=None, raises=None,
356 id_=None,
357 expect=None,
358 ):
359 """Ease of reading wrapper for pytest.param
360
361 Args:
362 expect:
363 Output of expand_parent_params()
364 raw_str:
365 The parent_params input string.
366 parameter_values
367 """
368 parameter_values = parameter_values if parameter_values else {}
369 templates = templates if templates else {}
370 self.raises = raises
371 self.expect = expect
372 self.raw_str = raw_str
373 self.parameter_values = parameter_values
374 self.templates = templates
375 self.parameters = ((parameter_values, templates))
376 self.name_expander = NameExpander(self.parameters)
377 self.id_ = 'raises:' + id_ if raises else id_
378
379 def get(self):
380 return param(self, id=self.id_)
381
382
383 @pytest.mark.parametrize(
384 "param",
385 (
386 myParam(
387 expect=(None, 'no_params_here'),
388 raw_str='no_params_here',
389 id_='basic'
390 ).get(),
391 myParam(
392 expect=({'bar': 1}, 'bar1'),
393 raw_str='<bar>',
394 parameter_values={'bar': 1},
395 templates={'bar': 'bar%(bar)s'},
396 id_='one-valid_-param'
397 ).get(),
398 myParam(
399 expect=({'bar': 1}, 'foo_bar1_baz'),
400 raw_str='foo<bar>baz',
401 parameter_values={'bar': 1},
402 templates={'bar': '_bar%(bar)s_'},
403 id_='one-valid_-param'
404 ).get(),
405 myParam(
406 raw_str='foo<bar>baz',
407 parameter_values={'qux': 2},
408 templates={'bar': '_bar%(bar)s_'},
409 raises=(ParamExpandError, 'parameter \'bar\' undefined'),
410 id_='one-invalid_-param'
411 ).get(),
412 myParam(
413 expect=({'bar': 1, 'baz': 42}, 'foo_bar1_baz42'),
414 raw_str='foo<bar, baz>',
415 parameter_values={'bar': 1, 'baz': 42},
416 templates={'bar': '_bar%(bar)s', 'baz': '_baz%(baz)s'},
417 id_='two-valid_-param'
418 ).get(),
419 myParam(
420 expect=({'bar': 1, 'baz': 42}, 'foo_bar1qux_baz42'),
421 raw_str='foo<bar>qux<baz>',
422 parameter_values={'bar': 1, 'baz': 42},
423 templates={'bar': '_bar%(bar)s', 'baz': '_baz%(baz)s'},
424 id_='two-valid_-param-sep-brackets',
425 ).get(),
426 myParam(
427 raw_str='foo<bar-1>baz',
428 raises=(ParamExpandError, '^parameter offsets illegal here'),
429 id_='offsets-illegal'
430 ).get(),
431 myParam(
432 expect=({'bar': 1}, 'foo_bar1_baz'),
433 raw_str='foo<bar=1>baz',
434 parameter_values={'bar': [1, 2]},
435 templates={'bar': '_bar%(bar)s_'},
436 id_='value-set'
437 ).get(),
438 myParam(
439 raw_str='foo<bar=3>baz',
440 parameter_values={'bar': [1, 2]},
441 raises=(ParamExpandError, '^illegal'),
442 id_='illegal-value'
443 ).get(),
444 myParam(
445 expect=({'bar': 1}, 'foo_bar1_baz'),
446 raw_str='foo<bar=3>baz',
447 raises=(ParamExpandError, '^parameter \'bar\' undefined'),
448 id_='parameter-undefined'
449 ).get(),
450 )
451 )
452 def test_expand_parent_params(param):
453 if not param.raises:
454 # Good Path tests:
455 result = param.name_expander.expand_parent_params(
456 param.raw_str, param.parameter_values, 'Errortext')
457 assert result == param.expect
458 else:
459 # Bad path tests:
460 with pytest.raises(param.raises[0], match=param.raises[1]):
461 param.name_expander.expand_parent_params(
462 param.raw_str, param.parameter_values, 'Errortext')