Debian Codegraph @

tests/test_argparse.py

raw symbols SCIP
1 """Cmd2 testing for argument parsing"""
2
3 import argparse
4
5 import pytest
6
7 import cmd2
8
9 from .conftest import (
10 run_cmd,
11 )
12
13
14 class ArgparseApp(cmd2.Cmd):
15 def __init__(self) -> None:
16 self.maxrepeats = 3
17 cmd2.Cmd.__init__(self)
18
19 def namespace_provider(self) -> argparse.Namespace:
20 ns = argparse.Namespace()
21 ns.custom_stuff = "custom"
22 return ns
23
24 @staticmethod
25 def _say_parser_builder() -> cmd2.Cmd2ArgumentParser:
26 say_parser = cmd2.Cmd2ArgumentParser()
27 say_parser.add_argument("-p", "--piglatin", action="store_true", help="atinLay")
28 say_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE")
29 say_parser.add_argument("-r", "--repeat", type=int, help="output [n] times")
30 say_parser.add_argument("words", nargs="+", help="words to say")
31 return say_parser
32
33 @cmd2.with_argparser(_say_parser_builder)
34 def do_say(self, args, *, keyword_arg: str | None = None) -> None:
35 """Repeat what you tell me to.
36
37 :param args: argparse namespace
38 :param keyword_arg: Optional keyword arguments
39 """
40 words = []
41 for word in args.words:
42 modified_word = word
43 if word is None:
44 modified_word = ""
45 if args.piglatin:
46 modified_word = f"{word[1:]}{word[0]}ay"
47 if args.shout:
48 modified_word = word.upper()
49 words.append(modified_word)
50 repetitions = args.repeat or 1
51 for _ in range(min(repetitions, self.maxrepeats)):
52 self.stdout.write(" ".join(words))
53 self.stdout.write("\n")
54
55 if keyword_arg is not None:
56 print(keyword_arg)
57
58 tag_parser = cmd2.Cmd2ArgumentParser(description="create a html tag")
59 tag_parser.add_argument("tag", help="tag")
60 tag_parser.add_argument("content", nargs="+", help="content to surround with tag")
61
62 @cmd2.with_argparser(tag_parser, preserve_quotes=True)
63 def do_tag(self, args) -> None:
64 self.stdout.write("<{0}>{1}</{0}>".format(args.tag, " ".join(args.content)))
65 self.stdout.write("\n")
66
67 @cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), ns_provider=namespace_provider)
68 def do_test_argparse_ns(self, args) -> None:
69 self.stdout.write(f"{args.custom_stuff}")
70
71 @cmd2.with_argument_list
72 def do_arglist(self, arglist, *, keyword_arg: str | None = None) -> None:
73 if isinstance(arglist, list):
74 self.stdout.write("True")
75 else:
76 self.stdout.write("False")
77
78 if keyword_arg is not None:
79 print(keyword_arg)
80
81 @cmd2.with_argument_list(preserve_quotes=True)
82 def do_preservelist(self, arglist) -> None:
83 self.stdout.write(f"{arglist}")
84
85 @classmethod
86 def _speak_parser_builder(cls) -> cmd2.Cmd2ArgumentParser:
87 known_parser = cmd2.Cmd2ArgumentParser()
88 known_parser.add_argument("-p", "--piglatin", action="store_true", help="atinLay")
89 known_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE")
90 known_parser.add_argument("-r", "--repeat", type=int, help="output [n] times")
91 return known_parser
92
93 @cmd2.with_argparser(_speak_parser_builder, with_unknown_args=True)
94 def do_speak(self, args, extra, *, keyword_arg: str | None = None) -> None:
95 """Repeat what you tell me to."""
96 words = []
97 for word in extra:
98 modified_word = word
99 if word is None:
100 modified_word = ""
101 if args.piglatin:
102 modified_word = f"{word[1:]}{word[0]}ay"
103 if args.shout:
104 modified_word = word.upper()
105 words.append(modified_word)
106 repetitions = args.repeat or 1
107 for _ in range(min(repetitions, self.maxrepeats)):
108 self.stdout.write(" ".join(words))
109 self.stdout.write("\n")
110
111 if keyword_arg is not None:
112 print(keyword_arg)
113
114 @cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), preserve_quotes=True, with_unknown_args=True)
115 def do_test_argparse_with_list_quotes(self, args, extra) -> None:
116 self.stdout.write("{}".format(" ".join(extra)))
117
118 @cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), ns_provider=namespace_provider, with_unknown_args=True)
119 def do_test_argparse_with_list_ns(self, args, extra) -> None:
120 self.stdout.write(f"{args.custom_stuff}")
121
122
123 @pytest.fixture
124 def argparse_app():
125 return ArgparseApp()
126
127
128 def test_invalid_syntax(argparse_app) -> None:
129 _out, err = run_cmd(argparse_app, 'speak "')
130 assert err[0] == "Invalid syntax: No closing quotation"
131
132
133 def test_argparse_basic_command(argparse_app) -> None:
134 out, _err = run_cmd(argparse_app, "say hello")
135 assert out == ["hello"]
136
137
138 def test_argparse_remove_quotes(argparse_app) -> None:
139 out, _err = run_cmd(argparse_app, 'say "hello there"')
140 assert out == ["hello there"]
141
142
143 def test_argparse_with_no_args(argparse_app) -> None:
144 """Make sure we receive TypeError when calling argparse-based function with no args"""
145 with pytest.raises(TypeError) as excinfo:
146 argparse_app.do_say()
147 assert "Expected arguments" in str(excinfo.value)
148
149
150 def test_argparser_kwargs(argparse_app, capsys) -> None:
151 """Test with_argparser wrapper passes through kwargs to command function"""
152 argparse_app.do_say("word", keyword_arg="foo")
153 out, _err = capsys.readouterr()
154 assert out == "foo\n"
155
156
157 def test_argparse_preserve_quotes(argparse_app) -> None:
158 out, _err = run_cmd(argparse_app, 'tag mytag "hello"')
159 assert out[0] == '<mytag>"hello"</mytag>'
160
161
162 def test_argparse_custom_namespace(argparse_app) -> None:
163 out, _err = run_cmd(argparse_app, "test_argparse_ns")
164 assert out[0] == "custom"
165
166
167 def test_argparse_with_list(argparse_app) -> None:
168 out, _err = run_cmd(argparse_app, "speak -s hello world!")
169 assert out == ["HELLO WORLD!"]
170
171
172 def test_argparse_with_list_remove_quotes(argparse_app) -> None:
173 out, _err = run_cmd(argparse_app, 'speak -s hello "world!"')
174 assert out == ["HELLO WORLD!"]
175
176
177 def test_argparse_with_list_preserve_quotes(argparse_app) -> None:
178 out, _err = run_cmd(argparse_app, 'test_argparse_with_list_quotes "hello" person')
179 assert out[0] == '"hello" person'
180
181
182 def test_argparse_with_list_custom_namespace(argparse_app) -> None:
183 out, _err = run_cmd(argparse_app, "test_argparse_with_list_ns")
184 assert out[0] == "custom"
185
186
187 def test_argparse_with_list_and_empty_doc(argparse_app) -> None:
188 out, _err = run_cmd(argparse_app, "speak -s hello world!")
189 assert out == ["HELLO WORLD!"]
190
191
192 def test_argparser_correct_args_with_quotes_and_midline_options(argparse_app) -> None:
193 out, _err = run_cmd(argparse_app, "speak 'This is a' -s test of the emergency broadcast system!")
194 assert out == ["THIS IS A TEST OF THE EMERGENCY BROADCAST SYSTEM!"]
195
196
197 def test_argparser_and_unknown_args_kwargs(argparse_app, capsys) -> None:
198 """Test with_argparser wrapper passing through kwargs to command function"""
199 argparse_app.do_speak("", keyword_arg="foo")
200 out, _err = capsys.readouterr()
201 assert out == "foo\n"
202
203
204 def test_argparse_quoted_arguments_multiple(argparse_app) -> None:
205 out, _err = run_cmd(argparse_app, 'say "hello there" "rick & morty"')
206 assert out == ["hello there rick & morty"]
207
208
209 def test_argparse_help_docstring(argparse_app) -> None:
210 out, _err = run_cmd(argparse_app, "help say")
211 assert out[0].startswith("Usage: say")
212 assert out[1] == ""
213 assert out[2] == "Repeat what you tell me to."
214 for line in out:
215 assert not line.startswith(":")
216
217
218 def test_argparse_help_description(argparse_app) -> None:
219 out, _err = run_cmd(argparse_app, "help tag")
220 assert out[0].startswith("Usage: tag")
221 assert out[1] == ""
222 assert out[2] == "create a html tag"
223
224
225 def test_argparse_prog(argparse_app) -> None:
226 out, _err = run_cmd(argparse_app, "help tag")
227 progname = out[0].split(" ")[1]
228 assert progname == "tag"
229
230
231 def test_arglist(argparse_app) -> None:
232 out, _err = run_cmd(argparse_app, 'arglist "we should" get these')
233 assert out[0] == "True"
234
235
236 def test_arglist_kwargs(argparse_app, capsys) -> None:
237 """Test with_argument_list wrapper passes through kwargs to command function"""
238 argparse_app.do_arglist("arg", keyword_arg="foo")
239 out, _err = capsys.readouterr()
240 assert out == "foo\n"
241
242
243 def test_preservelist(argparse_app) -> None:
244 out, _err = run_cmd(argparse_app, 'preservelist foo "bar baz"')
245 assert out[0] == "['foo', '\"bar baz\"']"
246
247
248 def test_invalid_parser_type(argparse_app):
249 parser_source = argparse.ArgumentParser()
250 with pytest.raises(TypeError, match="The parser must be an instance of 'Cmd2ArgumentParser'"):
251 argparse_app._build_parser(argparse_app, parser_source)
252
253
254 def test_invalid_return_staticmethod(argparse_app):
255 def bad_builder():
256 return argparse.ArgumentParser()
257
258 sm = staticmethod(bad_builder)
259
260 with pytest.raises(TypeError, match="must return a 'Cmd2ArgumentParser'"):
261 argparse_app._build_parser(argparse_app, sm)
262
263
264 def test_invalid_return_classmethod(argparse_app):
265 def bad_builder(cls):
266 return argparse.ArgumentParser()
267
268 cm = classmethod(bad_builder)
269
270 with pytest.raises(TypeError, match="must return a 'Cmd2ArgumentParser'"):
271 argparse_app._build_parser(argparse_app, cm)
272
273
274 def test_invalid_return_class_arg(argparse_app):
275 def bad_builder(cls):
276 return argparse.ArgumentParser()
277
278 with pytest.raises(TypeError, match="must return a 'Cmd2ArgumentParser'"):
279 argparse_app._build_parser(argparse_app, bad_builder)
280
281
282 def test_invalid_return_no_arg(argparse_app):
283 def bad_builder():
284 return argparse.ArgumentParser()
285
286 with pytest.raises(TypeError, match="must return a 'Cmd2ArgumentParser'"):
287 argparse_app._build_parser(argparse_app, bad_builder)
288
289
290 def test_invalid_parser_return_type_nameless_object(argparse_app):
291 # A class that is callable but has no __name__ attribute
292 class NamelessBuilder:
293 def __call__(self):
294 return argparse.ArgumentParser()
295
296 builder = NamelessBuilder()
297
298 # Verify __name__ is actually missing
299 assert not hasattr(builder, "__name__")
300
301 # The error message should now contain the string representation of the object
302 expected_msg = f"'{builder}' must return a 'Cmd2ArgumentParser'"
303
304 with pytest.raises(TypeError, match=expected_msg):
305 argparse_app._build_parser(argparse_app, builder)
306
307
308 def _build_has_subcmd_parser() -> cmd2.Cmd2ArgumentParser:
309 has_subcmds_parser = cmd2.Cmd2ArgumentParser(description="Tests as_subcmd_to decorator")
310 has_subcmds_parser.add_subparsers(dest="subcommand", metavar="SUBCOMMAND", required=True)
311 return has_subcmds_parser
312
313
314 class SubcommandApp(cmd2.Cmd):
315 """Example cmd2 application where we a base command which has a couple subcommands."""
316
317 # subcommand functions for the base command
318 def base_foo(self, args) -> None:
319 """Foo subcommand of base command"""
320 self.poutput(args.x * args.y)
321
322 def base_bar(self, args) -> None:
323 """Bar subcommand of base command"""
324 self.poutput(f"(({args.z}))")
325
326 def base_helpless(self, args) -> None:
327 """Helpless subcommand of base command"""
328 self.poutput(f"(({args.z}))")
329
330 # create the top-level parser for the base command
331 base_parser = cmd2.Cmd2ArgumentParser()
332 base_subparsers = base_parser.add_subparsers(dest="subcommand", metavar="SUBCOMMAND", required=True)
333
334 # create the parser for the "foo" subcommand
335 parser_foo = base_subparsers.add_parser("foo", help="foo help")
336 parser_foo.add_argument("-x", type=int, default=1, help="integer")
337 parser_foo.add_argument("y", type=float, help="float")
338 parser_foo.set_defaults(func=base_foo)
339
340 # create the parser for the "bar" subcommand
341 parser_bar = base_subparsers.add_parser("bar", help="bar help", aliases=["bar_1", "bar_2"])
342 parser_bar.add_argument("z", help="string")
343 parser_bar.set_defaults(func=base_bar)
344
345 # create the parser for the "helpless" subcommand
346 # This subcommand has aliases and no help text.
347 parser_helpless = base_subparsers.add_parser("helpless", aliases=["helpless_1", "helpless_2"])
348 parser_helpless.add_argument("z", help="string")
349 parser_helpless.set_defaults(func=base_helpless)
350
351 @cmd2.with_argparser(base_parser)
352 def do_base(self, args) -> None:
353 """Base command help"""
354 # Call whatever subcommand function was selected
355 func = args.func
356 func(self, args)
357
358 # Add subcommands using as_subcommand_to decorator
359 @cmd2.with_argparser(_build_has_subcmd_parser)
360 def do_test_subcmd_decorator(self, args: argparse.Namespace) -> None:
361 args.cmd2_subcommand_func(args)
362
363 subcmd_parser = cmd2.Cmd2ArgumentParser(description="A subcommand")
364
365 @cmd2.as_subcommand_to("test_subcmd_decorator", "subcmd", subcmd_parser, help=subcmd_parser.description.lower())
366 def subcmd_func(self, args: argparse.Namespace) -> None:
367 # Make sure printing the Namespace works.
368 self.poutput(args)
369
370 helpless_subcmd_parser = cmd2.Cmd2ArgumentParser(add_help=False, description="A subcommand with no help")
371
372 @cmd2.as_subcommand_to(
373 "test_subcmd_decorator", "helpless_subcmd", helpless_subcmd_parser, help=helpless_subcmd_parser.description.lower()
374 )
375 def helpless_subcmd_func(self, args: argparse.Namespace) -> None:
376 # Make sure vars(Namespace) works.
377 self.poutput(vars(args))
378
379
380 @pytest.fixture
381 def subcommand_app():
382 return SubcommandApp()
383
384
385 def test_subcommand_foo(subcommand_app) -> None:
386 out, _err = run_cmd(subcommand_app, "base foo -x2 5.0")
387 assert out == ["10.0"]
388
389
390 def test_subcommand_bar(subcommand_app) -> None:
391 out, _err = run_cmd(subcommand_app, "base bar baz")
392 assert out == ["((baz))"]
393
394
395 def test_subcommand_invalid(subcommand_app) -> None:
396 _out, err = run_cmd(subcommand_app, "base baz")
397 assert err[0].startswith("Usage: base")
398 assert err[1].startswith("Error: argument SUBCOMMAND: invalid choice: 'baz'")
399
400
401 def test_subcommand_base_help(subcommand_app) -> None:
402 out, _err = run_cmd(subcommand_app, "help base")
403 assert out[0].startswith("Usage: base")
404 assert out[1] == ""
405 assert out[2] == "Base command help"
406
407
408 def test_subcommand_help(subcommand_app) -> None:
409 # foo has no aliases
410 out, _err = run_cmd(subcommand_app, "help base foo")
411 assert out[0].startswith("Usage: base foo")
412 assert out[1] == ""
413 assert out[2] == "Positional Arguments:"
414
415 # bar has aliases (usage should never show alias name)
416 out, _err = run_cmd(subcommand_app, "help base bar")
417 assert out[0].startswith("Usage: base bar")
418 assert out[1] == ""
419 assert out[2] == "Positional Arguments:"
420
421 out, _err = run_cmd(subcommand_app, "help base bar_1")
422 assert out[0].startswith("Usage: base bar")
423 assert out[1] == ""
424 assert out[2] == "Positional Arguments:"
425
426 out, _err = run_cmd(subcommand_app, "help base bar_2")
427 assert out[0].startswith("Usage: base bar")
428 assert out[1] == ""
429 assert out[2] == "Positional Arguments:"
430
431 # helpless has aliases and no help text (usage should never show alias name)
432 out, _err = run_cmd(subcommand_app, "help base helpless")
433 assert out[0].startswith("Usage: base helpless")
434 assert out[1] == ""
435 assert out[2] == "Positional Arguments:"
436
437 out, _err = run_cmd(subcommand_app, "help base helpless_1")
438 assert out[0].startswith("Usage: base helpless")
439 assert out[1] == ""
440 assert out[2] == "Positional Arguments:"
441
442 out, _err = run_cmd(subcommand_app, "help base helpless_2")
443 assert out[0].startswith("Usage: base helpless")
444 assert out[1] == ""
445 assert out[2] == "Positional Arguments:"
446
447
448 def test_subcommand_invalid_help(subcommand_app) -> None:
449 out, _err = run_cmd(subcommand_app, "help base baz")
450 assert out[0].startswith("Usage: base")
451
452
453 def test_subcmd_decorator(subcommand_app) -> None:
454 # Test subcommand that has help option
455 out, err = run_cmd(subcommand_app, "test_subcmd_decorator subcmd")
456 assert out[0].startswith("Namespace(")
457
458 out, err = run_cmd(subcommand_app, "help test_subcmd_decorator subcmd")
459 assert out[0] == "Usage: test_subcmd_decorator subcmd [-h]"
460
461 out, err = run_cmd(subcommand_app, "test_subcmd_decorator subcmd -h")
462 assert out[0] == "Usage: test_subcmd_decorator subcmd [-h]"
463
464 # Test subcommand that has no help option
465 out, err = run_cmd(subcommand_app, "test_subcmd_decorator helpless_subcmd")
466 assert "'subcommand': 'helpless_subcmd'" in out[1]
467
468 out, err = run_cmd(subcommand_app, "help test_subcmd_decorator helpless_subcmd")
469 assert out[0] == "Usage: test_subcmd_decorator helpless_subcmd"
470 assert not err
471
472 out, err = run_cmd(subcommand_app, "test_subcmd_decorator helpless_subcmd -h")
473 assert not out
474 assert err[0] == "Usage: test_subcmd_decorator [-h] SUBCOMMAND ..."
475 assert err[1] == "Error: unrecognized arguments: -h"
476
477
478 def test_unittest_mock() -> None:
479 from unittest import (
480 mock,
481 )
482
483 from cmd2 import (
484 CommandSetRegistrationError,
485 )
486
487 with mock.patch.object(ArgparseApp, "namespace_provider"), pytest.raises(CommandSetRegistrationError):
488 ArgparseApp()
489
490 with mock.patch.object(ArgparseApp, "namespace_provider", spec=True):
491 ArgparseApp()
492
493 with mock.patch.object(ArgparseApp, "namespace_provider", spec_set=True):
494 ArgparseApp()
495
496 with mock.patch.object(ArgparseApp, "namespace_provider", autospec=True):
497 ArgparseApp()
498
499
500 def test_pytest_mock_invalid(mocker) -> None:
501 from cmd2 import (
502 CommandSetRegistrationError,
503 )
504
505 mocker.patch.object(ArgparseApp, "namespace_provider")
506 with pytest.raises(CommandSetRegistrationError):
507 ArgparseApp()
508
509
510 @pytest.mark.parametrize(
511 "spec_param",
512 [
513 {"spec": True},
514 {"spec_set": True},
515 {"autospec": True},
516 ],
517 )
518 def test_pytest_mock_valid(mocker, spec_param) -> None:
519 mocker.patch.object(ArgparseApp, "namespace_provider", **spec_param)
520 ArgparseApp()