Debian Codegraph @

tests/unit/test_option_parsers.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 redirect_stdout
18 import io
19 import sys
20 from types import SimpleNamespace
21 from typing import List
22
23 import pytest
24 from pytest import param
25
26 import cylc.flow.flags
27 from cylc.flow.option_parsers import (
28 CylcOptionParser as COP, Options, combine_options, combine_options_pair,
29 OptionSettings, cleanup_sysargv, filter_sysargv
30 )
31
32
33 USAGE_WITH_COMMENT = "usage \n # comment"
34 ARGS = 'args'
35 KWARGS = 'kwargs'
36 SOURCES = 'sources'
37 USEIF = 'useif'
38
39
40 @pytest.fixture(scope='module')
41 def parser():
42 return COP(
43 USAGE_WITH_COMMENT,
44 argdoc=[('SOME_ARG', "Description of SOME_ARG")]
45 )
46
47
48 @pytest.mark.parametrize(
49 'args,verbosity',
50 [
51 ([], 0),
52 (['-v'], 1),
53 (['-v', '-v', '-v'], 3),
54 (['-q'], -1),
55 (['-q', '-q', '-q'], -3),
56 (['-q', '-v', '-q'], -1),
57 (['--debug'], 2),
58 (['--debug', '-q'], 1),
59 (['--debug', '-v'], 3),
60 ]
61 )
62 def test_verbosity(
63 args: List[str],
64 verbosity: int,
65 parser: COP, monkeypatch: pytest.MonkeyPatch
66 ) -> None:
67 """-v, -q, --debug should be additive."""
68 # patch the cylc.flow.flags value so that it gets reset after the test
69 monkeypatch.setattr('cylc.flow.flags.verbosity', None)
70 opts, args = parser.parse_args(['default-arg'] + args)
71 assert opts.verbosity == verbosity
72 # test side-effect, the verbosity flag should be set
73 assert cylc.flow.flags.verbosity == verbosity
74
75
76 def test_help_color(monkeypatch: pytest.MonkeyPatch, parser: COP):
77 """Test for colorized comments in 'cylc cmd --help --color=always'."""
78 # This colorization is done on the fly when help is printed.
79 monkeypatch.setattr("sys.argv", ['cmd', 'foo', '--color=always'])
80 parser.parse_args(None)
81 assert parser.values.color == "always"
82 f = io.StringIO()
83 with redirect_stdout(f):
84 parser.print_help()
85 assert not (f.getvalue()).startswith("Usage: " + USAGE_WITH_COMMENT)
86
87
88 def test_help_nocolor(monkeypatch: pytest.MonkeyPatch, parser: COP):
89 """Test for no colorization in 'cylc cmd --help --color=never'."""
90 # This colorization is done on the fly when help is printed.
91 monkeypatch.setattr(sys, "argv", ['cmd', 'foo', '--color=never'])
92 parser.parse_args(None)
93 assert parser.values.color == "never"
94 f = io.StringIO()
95 with redirect_stdout(f):
96 parser.print_help()
97 assert (f.getvalue()).startswith("Usage: " + USAGE_WITH_COMMENT)
98
99
100 def test_Options_std_opts():
101 """Test Python Options API with standard options."""
102 parser = COP(USAGE_WITH_COMMENT, auto_add=True)
103 MyOptions = Options(parser)
104 MyValues = MyOptions(verbosity=1)
105 assert MyValues.verbosity == 1
106
107
108 # Add overlapping args tomorrow
109 @pytest.mark.parametrize(
110 'first, second, expect',
111 [
112 param(
113 [{ARGS: ['-f', '--foo'], KWARGS: {}, SOURCES: {'do'}}],
114 [{ARGS: ['-f', '--foo'], KWARGS: {}, SOURCES: {'dont'}}],
115 (
116 [{
117 ARGS: ['-f', '--foo'], KWARGS: {},
118 SOURCES: {'do', 'dont'}, USEIF: ''
119 }]
120 ),
121 id='identical arg lists unchanged'
122 ),
123 param(
124 [{ARGS: ['-f', '--foo'], KWARGS: {}, SOURCES: {'fall'}}],
125 [{
126 ARGS: ['-f', '--foolish'],
127 KWARGS: {'help': 'not identical'},
128 SOURCES: {'fold'}}],
129 (
130 [
131 {
132 ARGS: ['--foo'], KWARGS: {}, SOURCES: {'fall'},
133 USEIF: ''
134 },
135 {
136 ARGS: ['--foolish'],
137 KWARGS: {'help': 'not identical'},
138 SOURCES: {'fold'},
139 USEIF: ''
140 }
141 ]
142 ),
143 id='different arg lists lose shared names'
144 ),
145 param(
146 [{ARGS: ['-f', '--foo'], KWARGS: {}, SOURCES: {'cook'}}],
147 [{
148 ARGS: ['-f', '--foo'],
149 KWARGS: {'help': 'not identical', 'dest': 'foobius'},
150 SOURCES: {'bake'},
151 USEIF: ''
152 }],
153 None,
154 id='different args identical arg list cause exception'
155 ),
156 param(
157 [{ARGS: ['-g', '--goo'], KWARGS: {}, SOURCES: {'knit'}}],
158 [{ARGS: ['-f', '--foo'], KWARGS: {}, SOURCES: {'feed'}}],
159 [
160 {
161 ARGS: ['-g', '--goo'], KWARGS: {},
162 SOURCES: {'knit'}, USEIF: ''
163 },
164 {
165 ARGS: ['-f', '--foo'], KWARGS: {},
166 SOURCES: {'feed'}, USEIF: ''
167 },
168 ],
169 id='all unrelated args added'
170 ),
171 param(
172 [
173 {ARGS: ['-f', '--foo'], KWARGS: {}, SOURCES: {'work'}},
174 {ARGS: ['-r', '--redesdale'], KWARGS: {}, SOURCES: {'work'}}
175 ],
176 [
177 {ARGS: ['-f', '--foo'], KWARGS: {}, SOURCES: {'sink'}},
178 {
179 ARGS: ['-b', '--buttered-peas'],
180 KWARGS: {}, SOURCES: {'sink'}
181 }
182 ],
183 [
184 {
185 ARGS: ['-f', '--foo'],
186 KWARGS: {},
187 SOURCES: {'work', 'sink'},
188 USEIF: ''
189 },
190 {
191 ARGS: ['-b', '--buttered-peas'],
192 KWARGS: {},
193 SOURCES: {'sink'},
194 USEIF: ''
195 },
196 {
197 ARGS: ['-r', '--redesdale'],
198 KWARGS: {},
199 SOURCES: {'work'},
200 USEIF: ''
201 },
202 ],
203 id='do not repeat args'
204 ),
205 param(
206 [
207 {
208 ARGS: ['-f', '--foo'],
209 KWARGS: {},
210 SOURCES: {'push'}
211 },
212 ],
213 [],
214 [
215 {
216 ARGS: ['-f', '--foo'],
217 KWARGS: {},
218 SOURCES: {'push'},
219 USEIF: ''
220 },
221 ],
222 id='one empty list is fine'
223 )
224 ]
225 )
226 def test_combine_options_pair(first, second, expect):
227 """It combines sets of options"""
228 first = [
229 OptionSettings(i[ARGS], sources=i[SOURCES], **i[KWARGS])
230 for i in first
231 ]
232 second = [
233 OptionSettings(i[ARGS], sources=i[SOURCES], **i[KWARGS])
234 for i in second
235 ]
236 if expect is not None:
237 result = combine_options_pair(first, second)
238 assert [i.__dict__ for i in result] == expect
239 else:
240 with pytest.raises(Exception, match='Clashing Options'):
241 combine_options_pair(first, second)
242
243
244 @pytest.mark.parametrize(
245 'inputs, expect',
246 [
247 param(
248 [
249 ([OptionSettings(
250 ['-i', '--inflammable'], help='', sources={'wish'}
251 )]),
252 ([OptionSettings(
253 ['-f', '--flammable'], help='', sources={'rest'}
254 )]),
255 ([OptionSettings(
256 ['-n', '--non-flammable'], help='', sources={'swim'}
257 )]),
258 ],
259 [
260 {ARGS: ['-i', '--inflammable']},
261 {ARGS: ['-f', '--flammable']},
262 {ARGS: ['-n', '--non-flammable']}
263 ],
264 id='merge three argsets no overlap'
265 ),
266 param(
267 [
268 [
269 OptionSettings(
270 ['-m', '--morpeth'], help='', sources={'stop'}),
271 OptionSettings(
272 ['-r', '--redesdale'], help='', sources={'stop'}),
273 ],
274 [
275 OptionSettings(
276 ['-b', '--byker'], help='', sources={'walk'}),
277 OptionSettings(
278 ['-r', '--roxborough'], help='', sources={'walk'}),
279 ],
280 [
281 OptionSettings(
282 ['-b', '--bellingham'], help='', sources={'leap'}),
283 ]
284 ],
285 [
286 {ARGS: ['--bellingham']},
287 {ARGS: ['--roxborough']},
288 {ARGS: ['--redesdale']},
289 {ARGS: ['--byker']},
290 {ARGS: ['-m', '--morpeth']}
291 ],
292 id='merge three overlapping argsets'
293 ),
294 param(
295 [
296 ([]),
297 (
298 [
299 OptionSettings(
300 ['-c', '--campden'], help='x', sources={'foo'})
301 ]
302 )
303 ],
304 [
305 {ARGS: ['-c', '--campden']}
306 ],
307 id="empty list doesn't clear result"
308 ),
309 ]
310 )
311 def test_combine_options(inputs, expect):
312 """It combines multiple input sets"""
313 result = combine_options(*inputs)
314 result_args = [i.args for i in result]
315
316 # Order of args irrelevent to test
317 for option in expect:
318 assert option[ARGS] in result_args
319
320
321 @pytest.mark.parametrize(
322 'argv_before, kwargs, expect',
323 [
324 param(
325 'vip myworkflow -f something -b something_else --baz',
326 {
327 'script_name': 'play',
328 'workflow_id': 'myworkflow',
329 'compound_script_opts': [
330 OptionSettings(['--foo', '-f']),
331 OptionSettings(['--bar', '-b'], action='store'),
332 OptionSettings(['--baz'], action='store_true'),
333 ],
334 'script_opts': [
335 OptionSettings(['--foo', '-f']),
336 ]
337 },
338 'play myworkflow -f something',
339 id='remove some opts'
340 ),
341 param(
342 'vip myworkflow',
343 {
344 'script_name': 'play',
345 'workflow_id': 'myworkflow',
346 'compound_script_opts': [
347 OptionSettings(['--foo', '-f']),
348 OptionSettings(['--bar', '-b']),
349 OptionSettings(['--baz']),
350 ],
351 'script_opts': []
352 },
353 'play myworkflow',
354 id='no opts to keep'
355 ),
356 param(
357 'vip ./myworkflow --foo something',
358 {
359 'script_name': 'play',
360 'workflow_id': 'myworkflow',
361 'compound_script_opts': [
362 OptionSettings(['--foo', '-f'])],
363 'script_opts': [
364 OptionSettings(['--foo', '-f']),
365 ],
366 'source': './myworkflow',
367 },
368 'play --foo something myworkflow',
369 id='replace path'
370 ),
371 param(
372 'vip --foo something',
373 {
374 'script_name': 'play',
375 'workflow_id': 'myworkflow',
376 'compound_script_opts': [
377 OptionSettings(['--foo', '-f'])],
378 'script_opts': [
379 OptionSettings(['--foo', '-f']),
380 ],
381 'source': './myworkflow',
382 },
383 'play --foo something myworkflow',
384 id='no path given'
385 ),
386 param(
387 'vip -n myworkflow --no-run-name',
388 {
389 'script_name': 'play',
390 'workflow_id': 'myworkflow',
391 'compound_script_opts': [
392 OptionSettings(['--workflow-name', '-n']),
393 OptionSettings(['--no-run-name']),
394 ],
395 'script_opts': [
396 OptionSettings(['--not-used']),
397 ]
398 },
399 'play myworkflow',
400 id='workflow-id-added'
401 ),
402 ]
403 )
404 def test_cleanup_sysargv(
405 monkeypatch: pytest.MonkeyPatch,
406 argv_before: str,
407 kwargs: dict,
408 expect: str
409 ):
410 """It replaces the contents of sysargv with Cylc Play argv items.
411 """
412 # Fake up sys.argv: for this test.
413 dummy_cylc_path = ['/pathto/my/cylc/bin/cylc']
414 monkeypatch.setattr(sys, 'argv', dummy_cylc_path + argv_before.split())
415 # Fake options too:
416 opts = SimpleNamespace(**{
417 i.args[0].replace('--', ''): i for i in kwargs['compound_script_opts']
418 })
419
420 kwargs.update({'options': opts})
421 if not kwargs.get('source', None):
422 kwargs.update({'source': ''})
423
424 # Test the script:
425 cleanup_sysargv(**kwargs)
426 assert sys.argv == dummy_cylc_path + expect.split()
427
428
429 @pytest.mark.parametrize(
430 'sysargs, simple, compound, expect', (
431 param(
432 # Test for https://github.com/cylc/cylc-flow/issues/5905
433 '--no-run-name --workflow-name=name'.split(),
434 ['--no-run-name'],
435 ['--workflow-name'],
436 [],
437 id='--workflow-name=name'
438 ),
439 param(
440 '--foo something'.split(),
441 [], [], '--foo something'.split(),
442 id='no-opts-removed'
443 ),
444 param(
445 [], ['--foo'], ['--bar'], [],
446 id='Null-check'
447 ),
448 param(
449 '''--keep1 --keep2 42 --keep3=Hi
450 --throw1 --throw2 84 --throw3=There
451 '''.split(),
452 ['--throw1'],
453 '--throw2 --throw3'.split(),
454 '--keep1 --keep2 42 --keep3=Hi'.split(),
455 id='complex'
456 ),
457 param(
458 "--foo 'foo=42' --bar='foo=94'".split(),
459 [], ['--foo'],
460 ['--bar=\'foo=94\''],
461 id='--bar=\'foo=94\''
462 )
463 )
464 )
465 def test_filter_sysargv(
466 sysargs, simple, compound, expect
467 ):
468 """It returns the subset of sys.argv that we ask for.
469
470 n.b. The three most basic cases for this function are stored in
471 its own docstring.
472 """
473 assert filter_sysargv(sysargs, simple, compound) == expect
474
475
476 class TestOptionSettings():
477 @staticmethod
478 def test_init():
479 args = ['--foo', '-f']
480 kwargs = {'bar': 42}
481 sources = {'touch'}
482 useif = 'hello'
483
484 result = OptionSettings(
485 args, sources=sources, useif=useif, **kwargs)
486
487 assert result.__dict__ == {
488 'kwargs': kwargs, 'sources': sources,
489 'useif': useif, 'args': args
490 }
491
492 @staticmethod
493 @pytest.mark.parametrize(
494 'first, second, expect',
495 (
496 param(
497 (['--foo', '-f'], {'bar': 42}, {'touch'}, 'hello'),
498 (['--foo', '-f'], {'bar': 42}, {'touch'}, 'hello'),
499 True, id='Totally the same'),
500 param(
501 (['--foo', '-f'], {'bar': 42}, {'touch'}, 'hello'),
502 (['--foo', '-f'], {'bar': 42}, {'wibble'}, 'byee'),
503 True, id='Differing extras'),
504 param(
505 (['-f'], {'bar': 42}, {'touch'}, 'hello'),
506 (['--foo', '-f'], {'bar': 42}, {'wibble'}, 'byee'),
507 False, id='Not equal args'),
508 )
509 )
510 def test___eq__args_intersection(first, second, expect):
511 args, kwargs, sources, useif = first
512 first = OptionSettings(
513 args, sources=sources, useif=useif, **kwargs)
514 args, kwargs, sources, useif = second
515 second = OptionSettings(
516 args, sources=sources, useif=useif, **kwargs)
517 assert (first == second) == expect
518
519 @staticmethod
520 @pytest.mark.parametrize(
521 'first, second, expect',
522 (
523 param(
524 ['--foo', '-f'],
525 ['--foo', '-f'],
526 ['--foo', '-f'],
527 id='Totally the same'),
528 param(
529 ['--foo', '-f'],
530 ['--foolish', '-f'],
531 ['-f'],
532 id='Some overlap'),
533 param(
534 ['--foo', '-f'],
535 ['--bar', '-b'],
536 [],
537 id='No overlap'),
538 )
539 )
540 def test___and__(first, second, expect):
541 first = OptionSettings(first)
542 second = OptionSettings(second)
543 assert sorted(first & second) == sorted(expect)
544
545 @staticmethod
546 @pytest.mark.parametrize(
547 'first, second, expect',
548 (
549 param(
550 ['--foo', '-f'],
551 ['--foo', '-f'],
552 [],
553 id='Totally the same'),
554 param(
555 ['--foo', '-f'],
556 ['--foolish', '-f'],
557 ['--foo'],
558 id='Some overlap'),
559 param(
560 ['--foolish', '-f'],
561 ['--foo', '-f'],
562 ['--foolish'],
563 id='Some overlap not commuting'),
564 param(
565 ['--foo', '-f'],
566 ['--bar', '-b'],
567 ['--foo', '-f'],
568 id='No overlap'),
569 )
570 )
571 def test___sub__args_subtraction(first, second, expect):
572 first = OptionSettings(first)
573 second = OptionSettings(second)
574 assert sorted(first - second) == sorted(expect)
575
576 @staticmethod
577 def test__in_list():
578 """It is in a list."""
579 first = OptionSettings(['--foo'])
580 second = OptionSettings(['--foo'])
581 third = OptionSettings(['--bar'])
582 assert first._in_list([second, third]) is True