Debian Codegraph @

tests/parser_parser.py

raw
1 from pytest import raises
2
3 from invoke.parser import Argument, Context, ParseError, Parser
4
5
6 class Parser_:
7 def can_take_initial_context(self) -> None:
8 c = Context()
9 p = Parser(initial=c)
10 assert p.initial == c
11
12 def can_take_initial_and_other_contexts(self) -> None:
13 c1 = Context("foo")
14 c2 = Context("bar")
15 p = Parser(initial=Context(), contexts=[c1, c2])
16 assert p.contexts["foo"] == c1
17 assert p.contexts["bar"] == c2
18
19 def can_take_just_other_contexts(self) -> None:
20 c = Context("foo")
21 p = Parser(contexts=[c])
22 assert p.contexts["foo"] == c
23
24 def can_take_just_contexts_as_non_keyword_arg(self) -> None:
25 c = Context("foo")
26 p = Parser([c])
27 assert p.contexts["foo"] == c
28
29 def raises_ValueError_for_unnamed_Contexts_in_contexts(self) -> None:
30 with raises(ValueError):
31 Parser(initial=Context(), contexts=[Context()])
32
33 def raises_error_for_context_name_clashes(self) -> None:
34 with raises(ValueError):
35 Parser(contexts=(Context("foo"), Context("foo")))
36
37 def raises_error_for_context_alias_and_name_clashes(self) -> None:
38 with raises(ValueError):
39 Parser((Context("foo", aliases=("bar",)), Context("bar")))
40
41 def raises_error_for_context_name_and_alias_clashes(self) -> None:
42 # I.e. inverse of the above, which is a different code path.
43 with raises(ValueError):
44 Parser((Context("foo"), Context("bar", aliases=("foo",))))
45
46 def takes_ignore_unknown_kwarg(self) -> None:
47 Parser(ignore_unknown=True)
48
49 def ignore_unknown_defaults_to_False(self) -> None:
50 assert Parser().ignore_unknown is False
51
52 class parse_argv:
53 def parses_sys_argv_style_list_of_strings(self) -> None:
54 "parses sys.argv-style list of strings"
55 # Doesn't-blow-up tests FTL
56 mytask = Context(name="mytask")
57 mytask.add_arg("arg")
58 p = Parser(contexts=[mytask])
59 p.parse_argv(["mytask", "--arg", "value"])
60
61 def returns_only_contexts_mentioned(self) -> None:
62 task1 = Context("mytask")
63 task2 = Context("othertask")
64 result = Parser((task1, task2)).parse_argv(["othertask"])
65 assert len(result) == 1
66 assert result[0].name == "othertask"
67
68 def raises_error_if_unknown_contexts_found(self) -> None:
69 with raises(ParseError):
70 Parser().parse_argv(["foo", "bar"])
71
72 def unparsed_does_not_share_state(self) -> None:
73 r = Parser(ignore_unknown=True).parse_argv(["self"])
74 assert r.unparsed == ["self"]
75 r2 = Parser(ignore_unknown=True).parse_argv(["contained"])
76 assert r.unparsed == ["self"] # NOT ['self', 'contained']
77 assert r2.unparsed == ["contained"] # NOT ['self', 'contained']
78
79 def ignore_unknown_returns_unparsed_argv_instead(self) -> None:
80 r = Parser(ignore_unknown=True).parse_argv(["foo", "bar", "--baz"])
81 assert r.unparsed == ["foo", "bar", "--baz"]
82
83 def ignore_unknown_does_not_mutate_rest_of_argv(self) -> None:
84 p = Parser([Context("ugh")], ignore_unknown=True)
85 r = p.parse_argv(["ugh", "what", "-nowai"])
86 # NOT: ['what', '-n', '-w', '-a', '-i']
87 assert r.unparsed == ["what", "-nowai"]
88
89 def always_includes_initial_context_if_one_was_given(self) -> None:
90 # Even if no core/initial flags were seen
91 t1 = Context("t1")
92 init = Context()
93 result = Parser((t1,), initial=init).parse_argv(["t1"])
94 assert result[0].name is None
95 assert result[1].name == "t1"
96
97 def returned_contexts_are_in_order_given(self) -> None:
98 t1, t2 = Context("t1"), Context("t2")
99 r = Parser((t1, t2)).parse_argv(["t2", "t1"])
100 assert [x.name for x in r] == ["t2", "t1"]
101
102 def returned_context_member_arguments_contain_given_values(
103 self,
104 ) -> None:
105 c = Context("mytask", args=(Argument("boolean", kind=bool),))
106 result = Parser((c,)).parse_argv(["mytask", "--boolean"])
107 assert result[0].args["boolean"].value is True
108
109 def inverse_bools_get_set_correctly(self) -> None:
110 arg = Argument("myarg", kind=bool, default=True)
111 c = Context("mytask", args=(arg,))
112 r = Parser((c,)).parse_argv(["mytask", "--no-myarg"])
113 assert r[0].args["myarg"].value is False
114
115 def arguments_which_take_values_get_defaults_overridden_correctly(
116 self,
117 ) -> None: # noqa
118 args = (Argument("arg", kind=str), Argument("arg2", kind=int))
119 c = Context("mytask", args=args)
120 argv = ["mytask", "--arg", "myval", "--arg2", "25"]
121 result = Parser((c,)).parse_argv(argv)
122 assert result[0].args["arg"].value == "myval"
123 assert result[0].args["arg2"].value == 25
124
125 def returned_arguments_not_given_contain_default_values(self) -> None:
126 # I.e. a Context with args A and B, invoked with no mention of B,
127 # should result in B existing in the result, with its default value
128 # intact, and not e.g. None, or the arg not existing.
129 a = Argument("name", kind=str)
130 b = Argument("age", default=7)
131 c = Context("mytask", args=(a, b))
132 Parser((c,)).parse_argv(["mytask", "--name", "blah"])
133 assert c.args["age"].value == 7
134
135 def returns_remainder(self) -> None:
136 "returns -- style remainder string chunk"
137 r = Parser((Context("foo"),)).parse_argv(
138 ["foo", "--", "bar", "biz"]
139 )
140 assert r.remainder == "bar biz"
141
142 def clones_initial_context(self) -> None:
143 a = Argument("foo", kind=bool)
144 assert a.value is None
145 c = Context(args=(a,))
146 p = Parser(initial=c)
147 assert p.initial is c
148 r = p.parse_argv(["--foo"])
149 assert p.initial is c
150 c2 = r[0]
151 assert c2 is not c
152 a2 = c2.args["foo"]
153 assert a2 is not a
154 assert a.value is None
155 assert a2.value is True
156
157 def clones_noninitial_contexts(self) -> None:
158 a = Argument("foo")
159 assert a.value is None
160 c = Context(name="mytask", args=(a,))
161 p = Parser(contexts=(c,))
162 assert p.contexts["mytask"] is c
163 r = p.parse_argv(["mytask", "--foo", "val"])
164 assert p.contexts["mytask"] is c
165 c2 = r[0]
166 assert c2 is not c
167 a2 = c2.args["foo"]
168 assert a2 is not a
169 assert a.value is None
170 assert a2.value == "val"
171
172 class parsing_errors:
173 def setup_method(self) -> None:
174 self.p = Parser([Context(name="foo", args=[Argument("bar")])])
175
176 def missing_flag_values_raise_ParseError(self) -> None:
177 with raises(ParseError):
178 self.p.parse_argv(["foo", "--bar"])
179
180 def attaches_context_to_ParseErrors(self) -> None:
181 try:
182 self.p.parse_argv(["foo", "--bar"])
183 except ParseError as e:
184 assert e.context is not None
185
186 def attached_context_is_None_outside_contexts(self) -> None:
187 try:
188 Parser().parse_argv(["wat"])
189 except ParseError as e:
190 assert e.context is None
191
192 class positional_arguments:
193 def _basic(self) -> Parser:
194 arg = Argument("pos", positional=True)
195 mytask = Context(name="mytask", args=[arg])
196 return Parser(contexts=[mytask])
197
198 def single_positional_arg(self) -> None:
199 r = self._basic().parse_argv(["mytask", "posval"])
200 assert r[0].args["pos"].value == "posval"
201
202 def omitted_positional_arg_raises_ParseError(self) -> None:
203 try:
204 self._basic().parse_argv(["mytask"])
205 except ParseError as e:
206 expected = "'mytask' did not receive required positional arguments: 'pos'" # noqa
207 assert str(e) == expected
208 else:
209 assert False, "Did not raise ParseError!"
210
211 def omitted_positional_args_raises_ParseError(self) -> None:
212 try:
213 arg = Argument("pos", positional=True)
214 arg2 = Argument("morepos", positional=True)
215 mytask = Context(name="mytask", args=[arg, arg2])
216 Parser(contexts=[mytask]).parse_argv(["mytask"])
217 except ParseError as e:
218 expected = "'mytask' did not receive required positional arguments: 'pos', 'morepos'" # noqa
219 assert str(e) == expected
220 else:
221 assert False, "Did not raise ParseError!"
222
223 def positional_args_eat_otherwise_valid_context_names(
224 self,
225 ) -> None:
226 mytask = Context(
227 "mytask",
228 args=[
229 Argument("pos", positional=True),
230 Argument("nonpos", default="default"),
231 ],
232 )
233 Context("lolwut")
234 result = Parser([mytask]).parse_argv(["mytask", "lolwut"])
235 r = result[0]
236 assert r.args["pos"].value == "lolwut"
237 assert r.args["nonpos"].value == "default"
238 assert len(result) == 1 # Not 2
239
240 def positional_args_can_still_be_given_as_flags(self) -> None:
241 # AKA "positional args can come anywhere in the context"
242 pos1 = Argument("pos1", positional=True)
243 pos2 = Argument("pos2", positional=True)
244 nonpos = Argument("nonpos", positional=False, default="lol")
245 mytask = Context("mytask", args=[pos1, pos2, nonpos])
246 assert mytask.positional_args == [pos1, pos2]
247 r = Parser([mytask]).parse_argv(
248 [
249 "mytask",
250 "--nonpos",
251 "wut",
252 "--pos2",
253 "pos2val",
254 "pos1val",
255 ]
256 )[0]
257 assert r.args["pos1"].value == "pos1val"
258 assert r.args["pos2"].value == "pos2val"
259 assert r.args["nonpos"].value == "wut"
260
261 class equals_signs:
262 def _compare(self, argname: str, invoke: str, value: str) -> None:
263 c = Context("mytask", args=(Argument(argname, kind=str),))
264 r = Parser((c,)).parse_argv(["mytask", invoke])
265 assert r[0].args[argname].value == value
266
267 def handles_equals_style_long_flags(self) -> None:
268 self._compare("foo", "--foo=bar", "bar")
269
270 def handles_equals_style_short_flags(self) -> None:
271 self._compare("f", "-f=bar", "bar")
272
273 def does_not_require_escaping_equals_signs_in_value(self) -> None:
274 self._compare("f", "-f=biz=baz", "biz=baz")
275
276 def handles_multiple_boolean_flags_per_context(self) -> None:
277 c = Context(
278 "mytask",
279 args=(Argument("foo", kind=bool), Argument("bar", kind=bool)),
280 )
281 r = Parser([c]).parse_argv(["mytask", "--foo", "--bar"])
282 a = r[0].args
283 assert a.foo.value is True
284 assert a.bar.value is True
285
286 class optional_arg_values:
287 def setup_method(self) -> None:
288 self.parser = self._parser()
289
290 def _parser(self, arguments=None) -> Parser:
291 if arguments is None:
292 arguments = (
293 Argument(
294 names=("foo", "f"), optional=True, default="mydefault"
295 ),
296 )
297 self.context = Context("mytask", args=arguments)
298 self.parser = Parser([self.context])
299 return self.parser
300
301 def _parse(self, argstr, parser=None) -> Parser:
302 parser = parser or self.parser
303 return parser.parse_argv(["mytask"] + argstr.split())
304
305 def _expect(self, argstr, expected, parser=None) -> None:
306 result = self._parse(argstr, parser)
307 assert result[0].args.foo.value == expected
308
309 def no_value_becomes_True_not_default_value(self) -> None:
310 self._expect("--foo", True)
311 self._expect("-f", True)
312
313 def value_given_gets_preserved_normally(self) -> None:
314 for argstr in (
315 "--foo whatever",
316 "--foo=whatever",
317 "-f whatever",
318 "-f=whatever",
319 ):
320 self._expect(argstr, "whatever")
321
322 def not_given_at_all_uses_default_value(self) -> None:
323 self._expect("", "mydefault")
324
325 class ambiguity_sanity_checks:
326 def _test_for_ambiguity(self, invoke, parser=None) -> None:
327 msg = "is ambiguous"
328 try:
329 self._parse(invoke, parser or self.parser)
330 # Expected result
331 except ParseError as e:
332 assert msg in str(e)
333 # No exception occurred at all? Bollocks.
334 else:
335 assert False
336 # Any other exceptions will naturally cause failure here.
337
338 def unfilled_posargs(self) -> None:
339 p = self._parser(
340 (
341 Argument("foo", optional=True),
342 Argument("bar", positional=True),
343 )
344 )
345 self._test_for_ambiguity("--foo uhoh", p)
346
347 def no_ambiguity_if_option_val_already_given(self) -> None:
348 p = self._parser(
349 (
350 Argument("foo", optional=True),
351 Argument("bar", kind=bool),
352 )
353 )
354 # This should NOT raise a ParseError.
355 result = self._parse("--foo hello --bar", p)
356 assert result[0].args["foo"].value == "hello"
357 assert result[0].args["bar"].value is True
358
359 def valid_argument_is_NOT_ambiguous(self) -> None:
360 # The one exception that proves the rule?
361 self._parser((Argument("foo", optional=True), Argument("bar")))
362 for form in ("--bar barval", "--bar=barval"):
363 result = self._parse("--foo {}".format(form))
364 assert len(result) == 1
365 args = result[0].args
366 assert args["foo"].value is True
367 assert args["bar"].value == "barval"
368
369 def valid_flaglike_argument_is_NOT_ambiguous(self) -> None:
370 # The OTHER exception that proves the rule?
371 self._parser(
372 (
373 Argument("foo", optional=True),
374 Argument("bar", kind=bool),
375 )
376 )
377 result = self._parse("--foo --bar")
378 assert len(result) == 1
379 args = result[0].args
380 assert args["foo"].value is True
381 assert args["bar"].value is True
382
383 def invalid_flaglike_value_is_stored_as_value(self) -> None:
384 self._parser((Argument("foo", optional=True),))
385 result = self._parse("--foo --bar")
386 assert result[0].args["foo"].value == "--bar"
387
388 def task_name(self) -> None:
389 # mytask --foo myothertask
390 c1 = Context("mytask", args=(Argument("foo", optional=True),))
391 c2 = Context("othertask")
392 p = Parser([c1, c2])
393 self._test_for_ambiguity("--foo othertask", p)
394
395 class list_type_arguments:
396 "list-type (iterable) arguments"
397
398 def _parse(self, *args) -> list:
399 c = Context("mytask", args=(Argument("mylist", kind=list),))
400 argv = ["mytask"] + list(args)
401 return Parser([c]).parse_argv(argv)[0].args.mylist.value
402
403 def can_be_given_no_times_resulting_in_default_empty_list(
404 self,
405 ) -> None:
406 assert self._parse() == []
407
408 def given_once_becomes_single_item_list(self) -> None:
409 assert self._parse("--mylist", "foo") == ["foo"]
410
411 def given_N_times_becomes_list_of_len_N(self) -> None:
412 expected = ["foo", "bar", "biz"]
413 got = self._parse(
414 "--mylist", "foo", "--mylist", "bar", "--mylist", "biz"
415 )
416 assert got == expected
417
418 def iterables_work_correctly_outside_a_vacuum(self) -> None:
419 # Undetected bug where I was primarily focused on the -vvv use
420 # case...'normal' incrementables never left 'waiting for value'
421 # state in the parser! so _subsequent_ task names & such never got
422 # parsed right, always got appended to the list.
423 c = Context("mytask", args=[Argument("mylist", kind=list)])
424 c2 = Context("othertask")
425 argv = [
426 "mytask",
427 "--mylist",
428 "val",
429 "--mylist",
430 "val2",
431 "othertask",
432 ]
433 result = Parser([c, c2]).parse_argv(argv)
434 # When bug present, result only has one context (for 'mytask') and
435 # its 'mylist' consists of ['val', 'val2', 'othertask']. (the
436 # middle '--mylist' was handled semi-correctly.)
437 mylist = result[0].args.mylist.value
438 assert mylist == ["val", "val2"]
439 contexts = len(result)
440 err = "Got {} parse context results instead of 2!".format(contexts)
441 assert contexts == 2, err
442 assert result[1].name == "othertask"
443
444 class task_repetition:
445 def is_happy_to_handle_same_task_multiple_times(self) -> None:
446 task1 = Context("mytask")
447 result = Parser((task1,)).parse_argv(["mytask", "mytask"])
448 assert len(result) == 2
449 for x in result:
450 assert x.name == "mytask"
451
452 def task_args_work_correctly(self) -> None:
453 task1 = Context("mytask", args=(Argument("meh"),))
454 result = Parser((task1,)).parse_argv(
455 ["mytask", "--meh", "mehval1", "mytask", "--meh", "mehval2"]
456 )
457 assert result[0].args.meh.value == "mehval1"
458 assert result[1].args.meh.value == "mehval2"
459
460 class per_task_core_flags:
461 class general:
462 def _echo(self) -> Argument:
463 return Argument("echo", kind=bool, default=False)
464
465 def core_flags_work_normally_when_no_conflict(self) -> None:
466 # Initial parse context with an --echo, plus a no-args task
467 initial = Context(args=[self._echo()])
468 task1 = Context("mytask")
469 parser = Parser(initial=initial, contexts=[task1])
470 # Call with --echo in the per-task context, expect the core
471 # context got updated (vs an error)
472 result = parser.parse_argv(["mytask", "--echo"])
473 assert result[0].args.echo.value is True
474
475 def when_conflict_per_task_args_win_out(self) -> None:
476 # Initial parse context with an --echo, plus task w/ same
477 initial = Context(args=[self._echo()])
478 task1 = Context("mytask", args=[self._echo()])
479 parser = Parser(initial=initial, contexts=[task1])
480 # Call with --echo in the per-task context, expect the task
481 # context got updated, and not core.
482 result = parser.parse_argv(["mytask", "--echo"])
483 assert result[0].args.echo.value is False
484 assert result[1].args.echo.value is True
485
486 def value_requiring_core_flags_also_work_correctly(self) -> None:
487 "value-requiring core flags also work correctly"
488 initial = Context(args=[Argument("hide")])
489 task1 = Context("mytask")
490 parser = Parser(initial=initial, contexts=[task1])
491 result = parser.parse_argv(["mytask", "--hide", "both"])
492 assert result[0].args.hide.value == "both"
493
494 class edge_cases:
495 def core_bool_but_per_task_string(self) -> None:
496 # Initial parse context with bool --hide, and a task with a
497 # regular (string) --hide
498 initial = Context(
499 args=[Argument("hide", kind=bool, default=False)]
500 )
501 task1 = Context("mytask", args=[Argument("hide")])
502 parser = Parser(initial=initial, contexts=[task1])
503 # Expect that, because the task's version wins, we're able to
504 # call it with a value. (If there were weird bugs where the
505 # core flag informed the parsing, this would fail.)
506 result = parser.parse_argv(["mytask", "--hide", "both"])
507 assert result[0].args.hide.value is False
508 assert result[1].args.hide.value == "both"
509
510 class help_treats_context_name_as_its_value:
511 def by_itself_base_case(self) -> None:
512 task1 = Context("mytask")
513 init = Context(args=[Argument("help", optional=True)])
514 parser = Parser(initial=init, contexts=[task1])
515 result = parser.parse_argv(["mytask", "--help"])
516 assert len(result) == 2
517 assert result[0].args.help.value == "mytask"
518 assert "help" not in result[1].args
519
520 def other_tokens_afterwards_raise_parse_errors(self) -> None:
521 # NOTE: this is because of the special-casing where we supply
522 # the task name as the value when the flag is literally named
523 # "help".
524 task1 = Context("mytask")
525 init = Context(args=[Argument("help", optional=True)])
526 parser = Parser(initial=init, contexts=[task1])
527 with raises(ParseError, match=r".*foobar.*"):
528 parser.parse_argv(["mytask", "--help", "foobar"])
529
530
531 class ParseResult_:
532 "ParseResult"
533
534 def setup_method(self) -> None:
535 self.context = Context(
536 "mytask", args=(Argument("foo", kind=str), Argument("bar"))
537 )
538 argv = ["mytask", "--foo", "foo-val", "--", "my", "remainder"]
539 self.result = Parser((self.context,)).parse_argv(argv)
540
541 def acts_as_a_list_of_parsed_contexts(self) -> None:
542 assert len(self.result) == 1
543 assert self.result[0].name == "mytask"
544
545 def exhibits_remainder_attribute(self) -> None:
546 assert self.result.remainder == "my remainder"