Debian Codegraph @

tests/test_commandset.py

raw symbols SCIP
1 """Test CommandSet"""
2
3 import argparse
4 import signal
5
6 import pytest
7
8 import cmd2
9 from cmd2 import (
10 Completions,
11 Settable,
12 )
13 from cmd2.exceptions import (
14 CommandSetRegistrationError,
15 )
16
17 from .conftest import (
18 WithCommandSets,
19 normalize,
20 run_cmd,
21 )
22
23
24 class CommandSetBase(cmd2.CommandSet):
25 pass
26
27
28 class CommandSetA(CommandSetBase):
29 DEFAULT_CATEGORY = "Fruits"
30
31 def on_register(self, cmd) -> None:
32 super().on_register(cmd)
33 print("in on_register now")
34
35 def on_registered(self) -> None:
36 super().on_registered()
37 print("in on_registered now")
38
39 def on_unregister(self) -> None:
40 super().on_unregister()
41 print("in on_unregister now")
42
43 def on_unregistered(self) -> None:
44 super().on_unregistered()
45 print("in on_unregistered now")
46
47 def do_apple(self, statement: cmd2.Statement) -> None:
48 """Apple Command"""
49 self._cmd.poutput("Apple!")
50
51 def do_banana(self, statement: cmd2.Statement) -> None:
52 """Banana Command"""
53 self._cmd.poutput("Banana!!")
54
55 cranberry_parser = cmd2.Cmd2ArgumentParser()
56 cranberry_parser.add_argument("arg1", choices=["lemonade", "juice", "sauce"])
57
58 @cmd2.with_argparser(cranberry_parser, with_unknown_args=True)
59 def do_cranberry(self, ns: argparse.Namespace, unknown: list[str]) -> None:
60 """Cranberry Command"""
61 self._cmd.poutput(f"Cranberry {ns.arg1}!!")
62 if unknown and len(unknown):
63 self._cmd.poutput("Unknown: " + ", ".join(["{}"] * len(unknown)).format(*unknown))
64 self._cmd.last_result = {"arg1": ns.arg1, "unknown": unknown}
65
66 def help_cranberry(self) -> None:
67 self._cmd.stdout.write("This command does diddly squat...\n")
68
69 @cmd2.with_argument_list
70 @cmd2.with_category("Also Alone")
71 def do_durian(self, args: list[str]) -> None:
72 """Durian Command"""
73 self._cmd.poutput(f"{len(args)} Arguments: ")
74 self._cmd.poutput(", ".join(["{}"] * len(args)).format(*args))
75 self._cmd.last_result = {"args": args}
76
77 def complete_durian(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
78 return self._cmd.basic_complete(text, line, begidx, endidx, ["stinks", "smells", "disgusting"])
79
80 elderberry_parser = cmd2.Cmd2ArgumentParser()
81 elderberry_parser.add_argument("arg1")
82
83 @cmd2.with_category("Alone")
84 @cmd2.with_argparser(elderberry_parser)
85 def do_elderberry(self, ns: argparse.Namespace) -> None:
86 """Elderberry Command"""
87 self._cmd.poutput(f"Elderberry {ns.arg1}!!")
88 self._cmd.last_result = {"arg1": ns.arg1}
89
90 # Test that CommandSet with as_subcommand_to decorator successfully loads
91 # during `cmd2.Cmd.__init__()`.
92 main_parser = cmd2.Cmd2ArgumentParser(description="Main Command")
93 main_parser.add_subparsers(dest="subcommand", metavar="SUBCOMMAND", required=True)
94
95 @cmd2.with_category("Alone")
96 @cmd2.with_argparser(main_parser)
97 def do_main(self, args: argparse.Namespace) -> None:
98 # Call function for whatever subcommand was selected
99 args.cmd2_subcommand_func(args)
100
101 # main -> sub
102 subcmd_parser = cmd2.Cmd2ArgumentParser(description="Sub Command")
103
104 # Include aliases to cover the alias check in cmd2's check_parser_uninstallable().
105 @cmd2.as_subcommand_to("main", "sub", subcmd_parser, help="sub command", aliases=["sub_alias"])
106 def subcmd_func(self, args: argparse.Namespace) -> None:
107 self._cmd.poutput("Subcommand Ran")
108
109
110 class CommandSetB(CommandSetBase):
111 DEFAULT_CATEGORY = "Command Set B"
112
113 def __init__(self, arg1) -> None:
114 super().__init__()
115 self._arg1 = arg1
116
117 def do_aardvark(self, statement: cmd2.Statement) -> None:
118 """Aardvark Command"""
119 self._cmd.poutput("Aardvark!")
120
121 def do_bat(self, statement: cmd2.Statement) -> None:
122 """Bat Command"""
123 self._cmd.poutput("Bat!!")
124
125 def do_crocodile(self, statement: cmd2.Statement) -> None:
126 """Crocodile Command"""
127 self._cmd.poutput("Crocodile!!")
128
129
130 def test_autoload_commands(autoload_command_sets_app) -> None:
131 # verifies that, when autoload is enabled, CommandSets and registered functions all show up
132
133 cmds_cats, _help_topics = autoload_command_sets_app._build_command_info()
134
135 assert "Alone" in cmds_cats
136 assert "elderberry" in cmds_cats["Alone"]
137 assert "main" in cmds_cats["Alone"]
138
139 # Test subcommand was autoloaded
140 result = autoload_command_sets_app.app_cmd("main sub")
141 assert "Subcommand Ran" in result.stdout
142
143 assert "Also Alone" in cmds_cats
144 assert "durian" in cmds_cats["Also Alone"]
145
146 assert "Fruits" in cmds_cats
147 assert "cranberry" in cmds_cats["Fruits"]
148
149 assert "Command Set B" not in cmds_cats
150
151
152 def test_command_synonyms() -> None:
153 """Test the use of command synonyms in CommandSets"""
154
155 class SynonymCommandSet(cmd2.CommandSet):
156 def __init__(self, arg1) -> None:
157 super().__init__()
158 self._arg1 = arg1
159
160 @cmd2.with_argparser(cmd2.Cmd2ArgumentParser(description="Native Command"))
161 def do_builtin(self, _) -> None:
162 """Builtin Command"""
163
164 # Create a synonym to a command inside of this CommandSet
165 do_builtin_synonym = do_builtin
166
167 # Create a synonym to a command outside of this CommandSet with subcommands.
168 # This will best test the synonym check in cmd2.Cmd._check_uninstallable() when
169 # we unregister this CommandSet.
170 do_alias_synonym = cmd2.Cmd.do_alias
171
172 cs = SynonymCommandSet("foo")
173 app = WithCommandSets(command_sets=[cs])
174
175 # Make sure the synonyms have the same parser as what they alias
176 builtin_parser = app.command_parsers.get(app.do_builtin)
177 builtin_synonym_parser = app.command_parsers.get(app.do_builtin_synonym)
178 assert builtin_parser is not None
179 assert builtin_parser is builtin_synonym_parser
180
181 alias_parser = app.command_parsers.get(cmd2.Cmd.do_alias)
182 alias_synonym_parser = app.command_parsers.get(app.do_alias_synonym)
183 assert alias_parser is not None
184 assert alias_parser is alias_synonym_parser
185
186 # Unregister the CommandSet and make sure built-in command and synonyms are gone
187 app.unregister_command_set(cs)
188 assert not hasattr(app, "do_builtin")
189 assert not hasattr(app, "do_builtin_synonym")
190 assert not hasattr(app, "do_alias_synonym")
191
192 # Make sure the alias command still exists, has the same parser, and works.
193 assert alias_parser is app.command_parsers.get(cmd2.Cmd.do_alias)
194 out, _err = run_cmd(app, "alias --help")
195 assert normalize(alias_parser.format_help())[0] in out
196
197
198 def test_custom_construct_commandsets() -> None:
199 command_set_b = CommandSetB("foo")
200
201 # Verify that _cmd cannot be accessed until CommandSet is registered.
202 with pytest.raises(CommandSetRegistrationError) as excinfo:
203 command_set_b._cmd.poutput("test")
204 assert "is not registered" in str(excinfo.value)
205
206 # Verifies that a custom initialized CommandSet loads correctly when passed into the constructor
207 app = WithCommandSets(command_sets=[command_set_b])
208
209 cmds_cats, _help_topics = app._build_command_info()
210 assert "Command Set B" in cmds_cats
211
212 # Verifies that the same CommandSet cannot be loaded twice
213 command_set_2 = CommandSetB("bar")
214 with pytest.raises(CommandSetRegistrationError):
215 assert app.register_command_set(command_set_2)
216
217 # Verify that autoload doesn't conflict with a manually loaded CommandSet that could be autoloaded.
218 command_set_a = CommandSetA()
219 app2 = WithCommandSets(command_sets=[command_set_a])
220
221 with pytest.raises(CommandSetRegistrationError):
222 app2.register_command_set(command_set_b)
223
224 app.unregister_command_set(command_set_b)
225
226 app2.register_command_set(command_set_b)
227
228 assert hasattr(app2, "do_apple")
229 assert hasattr(app2, "do_aardvark")
230
231 assert app2.find_commandset_for_command("aardvark") is command_set_b
232 assert app2.find_commandset_for_command("apple") is command_set_a
233
234 matches = app2.find_commandsets(CommandSetBase, subclass_match=True)
235 assert command_set_a in matches
236 assert command_set_b in matches
237 assert command_set_2 not in matches
238
239
240 def test_load_commands(manual_command_sets_app, capsys) -> None:
241 # now install a command set and verify the commands are now present
242 cmd_set = CommandSetA()
243
244 assert manual_command_sets_app.find_commandset_for_command("elderberry") is None
245 assert not manual_command_sets_app.find_commandsets(CommandSetA)
246
247 manual_command_sets_app.register_command_set(cmd_set)
248
249 assert manual_command_sets_app.find_commandsets(CommandSetA)[0] is cmd_set
250 assert manual_command_sets_app.find_commandset_for_command("elderberry") is cmd_set
251
252 out = manual_command_sets_app.app_cmd("apple")
253 assert "Apple!" in out.stdout
254
255 # Make sure registration callbacks ran
256 out, _err = capsys.readouterr()
257 assert "in on_register now" in out
258 assert "in on_registered now" in out
259
260 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
261
262 assert "Alone" in cmds_cats
263 assert "elderberry" in cmds_cats["Alone"]
264 assert "main" in cmds_cats["Alone"]
265
266 # Test subcommand was loaded
267 result = manual_command_sets_app.app_cmd("main sub")
268 assert "Subcommand Ran" in result.stdout
269
270 assert "Fruits" in cmds_cats
271 assert "cranberry" in cmds_cats["Fruits"]
272
273 # uninstall the command set and verify it is now also no longer accessible
274 manual_command_sets_app.unregister_command_set(cmd_set)
275
276 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
277
278 assert "Alone" not in cmds_cats
279 assert "Fruits" not in cmds_cats
280
281 # Make sure unregistration callbacks ran
282 out, _err = capsys.readouterr()
283 assert "in on_unregister now" in out
284 assert "in on_unregistered now" in out
285
286 # uninstall a second time and verify no errors happen
287 manual_command_sets_app.unregister_command_set(cmd_set)
288
289 # reinstall the command set and verify it is accessible
290 manual_command_sets_app.register_command_set(cmd_set)
291
292 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
293
294 assert "Alone" in cmds_cats
295 assert "elderberry" in cmds_cats["Alone"]
296 assert "main" in cmds_cats["Alone"]
297
298 # Test subcommand was loaded
299 result = manual_command_sets_app.app_cmd("main sub")
300 assert "Subcommand Ran" in result.stdout
301
302 assert "Fruits" in cmds_cats
303 assert "cranberry" in cmds_cats["Fruits"]
304
305
306 def test_commandset_decorators(autoload_command_sets_app) -> None:
307 result = autoload_command_sets_app.app_cmd("cranberry juice extra1 extra2")
308 assert result is not None
309 assert result.data is not None
310 assert len(result.data["unknown"]) == 2
311 assert "extra1" in result.data["unknown"]
312 assert "extra2" in result.data["unknown"]
313 assert result.data["arg1"] == "juice"
314 assert not result.stderr
315
316 result = autoload_command_sets_app.app_cmd("durian juice extra1 extra2")
317 assert len(result.data["args"]) == 3
318 assert "juice" in result.data["args"]
319 assert "extra1" in result.data["args"]
320 assert "extra2" in result.data["args"]
321 assert not result.stderr
322
323 result = autoload_command_sets_app.app_cmd("durian")
324 assert len(result.data["args"]) == 0
325 assert not result.stderr
326
327 result = autoload_command_sets_app.app_cmd("elderberry")
328 assert "arguments are required" in result.stderr
329 assert result.data is None
330
331 result = autoload_command_sets_app.app_cmd("elderberry a b")
332 assert "unrecognized arguments" in result.stderr
333 assert result.data is None
334
335
336 def test_load_commandset_errors(manual_command_sets_app, capsys) -> None:
337 cmd_set = CommandSetA()
338
339 # create a conflicting command before installing CommandSet to verify rollback behavior
340 manual_command_sets_app._install_command_function("do_durian", cmd_set.do_durian)
341 with pytest.raises(CommandSetRegistrationError):
342 manual_command_sets_app.register_command_set(cmd_set)
343
344 # verify that the commands weren't installed
345 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
346
347 assert "Alone" not in cmds_cats
348 assert "Fruits" not in cmds_cats
349 assert not manual_command_sets_app._installed_command_sets
350
351 del manual_command_sets_app.do_durian
352
353 # pre-create intentionally conflicting macro and alias names
354 manual_command_sets_app.app_cmd("macro create apple run_pyscript")
355 manual_command_sets_app.app_cmd("alias create banana run_pyscript")
356
357 # now install a command set and verify the commands are now present
358 manual_command_sets_app.register_command_set(cmd_set)
359 _out, err = capsys.readouterr()
360
361 # verify aliases and macros are deleted with warning if they conflict with a command
362 assert "Deleting alias 'banana'" in err
363 assert "Deleting macro 'apple'" in err
364
365 # verify command functions which don't start with "do_" raise an exception
366 with pytest.raises(CommandSetRegistrationError):
367 manual_command_sets_app._install_command_function("new_cmd", cmd_set.do_banana)
368
369 # verify methods which don't start with "do_" raise an exception
370 with pytest.raises(CommandSetRegistrationError):
371 manual_command_sets_app._install_command_function("do_new_cmd", cmd_set.on_register)
372
373 # verify duplicate commands are detected
374 with pytest.raises(CommandSetRegistrationError):
375 manual_command_sets_app._install_command_function("do_banana", cmd_set.do_banana)
376
377 # verify bad command names are detected
378 with pytest.raises(CommandSetRegistrationError):
379 manual_command_sets_app._install_command_function("do_bad command", cmd_set.do_banana)
380
381 # verify error conflict with existing completer function
382 with pytest.raises(CommandSetRegistrationError):
383 manual_command_sets_app._install_completer_function("durian", cmd_set.complete_durian)
384
385 # verify error conflict with existing help function
386 with pytest.raises(CommandSetRegistrationError):
387 manual_command_sets_app._install_help_function("cranberry", cmd_set.help_cranberry)
388
389
390 class LoadableBase(cmd2.CommandSet):
391 def __init__(self, dummy) -> None:
392 super().__init__()
393 self._dummy = dummy # prevents autoload
394 self._cut_called = False
395
396 cut_parser = cmd2.Cmd2ArgumentParser()
397 cut_parser.add_subparsers(title="item", help="item to cut", metavar="ITEM", required=True)
398
399 def namespace_provider(self) -> argparse.Namespace:
400 ns = argparse.Namespace()
401 ns.cut_called = self._cut_called
402 return ns
403
404 @cmd2.with_argparser(cut_parser)
405 def do_cut(self, ns: argparse.Namespace) -> None:
406 """Cut something"""
407 # Call whatever subcommand function was selected
408 ns.cmd2_subcommand_func(ns)
409 self._cut_called = True
410
411 stir_parser = cmd2.Cmd2ArgumentParser()
412 stir_subparsers = stir_parser.add_subparsers(title="item", help="what to stir", metavar="ITEM", required=True)
413
414 @cmd2.with_argparser(stir_parser, ns_provider=namespace_provider)
415 def do_stir(self, ns: argparse.Namespace) -> None:
416 """Stir something"""
417 if not ns.cut_called:
418 self._cmd.poutput("Need to cut before stirring")
419 return
420
421 # Call whatever subcommand function was selected
422 ns.cmd2_subcommand_func(ns)
423
424 stir_pasta_parser = cmd2.Cmd2ArgumentParser()
425 stir_pasta_parser.add_argument("--option", "-o")
426 stir_pasta_parser.add_subparsers(title="style", help="Stir style", required=True)
427
428 @cmd2.as_subcommand_to("stir", "pasta", stir_pasta_parser)
429 def stir_pasta(self, ns: argparse.Namespace) -> None:
430 # Call whatever subcommand function was selected
431 ns.cmd2_subcommand_func(ns)
432
433
434 class LoadableBadBase(cmd2.CommandSet):
435 def __init__(self, dummy) -> None:
436 super().__init__()
437 self._dummy = dummy # prevents autoload
438
439 # Create function which fails to decorate as an argparse base command.
440 def do_cut(self, _: cmd2.Statement) -> None:
441 """Cut something"""
442
443
444 class LoadableFruits(cmd2.CommandSet):
445 DEFAULT_CATEGORY = "Fruits"
446
447 def __init__(self, dummy) -> None:
448 super().__init__()
449 self._dummy = dummy # prevents autoload
450
451 def do_apple(self, _: cmd2.Statement) -> None:
452 """Apple Command"""
453 self._cmd.poutput("Apple")
454
455 banana_parser = cmd2.Cmd2ArgumentParser()
456 banana_parser.add_argument("direction", choices=["discs", "lengthwise"])
457
458 @cmd2.as_subcommand_to("cut", "banana", banana_parser, help="Cut banana", aliases=["bananer"])
459 def cut_banana(self, ns: argparse.Namespace) -> None:
460 """Cut banana"""
461 self._cmd.poutput("cutting banana: " + ns.direction)
462
463
464 class LoadablePastaStir(cmd2.CommandSet):
465 def __init__(self, dummy) -> None:
466 super().__init__()
467 self._dummy = dummy # prevents autoload
468
469 stir_pasta_vigor_parser = cmd2.Cmd2ArgumentParser()
470 stir_pasta_vigor_parser.add_argument("frequency")
471
472 @cmd2.as_subcommand_to("stir pasta", "vigorously", stir_pasta_vigor_parser)
473 def stir_pasta_vigorously(self, ns: argparse.Namespace) -> None:
474 self._cmd.poutput("stir the pasta vigorously")
475
476
477 class LoadableVegetables(cmd2.CommandSet):
478 DEFAULT_CATEGORY = "Vegetables"
479
480 def __init__(self, dummy) -> None:
481 super().__init__()
482 self._dummy = dummy # prevents autoload
483
484 def do_arugula(self, _: cmd2.Statement) -> None:
485 """Arugula Command"""
486 self._cmd.poutput("Arugula")
487
488 def complete_style_arg(self, text: str, line: str, begidx: int, endidx: int) -> Completions:
489 return Completions.from_values(["quartered", "diced"])
490
491 bokchoy_parser = cmd2.Cmd2ArgumentParser()
492 bokchoy_parser.add_argument("style", completer=complete_style_arg)
493
494 @cmd2.as_subcommand_to("cut", "bokchoy", bokchoy_parser)
495 def cut_bokchoy(self, ns: argparse.Namespace) -> None:
496 self._cmd.poutput("Bok Choy: " + ns.style)
497
498
499 def test_subcommands(manual_command_sets_app) -> None:
500 base_cmds = LoadableBase(1)
501 badbase_cmds = LoadableBadBase(1)
502 fruit_cmds = LoadableFruits(1)
503 veg_cmds = LoadableVegetables(1)
504
505 # installing subcommands without base command present raises exception
506 with pytest.raises(CommandSetRegistrationError):
507 manual_command_sets_app.register_command_set(fruit_cmds)
508
509 # if the base command is present but isn't an argparse command, expect exception
510 manual_command_sets_app.register_command_set(badbase_cmds)
511 with pytest.raises(CommandSetRegistrationError):
512 manual_command_sets_app.register_command_set(fruit_cmds)
513
514 # verify that the Fruit commands weren't installed
515 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
516 assert "Fruits" not in cmds_cats
517 assert "cut" in manual_command_sets_app.get_all_commands()
518
519 # Now install the good base commands
520 manual_command_sets_app.unregister_command_set(badbase_cmds)
521 manual_command_sets_app.register_command_set(base_cmds)
522
523 # verify that we catch an attempt to register subcommands when the commandset isn't installed
524 with pytest.raises(CommandSetRegistrationError):
525 manual_command_sets_app._register_subcommands(fruit_cmds)
526
527 cmd_result = manual_command_sets_app.app_cmd("cut")
528 assert "Error: the following arguments are required" in cmd_result.stderr
529
530 # verify that command set install without problems
531 manual_command_sets_app.register_command_set(fruit_cmds)
532 manual_command_sets_app.register_command_set(veg_cmds)
533 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
534 assert "Fruits" in cmds_cats
535
536 text = ""
537 line = f"cut {text}"
538 endidx = len(line)
539 begidx = endidx
540 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
541
542 # check that the alias shows up correctly
543 assert completions.to_strings() == Completions.from_values(["banana", "bananer", "bokchoy"]).to_strings()
544
545 cmd_result = manual_command_sets_app.app_cmd("cut banana discs")
546 assert "cutting banana: discs" in cmd_result.stdout
547
548 text = ""
549 line = f"cut bokchoy {text}"
550 endidx = len(line)
551 begidx = endidx
552 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
553
554 # verify that argparse completer in commandset functions correctly
555 assert completions.to_strings() == Completions.from_values(["diced", "quartered"]).to_strings()
556
557 # verify that command set uninstalls without problems
558 manual_command_sets_app.unregister_command_set(fruit_cmds)
559 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
560 assert "Fruits" not in cmds_cats
561
562 # verify a double-unregister raises exception
563 with pytest.raises(CommandSetRegistrationError):
564 manual_command_sets_app._unregister_subcommands(fruit_cmds)
565 manual_command_sets_app.unregister_command_set(veg_cmds)
566
567 # Disable command and verify subcommands still load and unload
568 manual_command_sets_app.disable_command("cut", "disabled for test")
569
570 # verify that command set install without problems
571 manual_command_sets_app.register_command_set(fruit_cmds)
572 manual_command_sets_app.register_command_set(veg_cmds)
573
574 manual_command_sets_app.enable_command("cut")
575
576 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
577 assert "Fruits" in cmds_cats
578
579 text = ""
580 line = f"cut {text}"
581 endidx = len(line)
582 begidx = endidx
583 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
584
585 # check that the alias shows up correctly
586 assert completions.to_strings() == Completions.from_values(["banana", "bananer", "bokchoy"]).to_strings()
587
588 text = ""
589 line = f"cut bokchoy {text}"
590 endidx = len(line)
591 begidx = endidx
592 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
593
594 # verify that argparse completer in commandset functions correctly
595 assert completions.to_strings() == Completions.from_values(["diced", "quartered"]).to_strings()
596
597 # disable again and verify can still uninstnall
598 manual_command_sets_app.disable_command("cut", "disabled for test")
599
600 # verify that command set uninstalls without problems
601 manual_command_sets_app.unregister_command_set(fruit_cmds)
602 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
603 assert "Fruits" not in cmds_cats
604
605 # verify a double-unregister raises exception
606 with pytest.raises(CommandSetRegistrationError):
607 manual_command_sets_app._unregister_subcommands(fruit_cmds)
608
609 with pytest.raises(CommandSetRegistrationError):
610 manual_command_sets_app.unregister_command_set(base_cmds)
611
612 manual_command_sets_app.unregister_command_set(veg_cmds)
613 manual_command_sets_app.unregister_command_set(base_cmds)
614
615
616 def test_commandset_sigint(manual_command_sets_app) -> None:
617 # shows that the command is able to continue execution if the sigint_handler
618 # returns True that we've handled interrupting the command.
619 class SigintHandledCommandSet(cmd2.CommandSet):
620 def do_foo(self, _) -> None:
621 """Foo Command"""
622 self._cmd.poutput("in foo")
623 self._cmd.sigint_handler(signal.SIGINT, None)
624 self._cmd.poutput("end of foo")
625
626 def sigint_handler(self) -> bool:
627 return True
628
629 cs1 = SigintHandledCommandSet()
630 manual_command_sets_app.register_command_set(cs1)
631 out = manual_command_sets_app.app_cmd("foo")
632 assert "in foo" in out.stdout
633 assert "end of foo" in out.stdout
634
635 # shows that the command is interrupted if we don't report we've handled the sigint
636 class SigintUnhandledCommandSet(cmd2.CommandSet):
637 def do_bar(self, _) -> None:
638 """Bar Command"""
639 self._cmd.poutput("in do bar")
640 self._cmd.sigint_handler(signal.SIGINT, None)
641 self._cmd.poutput("end of do bar")
642
643 cs2 = SigintUnhandledCommandSet()
644 manual_command_sets_app.register_command_set(cs2)
645 out = manual_command_sets_app.app_cmd("bar")
646 assert "in do bar" in out.stdout
647 assert "end of do bar" not in out.stdout
648
649
650 def test_nested_subcommands(manual_command_sets_app) -> None:
651 base_cmds = LoadableBase(1)
652 pasta_cmds = LoadablePastaStir(1)
653
654 with pytest.raises(CommandSetRegistrationError):
655 manual_command_sets_app.register_command_set(pasta_cmds)
656
657 manual_command_sets_app.register_command_set(base_cmds)
658
659 manual_command_sets_app.register_command_set(pasta_cmds)
660
661 with pytest.raises(CommandSetRegistrationError):
662 manual_command_sets_app.unregister_command_set(base_cmds)
663
664 class BadNestedSubcommands(cmd2.CommandSet):
665 def __init__(self, dummy) -> None:
666 super().__init__()
667 self._dummy = dummy # prevents autoload
668
669 stir_pasta_vigor_parser = cmd2.Cmd2ArgumentParser()
670 stir_pasta_vigor_parser.add_argument("frequency")
671
672 # stir sauce doesn't exist anywhere, this should fail
673 @cmd2.as_subcommand_to("stir sauce", "vigorously", stir_pasta_vigor_parser)
674 def stir_pasta_vigorously(self, ns: argparse.Namespace) -> None:
675 self._cmd.poutput("stir the pasta vigorously")
676
677 with pytest.raises(CommandSetRegistrationError):
678 manual_command_sets_app.register_command_set(BadNestedSubcommands(1))
679
680 fruit_cmds = LoadableFruits(1)
681 manual_command_sets_app.register_command_set(fruit_cmds)
682
683 # validates custom namespace provider works correctly. Stir command will fail until
684 # the cut command is called
685 result = manual_command_sets_app.app_cmd("stir pasta vigorously everyminute")
686 assert "Need to cut before stirring" in result.stdout
687
688 result = manual_command_sets_app.app_cmd("cut banana discs")
689 assert "cutting banana: discs" in result.stdout
690
691 result = manual_command_sets_app.app_cmd("stir pasta vigorously everyminute")
692 assert "stir the pasta vigorously" in result.stdout
693
694
695 class AppWithSubCommands(cmd2.Cmd):
696 """Class for testing usage of `as_subcommand_to` decorator directly in a Cmd2 subclass."""
697
698 def __init__(self, *args, **kwargs) -> None:
699 super().__init__(*args, **kwargs)
700
701 cut_parser = cmd2.Cmd2ArgumentParser()
702 cut_parser.add_subparsers(title="item", help="item to cut", metavar="ITEM", required=True)
703
704 @cmd2.with_argparser(cut_parser)
705 def do_cut(self, ns: argparse.Namespace) -> None:
706 """Cut something"""
707 # Call whatever subcommand function was selected
708 ns.cmd2_subcommand_func(ns)
709
710 banana_parser = cmd2.Cmd2ArgumentParser()
711 banana_parser.add_argument("direction", choices=["discs", "lengthwise"])
712
713 @cmd2.as_subcommand_to("cut", "banana", banana_parser, help="Cut banana", aliases=["bananer"])
714 def cut_banana(self, ns: argparse.Namespace) -> None:
715 """Cut banana"""
716 self.poutput("cutting banana: " + ns.direction)
717
718 def complete_style_arg(self, text: str, line: str, begidx: int, endidx: int) -> Completions:
719 return Completions.from_values(["quartered", "diced"])
720
721 bokchoy_parser = cmd2.Cmd2ArgumentParser()
722 bokchoy_parser.add_argument("style", completer=complete_style_arg)
723
724 @cmd2.as_subcommand_to("cut", "bokchoy", bokchoy_parser)
725 def cut_bokchoy(self, _: argparse.Namespace) -> None:
726 self.poutput("Bok Choy")
727
728
729 @pytest.fixture
730 def static_subcommands_app():
731 return AppWithSubCommands(auto_load_commands=True)
732
733
734 def test_static_subcommands(static_subcommands_app) -> None:
735 cmds_cats, _help_topics = static_subcommands_app._build_command_info()
736 assert "Fruits" in cmds_cats
737
738 text = ""
739 line = f"cut {text}"
740 endidx = len(line)
741 begidx = endidx
742 completions = static_subcommands_app.complete(text, line, begidx, endidx)
743
744 # check that the alias shows up correctly
745 assert completions.to_strings() == Completions.from_values(["banana", "bananer", "bokchoy"]).to_strings()
746
747 text = ""
748 line = f"cut bokchoy {text}"
749 endidx = len(line)
750 begidx = endidx
751 completions = static_subcommands_app.complete(text, line, begidx, endidx)
752
753 # verify that argparse completer in commandset functions correctly
754 assert completions.to_strings() == Completions.from_values(["diced", "quartered"]).to_strings()
755
756
757 complete_states_expected_self = None
758
759
760 class SupportFuncProvider(cmd2.CommandSet):
761 """CommandSet which provides a support function (complete_states) to other CommandSets"""
762
763 DEFAULT_CATEGORY = "With Completer"
764 states = ("alabama", "alaska", "arizona", "arkansas", "california", "colorado", "connecticut", "delaware")
765
766 def __init__(self, dummy) -> None:
767 """Dummy variable prevents this from being autoloaded in other tests"""
768 super().__init__()
769
770 def complete_states(self, text: str, line: str, begidx: int, endidx: int) -> Completions:
771 assert self is complete_states_expected_self
772 return self._cmd.basic_complete(text, line, begidx, endidx, self.states)
773
774
775 class SupportFuncUserSubclass1(SupportFuncProvider):
776 """A sub-class of SupportFuncProvider which uses its support function"""
777
778 parser = cmd2.Cmd2ArgumentParser()
779 parser.add_argument("state", type=str, completer=SupportFuncProvider.complete_states)
780
781 @cmd2.with_argparser(parser)
782 def do_user_sub1(self, ns: argparse.Namespace) -> None:
783 """User Sub1 Command"""
784 self._cmd.poutput(f"something {ns.state}")
785
786
787 class SupportFuncUserSubclass2(SupportFuncProvider):
788 """A second sub-class of SupportFuncProvider which uses its support function"""
789
790 parser = cmd2.Cmd2ArgumentParser()
791 parser.add_argument("state", type=str, completer=SupportFuncProvider.complete_states)
792
793 @cmd2.with_argparser(parser)
794 def do_user_sub2(self, ns: argparse.Namespace) -> None:
795 """User sub2 Command"""
796 self._cmd.poutput(f"something {ns.state}")
797
798
799 class SupportFuncUserUnrelated(cmd2.CommandSet):
800 """A CommandSet that isn't related to SupportFuncProvider which uses its support function"""
801
802 def __init__(self, dummy) -> None:
803 """Dummy variable prevents this from being autoloaded in other tests"""
804 super().__init__()
805
806 parser = cmd2.Cmd2ArgumentParser()
807 parser.add_argument("state", type=str, completer=SupportFuncProvider.complete_states)
808
809 @cmd2.with_argparser(parser)
810 def do_user_unrelated(self, ns: argparse.Namespace) -> None:
811 """User Unrelated Command"""
812 self._cmd.poutput(f"something {ns.state}")
813
814
815 def test_cross_commandset_completer(manual_command_sets_app) -> None:
816 global complete_states_expected_self # noqa: PLW0603
817 # This tests the different ways to locate the matching CommandSet when completing an argparse argument.
818 # Exercises the 3 cases in cmd2.Cmd._resolve_func_self() which is called during argparse tab completion.
819
820 # Create all the CommandSets for these tests
821 func_provider = SupportFuncProvider(1)
822 user_sub1 = SupportFuncUserSubclass1(2)
823 user_sub2 = SupportFuncUserSubclass2(3)
824 user_unrelated = SupportFuncUserUnrelated(4)
825
826 ####################################################################################################################
827 # This exercises Case 1
828 # If the CommandSet holding a command is a sub-class of the class that defines the completer function, then use that
829 # CommandSet instance as self when calling the completer
830
831 # Create instances of two different sub-class types to ensure no one removes the case 1 check in Cmd._resolve_func_self().
832 # If that check is removed, testing with only 1 sub-class type will still pass. Testing it with two sub-class types
833 # will fail and show that the case 1 check cannot be removed.
834 manual_command_sets_app.register_command_set(user_sub1)
835 manual_command_sets_app.register_command_set(user_sub2)
836
837 text = ""
838 line = f"user_sub1 {text}"
839 endidx = len(line)
840 begidx = endidx
841 complete_states_expected_self = user_sub1
842 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
843 complete_states_expected_self = None
844
845 assert completions.to_strings() == Completions.from_values(SupportFuncProvider.states).to_strings()
846
847 cmds_cats, _help_topics = manual_command_sets_app._build_command_info()
848 assert "user_sub1" in cmds_cats["With Completer"]
849
850 manual_command_sets_app.unregister_command_set(user_sub2)
851 manual_command_sets_app.unregister_command_set(user_sub1)
852
853 ####################################################################################################################
854 # This exercises Case 2
855 # If the CommandSet holding a command is unrelated to the CommandSet holding the completer function, then search
856 # all installed CommandSet instances for one that is an exact type match
857
858 manual_command_sets_app.register_command_set(func_provider)
859 manual_command_sets_app.register_command_set(user_unrelated)
860
861 text = ""
862 line = f"user_unrelated {text}"
863 endidx = len(line)
864 begidx = endidx
865 complete_states_expected_self = func_provider
866 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
867 complete_states_expected_self = None
868
869 assert completions.to_strings() == Completions.from_values(SupportFuncProvider.states).to_strings()
870
871 manual_command_sets_app.unregister_command_set(user_unrelated)
872 manual_command_sets_app.unregister_command_set(func_provider)
873
874 ####################################################################################################################
875 # This exercises Case 3
876 # If the CommandSet holding a command is unrelated to the CommandSet holding the completer function,
877 # and no exact type match can be found, but sub-class matches can be found and there is only a single
878 # sub-class match, then use the lone sub-class match as the parent CommandSet.
879
880 manual_command_sets_app.register_command_set(user_sub1)
881 manual_command_sets_app.register_command_set(user_unrelated)
882
883 text = ""
884 line = f"user_unrelated {text}"
885 endidx = len(line)
886 begidx = endidx
887 complete_states_expected_self = user_sub1
888 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
889 complete_states_expected_self = None
890
891 assert completions.to_strings() == Completions.from_values(SupportFuncProvider.states).to_strings()
892
893 manual_command_sets_app.unregister_command_set(user_unrelated)
894 manual_command_sets_app.unregister_command_set(user_sub1)
895
896 ####################################################################################################################
897 # Error Case 1
898 # If the CommandSet holding a command is unrelated to the CommandSet holding the completer function, then search
899 # all installed CommandSet instances for one that is an exact type match, none are found
900 # search for sub-class matches, also none are found.
901
902 manual_command_sets_app.register_command_set(user_unrelated)
903
904 text = ""
905 line = f"user_unrelated {text}"
906 endidx = len(line)
907 begidx = endidx
908 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
909
910 assert not completions
911 assert "Could not find CommandSet instance" in completions.error
912
913 manual_command_sets_app.unregister_command_set(user_unrelated)
914
915 ####################################################################################################################
916 # Error Case 2
917 # If the CommandSet holding a command is unrelated to the CommandSet holding the completer function, then search
918 # all installed CommandSet instances for one that is an exact type match, none are found
919 # search for sub-class matches, more than 1 is found.
920
921 manual_command_sets_app.register_command_set(user_sub1)
922 manual_command_sets_app.register_command_set(user_sub2)
923 manual_command_sets_app.register_command_set(user_unrelated)
924
925 text = ""
926 line = f"user_unrelated {text}"
927 endidx = len(line)
928 begidx = endidx
929 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
930
931 assert not completions
932 assert "Could not find CommandSet instance" in completions.error
933
934 manual_command_sets_app.unregister_command_set(user_unrelated)
935 manual_command_sets_app.unregister_command_set(user_sub2)
936 manual_command_sets_app.unregister_command_set(user_sub1)
937
938
939 class CommandSetWithPathComplete(cmd2.CommandSet):
940 def __init__(self, dummy) -> None:
941 """Dummy variable prevents this from being autoloaded in other tests"""
942 super().__init__()
943
944 parser = cmd2.Cmd2ArgumentParser()
945 parser.add_argument("path", nargs="+", help="paths", completer=cmd2.Cmd.path_complete)
946
947 @cmd2.with_argparser(parser)
948 def do_path(self, app: cmd2.Cmd, args) -> None:
949 """Path Command"""
950 app.poutput(args.path)
951
952
953 def test_path_complete(manual_command_sets_app) -> None:
954 test_set = CommandSetWithPathComplete(1)
955
956 manual_command_sets_app.register_command_set(test_set)
957
958 text = ""
959 line = f"path {text}"
960 endidx = len(line)
961 begidx = endidx
962 completions = manual_command_sets_app.complete(text, line, begidx, endidx)
963
964 assert completions
965
966
967 def test_bad_subcommand() -> None:
968 class BadSubcommandApp(cmd2.Cmd):
969 """Class for testing usage of `as_subcommand_to` decorator directly in a Cmd2 subclass."""
970
971 def __init__(self, *args, **kwargs) -> None:
972 super().__init__(*args, **kwargs)
973
974 cut_parser = cmd2.Cmd2ArgumentParser()
975 cut_parser.add_subparsers(title="item", help="item to cut", metavar="ITEM", required=True)
976
977 @cmd2.with_argparser(cut_parser)
978 def do_cut(self, ns: argparse.Namespace) -> None:
979 """Cut something"""
980
981 banana_parser = cmd2.Cmd2ArgumentParser()
982 banana_parser.add_argument("direction", choices=["discs", "lengthwise"])
983
984 @cmd2.as_subcommand_to("cut", "bad name", banana_parser, help="This should fail")
985 def cut_banana(self, ns: argparse.Namespace) -> None:
986 """Cut banana"""
987 self.poutput("cutting banana: " + ns.direction)
988
989 with pytest.raises(CommandSetRegistrationError):
990 BadSubcommandApp()
991
992
993 def test_commandset_settables() -> None:
994 # Define an arbitrary class with some attribute
995 class Arbitrary:
996 def __init__(self) -> None:
997 self.some_value = 5
998
999 # Declare a CommandSet with a settable of some arbitrary property
1000 class WithSettablesA(CommandSetBase):
1001 def __init__(self) -> None:
1002 super().__init__()
1003
1004 self._arbitrary = Arbitrary()
1005 self._settable_prefix = "addon"
1006 self.my_int = 11
1007
1008 self.add_settable(
1009 Settable(
1010 "arbitrary_value",
1011 int,
1012 "Some settable value",
1013 settable_object=self._arbitrary,
1014 settable_attrib_name="some_value",
1015 )
1016 )
1017
1018 # Declare a CommandSet with an empty settable prefix
1019 class WithSettablesNoPrefix(CommandSetBase):
1020 def __init__(self) -> None:
1021 super().__init__()
1022
1023 self._arbitrary = Arbitrary()
1024 self._settable_prefix = ""
1025 self.my_int = 11
1026
1027 self.add_settable(
1028 Settable(
1029 "another_value",
1030 float,
1031 "Some settable value",
1032 settable_object=self._arbitrary,
1033 settable_attrib_name="some_value",
1034 )
1035 )
1036
1037 # Declare a commandset with duplicate settable name
1038 class WithSettablesB(CommandSetBase):
1039 def __init__(self) -> None:
1040 super().__init__()
1041
1042 self._arbitrary = Arbitrary()
1043 self._settable_prefix = "some"
1044 self.my_int = 11
1045
1046 self.add_settable(
1047 Settable(
1048 "arbitrary_value",
1049 int,
1050 "Some settable value",
1051 settable_object=self._arbitrary,
1052 settable_attrib_name="some_value",
1053 )
1054 )
1055
1056 # create the command set and cmd2
1057 cmdset = WithSettablesA()
1058 arbitrary2 = Arbitrary()
1059 app = cmd2.Cmd(command_sets=[cmdset], auto_load_commands=False)
1060 app.str_value = ""
1061 app.add_settable(Settable("always_prefix_settables", bool, "Prefix settables", app))
1062 app._settables["str_value"] = Settable("str_value", str, "String value", app)
1063
1064 assert "arbitrary_value" in app.settables
1065 assert "always_prefix_settables" in app.settables
1066 assert "str_value" in app.settables
1067
1068 # verify the settable shows up
1069 out, err = run_cmd(app, "set")
1070 any("arbitrary_value" in line and "5" in line for line in out)
1071
1072 out, err = run_cmd(app, "set arbitrary_value")
1073 any("arbitrary_value" in line and "5" in line for line in out)
1074
1075 # change the value and verify the value changed
1076 out, err = run_cmd(app, "set arbitrary_value 10")
1077 assert not err
1078 assert out[0].startswith("arbitrary_value")
1079 assert out[0].endswith("─> 10")
1080 out, err = run_cmd(app, "set arbitrary_value")
1081 any("arbitrary_value" in line and "10" in line for line in out)
1082
1083 # can't add to cmd2 now because commandset already has this settable
1084 with pytest.raises(KeyError):
1085 app.add_settable(Settable("arbitrary_value", int, "This should fail", app))
1086
1087 cmdset.add_settable(
1088 Settable("arbitrary_value", int, "Replaced settable", settable_object=arbitrary2, settable_attrib_name="some_value")
1089 )
1090
1091 # Can't add a settable to the commandset that already exists in cmd2
1092 with pytest.raises(KeyError):
1093 cmdset.add_settable(Settable("always_prefix_settables", int, "This should also fail", cmdset))
1094
1095 # Can't remove a settable from the CommandSet if it is elsewhere and not in the CommandSet
1096 with pytest.raises(KeyError):
1097 cmdset.remove_settable("always_prefix_settables")
1098
1099 # verify registering a commandset with duplicate settable names fails
1100 cmdset_dupname = WithSettablesB()
1101 with pytest.raises(CommandSetRegistrationError):
1102 app.register_command_set(cmdset_dupname)
1103
1104 # unregister the CommandSet and verify the settable is now gone
1105 app.unregister_command_set(cmdset)
1106 out, err = run_cmd(app, "set")
1107 assert "arbitrary_value" not in out
1108 out, err = run_cmd(app, "set arbitrary_value")
1109 expected = """
1110 Parameter 'arbitrary_value' not supported (type 'set' for list of parameters).
1111 """
1112 assert err == normalize(expected)
1113
1114 # Add a commandset with no prefix
1115 cmdset_nopfx = WithSettablesNoPrefix()
1116 app.register_command_set(cmdset_nopfx)
1117
1118 with pytest.raises(
1119 ValueError,
1120 match=r"Cannot force settable prefixes. CommandSet WithSettablesNoPrefix does not have a settable prefix defined.",
1121 ):
1122 app.always_prefix_settables = True
1123
1124 app.unregister_command_set(cmdset_nopfx)
1125
1126 # turn on prefixes and add the commandset back
1127 app.always_prefix_settables = True
1128
1129 with pytest.raises(CommandSetRegistrationError):
1130 app.register_command_set(cmdset_nopfx)
1131
1132 app.register_command_set(cmdset)
1133
1134 # Verify the settable is back with the defined prefix.
1135 assert "addon.arbitrary_value" in app.settables
1136
1137 # rename the prefix and verify that the prefix changes everywhere
1138 cmdset._settable_prefix = "some"
1139 assert "addon.arbitrary_value" not in app.settables
1140 assert "some.arbitrary_value" in app.settables
1141
1142 out, err = run_cmd(app, "set")
1143 any("some.arbitrary_value" in line and "5" in line for line in out)
1144
1145 out, err = run_cmd(app, "set some.arbitrary_value")
1146 any("some.arbitrary_value" in line and "5" in line for line in out)
1147
1148 # verify registering a commandset with duplicate prefix and settable names fails
1149 with pytest.raises(CommandSetRegistrationError):
1150 app.register_command_set(cmdset_dupname)
1151
1152 cmdset_dupname.remove_settable("arbitrary_value")
1153
1154 app.register_command_set(cmdset_dupname)
1155
1156 with pytest.raises(KeyError):
1157 cmdset_dupname.add_settable(
1158 Settable(
1159 "arbitrary_value",
1160 int,
1161 "Some settable value",
1162 settable_object=cmdset_dupname._arbitrary,
1163 settable_attrib_name="some_value",
1164 )
1165 )
1166
1167
1168 class NsProviderSet(cmd2.CommandSet):
1169 # CommandSet which implements a namespace provider
1170 def __init__(self, dummy) -> None:
1171 # Use dummy argument so this won't be autoloaded by other tests
1172 super().__init__()
1173
1174 def ns_provider(self) -> argparse.Namespace:
1175 ns = argparse.Namespace()
1176 # Save what was passed as self from with_argparser().
1177 ns.self = self
1178 return ns
1179
1180
1181 class NsProviderApp(cmd2.Cmd):
1182 # Used to test namespace providers in CommandSets
1183 def __init__(self, *args, **kwargs) -> None:
1184 super().__init__(*args, **kwargs)
1185 super().__init__(*args, **kwargs)
1186
1187 @cmd2.with_argparser(cmd2.Cmd2ArgumentParser(), ns_provider=NsProviderSet.ns_provider)
1188 def do_test_ns(self, args: argparse.Namespace) -> None:
1189 # Save args.self so the unit tests can read it.
1190 self.last_result = args.self
1191
1192
1193 def test_ns_provider() -> None:
1194 """This exercises code in with_argparser() decorator that calls namespace providers"""
1195 ns_provider_set = NsProviderSet(1)
1196 app = NsProviderApp(auto_load_commands=False)
1197
1198 # First test the case in which a namespace provider function resides in a CommandSet class which is registered.
1199 # with_argparser() will pass the CommandSet instance to the ns_provider() function.
1200 app.register_command_set(ns_provider_set)
1201 run_cmd(app, "test_ns")
1202 assert app.last_result == ns_provider_set
1203
1204 # Now test the case in which a namespace provider function resides in a CommandSet class which is not registered.
1205 # with_argparser() will receive None from cmd2.Cmd._resolve_func_self() and therefore pass app as self to ns_provider().
1206 app.unregister_command_set(ns_provider_set)
1207 run_cmd(app, "test_ns")
1208 assert app.last_result == app