Debian Codegraph @

tests/test_argparse_completer.py

raw symbols SCIP
1 """Unit/functional testing for argparse completer in cmd2"""
2
3 import argparse
4 from typing import cast
5
6 import pytest
7 from rich.text import Text
8
9 import cmd2
10 import cmd2.string_utils as su
11 from cmd2 import (
12 Choices,
13 Cmd2ArgumentParser,
14 CompletionError,
15 CompletionItem,
16 Completions,
17 argparse_completer,
18 argparse_utils,
19 with_argparser,
20 )
21 from cmd2 import rich_utils as ru
22
23 from .conftest import (
24 run_cmd,
25 with_ansi_style,
26 )
27
28 # Data and functions for testing standalone choice_provider and completer
29 standalone_choices = ["standalone", "provider"]
30 standalone_completions = ["standalone", "completer"]
31
32
33 def standalone_choice_provider(cli: cmd2.Cmd) -> Choices:
34 return Choices.from_values(standalone_choices)
35
36
37 def standalone_completer(cli: cmd2.Cmd, text: str, line: str, begidx: int, endidx: int) -> Completions:
38 return cli.basic_complete(text, line, begidx, endidx, standalone_completions)
39
40
41 class ArgparseCompleterTester(cmd2.Cmd):
42 """Cmd2 app that exercises ArgparseCompleter class"""
43
44 def __init__(self, *args, **kwargs) -> None:
45 super().__init__(*args, **kwargs)
46
47 ############################################################################################################
48 # Begin code related to help and command name completion
49 ############################################################################################################
50 # Top level parser for music command
51 music_parser = Cmd2ArgumentParser(description="Manage music")
52
53 # Add subcommands to music
54 music_subparsers = music_parser.add_subparsers()
55 music_create_parser = music_subparsers.add_parser("create", help="create music")
56
57 # Add subcommands to music -> create
58 music_create_subparsers = music_create_parser.add_subparsers()
59 music_create_jazz_parser = music_create_subparsers.add_parser("jazz", help="create jazz")
60 music_create_rock_parser = music_create_subparsers.add_parser("rock", help="create rock")
61
62 @with_argparser(music_parser)
63 def do_music(self, args: argparse.Namespace) -> None:
64 pass
65
66 ############################################################################################################
67 # Begin code related to flag completion
68 ############################################################################################################
69
70 # Uses default flag prefix value (-)
71 flag_parser = Cmd2ArgumentParser()
72 flag_parser.add_argument("-n", "--normal_flag", help="a normal flag", action="store_true")
73 flag_parser.add_argument("-a", "--append_flag", help="append flag", action="append")
74 flag_parser.add_argument("-o", "--append_const_flag", help="append const flag", action="append_const", const=True)
75 flag_parser.add_argument("-c", "--count_flag", help="count flag", action="count")
76 flag_parser.add_argument("-e", "--extend_flag", help="extend flag", action="extend")
77 flag_parser.add_argument("-s", "--suppressed_flag", help=argparse.SUPPRESS, action="store_true")
78 flag_parser.add_argument("-r", "--remainder_flag", nargs=argparse.REMAINDER, help="a remainder flag")
79 flag_parser.add_argument("-q", "--required_flag", required=True, help="a required flag", action="store_true")
80
81 @with_argparser(flag_parser)
82 def do_flag(self, args: argparse.Namespace) -> None:
83 pass
84
85 # Uses non-default flag prefix value (+)
86 plus_flag_parser = Cmd2ArgumentParser(prefix_chars="+")
87 plus_flag_parser.add_argument("+n", "++normal_flag", help="a normal flag", action="store_true")
88 plus_flag_parser.add_argument("+q", "++required_flag", required=True, help="a required flag", action="store_true")
89
90 @with_argparser(plus_flag_parser)
91 def do_plus_flag(self, args: argparse.Namespace) -> None:
92 pass
93
94 # A parser with a positional and flags. Used to test that remaining flag names are completed when all positionals are done.
95 pos_and_flag_parser = Cmd2ArgumentParser()
96 pos_and_flag_parser.add_argument("positional", choices=["a", "choice"])
97 pos_and_flag_parser.add_argument("-f", "--flag", action="store_true")
98
99 @with_argparser(pos_and_flag_parser)
100 def do_pos_and_flag(self, args: argparse.Namespace) -> None:
101 pass
102
103 ############################################################################################################
104 # Begin code related to testing choices and choices_provider parameters
105 ############################################################################################################
106 STR_METAVAR = "HEADLESS"
107 TUPLE_METAVAR = ("arg1", "others")
108 DESCRIPTION_TABLE_COLUMNS = ("Description",)
109
110 # tuples (for sake of immutability) used in our tests (there is a mix of sorted and unsorted on purpose)
111 non_negative_num_choices = (1, 2, 3, 0.5, 22)
112 num_choices = (-1, 1, -2, 2.5, 0, -12)
113 static_choices_list = ("static", "choices", "stop", "here")
114 choices_from_provider = ("choices", "provider", "probably", "improved")
115 completion_item_choices = (
116 CompletionItem("choice_1", table_data=["Description 1"]),
117 CompletionItem("choice_2", table_data=[su.stylize("String with style", style=cmd2.Color.BLUE)]),
118 CompletionItem("choice_3", table_data=[Text("Text with style", style=cmd2.Color.RED)]),
119 )
120
121 # This tests that CompletionItems created with numerical values are sorted as numbers.
122 num_completion_items = (
123 CompletionItem(5, table_data=["Five"]),
124 CompletionItem(1.5, table_data=["One.Five"]),
125 CompletionItem(2, table_data=["Two"]),
126 )
127
128 def choices_provider(self) -> Choices:
129 """Method that provides choices"""
130 return Choices.from_values(self.choices_from_provider)
131
132 def completion_item_method(self) -> list[CompletionItem]:
133 """Choices method that returns CompletionItems"""
134 items = []
135 for i in range(10):
136 main_str = f"main_str{i}"
137 items.append(CompletionItem(main_str, table_data=["blah blah"]))
138 return items
139
140 choices_parser = Cmd2ArgumentParser()
141
142 # Flag args for choices command. Include string and non-string arg types.
143 choices_parser.add_argument(
144 "-l",
145 "--list",
146 help="a flag populated with a choices list",
147 choices=static_choices_list,
148 )
149 choices_parser.add_argument(
150 "-p",
151 "--provider",
152 help="a flag populated with a choices provider",
153 choices_provider=choices_provider,
154 )
155 choices_parser.add_argument(
156 "--no_metavar",
157 help="this arg has no metavar",
158 choices_provider=completion_item_method,
159 table_columns=DESCRIPTION_TABLE_COLUMNS,
160 )
161 choices_parser.add_argument(
162 "--str_metavar",
163 help="this arg has str for a metavar",
164 choices_provider=completion_item_method,
165 metavar=STR_METAVAR,
166 table_columns=DESCRIPTION_TABLE_COLUMNS,
167 )
168 choices_parser.add_argument(
169 "-t",
170 "--tuple_metavar",
171 help="this arg has tuple for a metavar",
172 metavar=TUPLE_METAVAR,
173 nargs=argparse.ONE_OR_MORE,
174 choices_provider=completion_item_method,
175 table_columns=DESCRIPTION_TABLE_COLUMNS,
176 )
177 choices_parser.add_argument(
178 "-n",
179 "--num",
180 type=int,
181 help="a flag with an int type",
182 choices=num_choices,
183 )
184 choices_parser.add_argument(
185 "--completion_items",
186 help="choices are CompletionItems",
187 choices=completion_item_choices,
188 table_columns=DESCRIPTION_TABLE_COLUMNS,
189 )
190 choices_parser.add_argument(
191 "--num_completion_items",
192 help="choices are numerical CompletionItems",
193 choices=num_completion_items,
194 table_columns=DESCRIPTION_TABLE_COLUMNS,
195 )
196
197 # Positional args for choices command
198 choices_parser.add_argument(
199 "list_pos",
200 help="a positional populated with a choices list",
201 choices=static_choices_list,
202 )
203 choices_parser.add_argument(
204 "method_pos",
205 help="a positional populated with a choices provider",
206 choices_provider=choices_provider,
207 )
208 choices_parser.add_argument(
209 "non_negative_num",
210 type=int,
211 help="a positional with non-negative numerical choices",
212 choices=non_negative_num_choices,
213 )
214 choices_parser.add_argument(
215 "empty_choices",
216 help="a positional with empty choices",
217 choices=[],
218 )
219
220 @with_argparser(choices_parser)
221 def do_choices(self, args: argparse.Namespace) -> None:
222 pass
223
224 ############################################################################################################
225 # Begin code related to testing completer parameter
226 ############################################################################################################
227 completions_for_flag = ("completions", "flag", "fairly", "complete")
228 completions_for_pos_1 = ("completions", "positional_1", "probably", "missed", "spot")
229 completions_for_pos_2 = ("completions", "positional_2", "probably", "missed", "me")
230
231 def flag_completer(self, text: str, line: str, begidx: int, endidx: int) -> Completions:
232 return self.basic_complete(text, line, begidx, endidx, self.completions_for_flag)
233
234 def pos_1_completer(self, text: str, line: str, begidx: int, endidx: int) -> Completions:
235 return self.basic_complete(text, line, begidx, endidx, self.completions_for_pos_1)
236
237 def pos_2_completer(self, text: str, line: str, begidx: int, endidx: int) -> Completions:
238 return self.basic_complete(text, line, begidx, endidx, self.completions_for_pos_2)
239
240 completer_parser = Cmd2ArgumentParser()
241
242 # Flag args for completer command
243 completer_parser.add_argument("-c", "--completer", help="a flag using a completer", completer=flag_completer)
244
245 # Positional args for completer command
246 completer_parser.add_argument("pos_1", help="a positional using a completer method", completer=pos_1_completer)
247 completer_parser.add_argument("pos_2", help="a positional using a completer method", completer=pos_2_completer)
248
249 @with_argparser(completer_parser)
250 def do_completer(self, args: argparse.Namespace) -> None:
251 pass
252
253 ############################################################################################################
254 # Begin code related to nargs
255 ############################################################################################################
256 set_value_choices = ("set", "value", "choices")
257 one_or_more_choices = ("one", "or", "more", "choices")
258 optional_choices = ("a", "few", "optional", "choices")
259 range_choices = ("some", "range", "choices")
260 remainder_choices = ("remainder", "choices")
261 positional_choices = ("the", "positional", "choices")
262
263 nargs_parser = Cmd2ArgumentParser()
264
265 # Flag args for nargs command
266 nargs_parser.add_argument("--set_value", help="a flag with a set value for nargs", nargs=2, choices=set_value_choices)
267 nargs_parser.add_argument(
268 "--one_or_more", help="a flag wanting one or more args", nargs=argparse.ONE_OR_MORE, choices=one_or_more_choices
269 )
270 nargs_parser.add_argument(
271 "--optional", help="a flag with an optional value", nargs=argparse.OPTIONAL, choices=optional_choices
272 )
273 nargs_parser.add_argument("--range", help="a flag with nargs range", nargs=(1, 2), choices=range_choices)
274 nargs_parser.add_argument(
275 "--remainder", help="a flag wanting remaining", nargs=argparse.REMAINDER, choices=remainder_choices
276 )
277
278 nargs_parser.add_argument("normal_pos", help="a remainder positional", nargs=2, choices=positional_choices)
279 nargs_parser.add_argument(
280 "remainder_pos", help="a remainder positional", nargs=argparse.REMAINDER, choices=remainder_choices
281 )
282
283 @with_argparser(nargs_parser)
284 def do_nargs(self, args: argparse.Namespace) -> None:
285 pass
286
287 ############################################################################################################
288 # Begin code related to testing tab hints
289 ############################################################################################################
290 hint_parser = Cmd2ArgumentParser()
291 hint_parser.add_argument("-f", "--flag", help="a flag arg")
292 hint_parser.add_argument("-s", "--suppressed_help", help=argparse.SUPPRESS)
293 hint_parser.add_argument("-t", "--suppressed_hint", help="a flag arg", suppress_tab_hint=True)
294
295 hint_parser.add_argument("hint_pos", help="here is a hint\nwith new lines")
296 hint_parser.add_argument("no_help_pos")
297
298 @with_argparser(hint_parser)
299 def do_hint(self, args: argparse.Namespace) -> None:
300 pass
301
302 ############################################################################################################
303 # Begin code related to CompletionError
304 ############################################################################################################
305 def completer_raise_error(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
306 """Raises CompletionError"""
307 raise CompletionError("completer broke something")
308
309 def choice_raise_completion_error(self) -> list[str]:
310 """Raises CompletionError"""
311 raise CompletionError("choice broke something")
312
313 comp_error_parser = Cmd2ArgumentParser()
314 comp_error_parser.add_argument("completer_pos", help="positional arg", completer=completer_raise_error)
315 comp_error_parser.add_argument("--choice", help="flag arg", choices_provider=choice_raise_completion_error)
316
317 @with_argparser(comp_error_parser)
318 def do_raise_completion_error(self, args: argparse.Namespace) -> None:
319 pass
320
321 ############################################################################################################
322 # Begin code related to receiving arg_tokens
323 ############################################################################################################
324 def choices_takes_arg_tokens(self, arg_tokens: dict[str, list[str]]) -> Choices:
325 """Choices function that receives arg_tokens from ArgparseCompleter"""
326 return Choices.from_values([arg_tokens["parent_arg"][0], arg_tokens["subcommand"][0]])
327
328 def completer_takes_arg_tokens(
329 self, text: str, line: str, begidx: int, endidx: int, arg_tokens: dict[str, list[str]]
330 ) -> Completions:
331 """Completer function that receives arg_tokens from ArgparseCompleter"""
332 match_against = [arg_tokens["parent_arg"][0], arg_tokens["subcommand"][0]]
333 return self.basic_complete(text, line, begidx, endidx, match_against)
334
335 arg_tokens_parser = Cmd2ArgumentParser()
336 arg_tokens_parser.add_argument("parent_arg", help="arg from a parent parser")
337
338 # Create a subcommand to exercise receiving parent_tokens and subcommand name in arg_tokens
339 arg_tokens_subparser = arg_tokens_parser.add_subparsers(dest="subcommand")
340 arg_tokens_subcmd_parser = arg_tokens_subparser.add_parser("subcmd")
341
342 arg_tokens_subcmd_parser.add_argument("choices_pos", choices_provider=choices_takes_arg_tokens)
343 arg_tokens_subcmd_parser.add_argument("completer_pos", completer=completer_takes_arg_tokens)
344
345 # Used to override parent_arg in arg_tokens_parser
346 arg_tokens_subcmd_parser.add_argument("--parent_arg")
347
348 @with_argparser(arg_tokens_parser)
349 def do_arg_tokens(self, args: argparse.Namespace) -> None:
350 pass
351
352 ############################################################################################################
353 # Begin code related to mutually exclusive groups
354 ############################################################################################################
355 mutex_parser = Cmd2ArgumentParser()
356
357 mutex_group = mutex_parser.add_mutually_exclusive_group(required=True)
358 mutex_group.add_argument("optional_pos", help="the optional positional", nargs=argparse.OPTIONAL)
359 mutex_group.add_argument("-f", "--flag", help="the flag arg")
360 mutex_group.add_argument("-o", "--other_flag", help="the other flag arg")
361
362 mutex_parser.add_argument("last_arg", help="the last arg")
363
364 @with_argparser(mutex_parser)
365 def do_mutex(self, args: argparse.Namespace) -> None:
366 pass
367
368 ############################################################################################################
369 # Begin code related to standalone functions
370 ############################################################################################################
371 standalone_parser = Cmd2ArgumentParser()
372 standalone_parser.add_argument("--provider", help="standalone provider", choices_provider=standalone_choice_provider)
373 standalone_parser.add_argument("--completer", help="standalone completer", completer=standalone_completer)
374
375 @with_argparser(standalone_parser)
376 def do_standalone(self, args: argparse.Namespace) -> None:
377 pass
378
379 ############################################################################################################
380 # Begin code related to display_meta data
381 ############################################################################################################
382 meta_parser = Cmd2ArgumentParser()
383
384 # Add subcommands to meta
385 meta_subparsers = meta_parser.add_subparsers()
386
387 # Create subcommands with and without help text
388 meta_helpful_parser = meta_subparsers.add_parser("helpful", help="my helpful text")
389 meta_helpless_parser = meta_subparsers.add_parser("helpless")
390
391 # Create flags with and without help text
392 meta_helpful_parser.add_argument("--helpful_flag", help="a helpful flag")
393 meta_helpless_parser.add_argument("--helpless_flag")
394
395 @with_argparser(meta_parser)
396 def do_meta(self, args: argparse.Namespace) -> None:
397 pass
398
399
400 @pytest.fixture
401 def ac_app() -> ArgparseCompleterTester:
402 return ArgparseCompleterTester()
403
404
405 @pytest.mark.parametrize("command", ["music", "music create", "music create rock", "music create jazz"])
406 def test_help(ac_app, command) -> None:
407 out1, _err1 = run_cmd(ac_app, f"{command} -h")
408 out2, _err2 = run_cmd(ac_app, f"help {command}")
409 assert out1 == out2
410
411
412 def test_bad_subcommand_help(ac_app) -> None:
413 # These should give the same output because the second one isn't using a
414 # real subcommand, so help will be called on the music command instead.
415 out1, _err1 = run_cmd(ac_app, "help music")
416 out2, _err2 = run_cmd(ac_app, "help music fake")
417 assert out1 == out2
418
419
420 @pytest.mark.parametrize(
421 ("command", "text", "expected"),
422 [
423 ("", "mus", ["music"]),
424 ("music", "cre", ["create"]),
425 ("music", "creab", []),
426 ("music create", "", ["jazz", "rock"]),
427 ("music crea", "jazz", []),
428 ("music create", "foo", []),
429 ("fake create", "", []),
430 ("music fake", "", []),
431 ],
432 )
433 def test_complete_help(ac_app, command, text, expected) -> None:
434 line = f"help {command} {text}"
435 endidx = len(line)
436 begidx = endidx - len(text)
437
438 completions = ac_app.complete(text, line, begidx, endidx)
439 assert completions.to_strings() == Completions.from_values(expected).to_strings()
440
441
442 @pytest.mark.parametrize(
443 ("subcommand", "text", "expected"),
444 [
445 ("create", "", ["jazz", "rock"]),
446 ("create", "ja", ["jazz"]),
447 ("create", "foo", []),
448 ("creab", "ja", []),
449 ],
450 )
451 def test_subcommand_completions(ac_app, subcommand, text, expected) -> None:
452 line = f"music {subcommand} {text}"
453 endidx = len(line)
454 begidx = endidx - len(text)
455
456 completions = ac_app.complete(text, line, begidx, endidx)
457 assert completions.to_strings() == Completions.from_values(expected).to_strings()
458
459
460 @pytest.mark.parametrize(
461 # expected_data is a list of tuples with completion text and display values
462 ("command_and_args", "text", "expected_data"),
463 [
464 # Complete all flags (suppressed will not show)
465 (
466 "flag",
467 "-",
468 [
469 ("-a", "[-a, --append_flag]"),
470 ("-c", "[-c, --count_flag]"),
471 ("-e", "[-e, --extend_flag]"),
472 ("-h", "[-h, --help]"),
473 ("-n", "[-n, --normal_flag]"),
474 ("-o", "[-o, --append_const_flag]"),
475 ("-q", "-q, --required_flag"),
476 ("-r", "[-r, --remainder_flag]"),
477 ],
478 ),
479 (
480 "flag",
481 "--",
482 [
483 ("--append_const_flag", "[--append_const_flag]"),
484 ("--append_flag", "[--append_flag]"),
485 ("--count_flag", "[--count_flag]"),
486 ("--extend_flag", "[--extend_flag]"),
487 ("--help", "[--help]"),
488 ("--normal_flag", "[--normal_flag]"),
489 ("--remainder_flag", "[--remainder_flag]"),
490 ("--required_flag", "--required_flag"),
491 ],
492 ),
493 # Complete individual flag
494 ("flag", "-n", [("-n", "[-n]")]),
495 ("flag", "--n", [("--normal_flag", "[--normal_flag]")]),
496 # No flags should complete until current flag has its args
497 ("flag --append_flag", "-", []),
498 # Complete REMAINDER flag name
499 ("flag", "-r", [("-r", "[-r]")]),
500 ("flag", "--rem", [("--remainder_flag", "[--remainder_flag]")]),
501 # No flags after a REMAINDER should complete
502 ("flag -r value", "-", []),
503 ("flag --remainder_flag value", "--", []),
504 # Suppressed flag should not complete
505 ("flag", "-s", []),
506 ("flag", "--s", []),
507 # A used flag should not show in completions
508 (
509 "flag -n",
510 "--",
511 [
512 ("--append_const_flag", "[--append_const_flag]"),
513 ("--append_flag", "[--append_flag]"),
514 ("--count_flag", "[--count_flag]"),
515 ("--extend_flag", "[--extend_flag]"),
516 ("--help", "[--help]"),
517 ("--remainder_flag", "[--remainder_flag]"),
518 ("--required_flag", "--required_flag"),
519 ],
520 ),
521 # Flags with actions set to append, append_const, extend, and count will always show even if they've been used
522 (
523 "flag --append_flag value --append_const_flag --count_flag --extend_flag value",
524 "--",
525 [
526 ("--append_const_flag", "[--append_const_flag]"),
527 ("--append_flag", "[--append_flag]"),
528 ("--count_flag", "[--count_flag]"),
529 ("--extend_flag", "[--extend_flag]"),
530 ("--help", "[--help]"),
531 ("--normal_flag", "[--normal_flag]"),
532 ("--remainder_flag", "[--remainder_flag]"),
533 ("--required_flag", "--required_flag"),
534 ],
535 ),
536 # Non-default flag prefix character (+)
537 (
538 "plus_flag",
539 "+",
540 [
541 ("+h", "[+h, ++help]"),
542 ("+n", "[+n, ++normal_flag]"),
543 ("+q", "+q, ++required_flag"),
544 ],
545 ),
546 (
547 "plus_flag",
548 "++",
549 [
550 ("++help", "[++help]"),
551 ("++normal_flag", "[++normal_flag]"),
552 ("++required_flag", "++required_flag"),
553 ],
554 ),
555 # Flag completion should not occur after '--' since that tells argparse all remaining arguments are non-flags
556 ("flag --", "--", []),
557 ("flag --help --", "--", []),
558 ("plus_flag --", "++", []),
559 ("plus_flag ++help --", "++", []),
560 # Test remaining flag names complete after all positionals are complete
561 ("pos_and_flag", "", [("a", "a"), ("choice", "choice")]),
562 ("pos_and_flag choice ", "", [("-f", "[-f, --flag]"), ("-h", "[-h, --help]")]),
563 ("pos_and_flag choice -f ", "", [("-h", "[-h, --help]")]),
564 ("pos_and_flag choice -f -h ", "", []),
565 ],
566 )
567 def test_autcomp_flag_completion(ac_app, command_and_args, text, expected_data) -> None:
568 line = f"{command_and_args} {text}"
569 endidx = len(line)
570 begidx = endidx - len(text)
571
572 expected_completions = Completions(items=[CompletionItem(value=v, display=d) for v, d in expected_data])
573 completions = ac_app.complete(text, line, begidx, endidx)
574
575 assert completions.to_strings() == expected_completions.to_strings()
576 assert [item.display for item in completions] == [item.display for item in expected_completions]
577
578
579 @pytest.mark.parametrize(
580 ("flag", "text", "expected"),
581 [
582 ("-l", "", ArgparseCompleterTester.static_choices_list),
583 ("--list", "s", ["static", "stop"]),
584 ("-p", "", ArgparseCompleterTester.choices_from_provider),
585 ("--provider", "pr", ["provider", "probably"]),
586 ("-n", "", ArgparseCompleterTester.num_choices),
587 ("--num", "1", ["1"]),
588 ("--num", "-", [-1, -2, -12]),
589 ("--num", "-1", [-1, -12]),
590 ("--num_completion_items", "", ArgparseCompleterTester.num_completion_items),
591 ],
592 )
593 def test_autocomp_flag_choices_completion(ac_app, flag, text, expected) -> None:
594 line = f"choices {flag} {text}"
595 endidx = len(line)
596 begidx = endidx - len(text)
597
598 completions = ac_app.complete(text, line, begidx, endidx)
599 assert completions.to_strings() == Completions.from_values(expected).to_strings()
600
601
602 @pytest.mark.parametrize(
603 ("pos", "text", "expected"),
604 [
605 (1, "", ArgparseCompleterTester.static_choices_list),
606 (1, "s", ["static", "stop"]),
607 (2, "", ArgparseCompleterTester.choices_from_provider),
608 (2, "pr", ["provider", "probably"]),
609 (3, "", ArgparseCompleterTester.non_negative_num_choices),
610 (3, "2", [2, 22]),
611 (4, "", []),
612 ],
613 )
614 def test_autocomp_positional_choices_completion(ac_app, pos, text, expected) -> None:
615 # Generate line where preceding positionals are already filled
616 line = "choices {} {}".format("foo " * (pos - 1), text)
617 endidx = len(line)
618 begidx = endidx - len(text)
619
620 completions = ac_app.complete(text, line, begidx, endidx)
621 assert completions.to_strings() == Completions.from_values(expected).to_strings()
622
623
624 @pytest.mark.parametrize(
625 ("flag", "text", "expected"),
626 [
627 ("-c", "", ArgparseCompleterTester.completions_for_flag),
628 ("--completer", "f", ["flag", "fairly"]),
629 ],
630 )
631 def test_autocomp_flag_completers(ac_app, flag, text, expected) -> None:
632 line = f"completer {flag} {text}"
633 endidx = len(line)
634 begidx = endidx - len(text)
635
636 completions = ac_app.complete(text, line, begidx, endidx)
637 assert completions.to_strings() == Completions.from_values(expected).to_strings()
638
639
640 @pytest.mark.parametrize(
641 ("pos", "text", "expected"),
642 [
643 (1, "", ArgparseCompleterTester.completions_for_pos_1),
644 (1, "p", ["positional_1", "probably"]),
645 (2, "", ArgparseCompleterTester.completions_for_pos_2),
646 (2, "m", ["missed", "me"]),
647 ],
648 )
649 def test_autocomp_positional_completers(ac_app, pos, text, expected) -> None:
650 # Generate line were preceding positionals are already filled
651 line = "completer {} {}".format("foo " * (pos - 1), text)
652 endidx = len(line)
653 begidx = endidx - len(text)
654
655 completions = ac_app.complete(text, line, begidx, endidx)
656 assert completions.to_strings() == Completions.from_values(expected).to_strings()
657
658
659 def test_autocomp_blank_token(ac_app) -> None:
660 """Force a blank token to make sure ArgparseCompleter consumes them like argparse does"""
661 from cmd2.argparse_completer import (
662 ArgparseCompleter,
663 )
664
665 blank = ""
666
667 # Blank flag arg will be consumed. Therefore we expect to be completing the first positional.
668 text = ""
669 line = f"completer -c {blank} {text}"
670 endidx = len(line)
671 begidx = endidx - len(text)
672
673 completer = ArgparseCompleter(ac_app.completer_parser, ac_app)
674 tokens = ["-c", blank, text]
675 completions = completer.complete(text, line, begidx, endidx, tokens)
676 expected = ArgparseCompleterTester.completions_for_pos_1
677 assert completions.to_strings() == Completions.from_values(expected).to_strings()
678
679 # Blank arg for first positional will be consumed. Therefore we expect to be completing the second positional.
680 text = ""
681 line = f"completer {blank} {text}"
682 endidx = len(line)
683 begidx = endidx - len(text)
684
685 completer = ArgparseCompleter(ac_app.completer_parser, ac_app)
686 tokens = [blank, text]
687 completions = completer.complete(text, line, begidx, endidx, tokens)
688 expected = ArgparseCompleterTester.completions_for_pos_2
689 assert completions.to_strings() == Completions.from_values(expected).to_strings()
690
691
692 @with_ansi_style(ru.AllowStyle.ALWAYS)
693 def test_completion_tables_strings(ac_app) -> None:
694 # Test completion table created from strings
695 text = ""
696 line = f"choices --completion_items {text}"
697 endidx = len(line)
698 begidx = endidx - len(text)
699
700 completions = ac_app.complete(text, line, begidx, endidx)
701 assert len(completions) == len(ac_app.completion_item_choices)
702 assert completions.table is not None
703
704 # Verify the column for the item being completed
705 col_0_cells = list(completions.table.columns[0].cells)
706 assert len(col_0_cells) == 3
707
708 # Since the completed item column is all strings, it is left-aligned
709 assert completions.table.columns[0].justify == "left"
710 assert completions.table.columns[0].header == "COMPLETION_ITEMS"
711
712 # ArgparseCompleter converts all items in this column to Rich Text objects
713 assert col_0_cells[0].plain == "choice_1"
714 assert col_0_cells[1].plain == "choice_2"
715 assert col_0_cells[2].plain == "choice_3"
716
717 # Verify the column containing contextual data about the item being completed
718 col_1_cells = list(completions.table.columns[1].cells)
719 assert len(col_1_cells) == 3
720
721 # Strings with no ANSI style remain strings
722 assert col_1_cells[0] == "Description 1"
723
724 # CompletionItem converts strings with ANSI styles to Rich Text objects
725 assert col_1_cells[1].plain == "String with style"
726
727 # This item was already a Rich Text object
728 assert col_1_cells[2].plain == "Text with style"
729
730
731 @with_ansi_style(ru.AllowStyle.ALWAYS)
732 def test_completion_tables_numbers(ac_app) -> None:
733 # Test completion table created from numbers
734 text = ""
735 line = f"choices --num_completion_items {text}"
736 endidx = len(line)
737 begidx = endidx - len(text)
738
739 completions = ac_app.complete(text, line, begidx, endidx)
740 assert len(completions) == len(ac_app.num_completion_items)
741 assert completions.table is not None
742
743 # Verify the column for the item being completed
744 col_0_cells = list(completions.table.columns[0].cells)
745 assert len(col_0_cells) == 3
746
747 # Since the completed item column is all numbers, it is right-aligned
748 assert completions.table.columns[0].justify == "right"
749
750 # ArgparseCompleter converts all items in this column to Rich Text objects
751 assert col_0_cells[0].plain == "1.5"
752 assert col_0_cells[1].plain == "2"
753 assert col_0_cells[2].plain == "5"
754
755 # Verify the column containing contextual data about the item being completed
756 col_1_cells = list(completions.table.columns[1].cells)
757 assert len(col_1_cells) == 3
758 assert col_1_cells[0] == "One.Five"
759 assert col_1_cells[1] == "Two"
760 assert col_1_cells[2] == "Five"
761
762
763 @pytest.mark.parametrize(
764 ("num_aliases", "show_table"),
765 [
766 # The number of completion results determines if a completion table is displayed.
767 # The count must be greater than 1 and less than ac_app.max_completion_table_items,
768 # which defaults to 50.
769 (1, False),
770 (5, True),
771 (100, False),
772 ],
773 )
774 def test_max_completion_table_items(ac_app, num_aliases, show_table) -> None:
775 # Create aliases
776 for i in range(num_aliases):
777 run_cmd(ac_app, f"alias create fake_alias{i} help")
778
779 assert len(ac_app.aliases) == num_aliases
780
781 text = "fake_alias"
782 line = f"alias list {text}"
783 endidx = len(line)
784 begidx = endidx - len(text)
785
786 completions = ac_app.complete(text, line, begidx, endidx)
787 assert len(completions) == num_aliases
788 assert show_table == (completions.table is not None)
789
790
791 @pytest.mark.parametrize(
792 ("args", "expected"),
793 [
794 # Flag with nargs = 2
795 ("--set_value", ArgparseCompleterTester.set_value_choices),
796 ("--set_value set", ["value", "choices"]),
797 # Both args are filled. At positional arg now.
798 ("--set_value set value", ArgparseCompleterTester.positional_choices),
799 # Using the flag again will reset the choices available
800 ("--set_value set value --set_value", ArgparseCompleterTester.set_value_choices),
801 # Flag with nargs = ONE_OR_MORE
802 ("--one_or_more", ArgparseCompleterTester.one_or_more_choices),
803 ("--one_or_more one", ["or", "more", "choices"]),
804 # Flag with nargs = OPTIONAL
805 ("--optional", ArgparseCompleterTester.optional_choices),
806 # Only one arg allowed for an OPTIONAL. At positional now.
807 ("--optional optional", ArgparseCompleterTester.positional_choices),
808 # Flag with nargs range (1, 2)
809 ("--range", ArgparseCompleterTester.range_choices),
810 ("--range some", ["range", "choices"]),
811 # Already used 2 args so at positional
812 ("--range some range", ArgparseCompleterTester.positional_choices),
813 # Flag with nargs = REMAINDER
814 ("--remainder", ArgparseCompleterTester.remainder_choices),
815 ("--remainder remainder ", ["choices"]),
816 # No more flags can appear after a REMAINDER flag)
817 ("--remainder choices --set_value", ["remainder"]),
818 # Double dash ends the current flag
819 ("--range choice --", ArgparseCompleterTester.positional_choices),
820 # Double dash ends a REMAINDER flag
821 ("--remainder remainder --", ArgparseCompleterTester.positional_choices),
822 # No more flags after a double dash
823 ("-- --one_or_more ", ArgparseCompleterTester.positional_choices),
824 # Consume positional
825 ("", ArgparseCompleterTester.positional_choices),
826 ("positional", ["the", "choices"]),
827 # Intermixed flag and positional
828 ("positional --set_value", ArgparseCompleterTester.set_value_choices),
829 ("positional --set_value set", ["choices", "value"]),
830 # Intermixed flag and positional with flag finishing
831 ("positional --set_value set value", ["the", "choices"]),
832 ("positional --range choice --", ["the", "choices"]),
833 # REMAINDER positional
834 ("the positional", ArgparseCompleterTester.remainder_choices),
835 ("the positional remainder", ["choices"]),
836 ("the positional remainder choices", []),
837 # REMAINDER positional. Flags don't work in REMAINDER
838 ("the positional --set_value", ArgparseCompleterTester.remainder_choices),
839 ("the positional remainder --set_value", ["choices"]),
840 ],
841 )
842 def test_autcomp_nargs(ac_app, args, expected) -> None:
843 text = ""
844 line = f"nargs {args} {text}"
845 endidx = len(line)
846 begidx = endidx - len(text)
847
848 completions = ac_app.complete(text, line, begidx, endidx)
849 assert completions.to_strings() == Completions.from_values(expected).to_strings()
850
851
852 @pytest.mark.parametrize(
853 ("command_and_args", "text", "is_error"),
854 [
855 # Flag is finished before moving on
856 ("hint --flag foo --", "", False),
857 ("hint --flag foo --help", "", False),
858 ("hint --flag foo", "--", False),
859 ("nargs --one_or_more one --", "", False),
860 ("nargs --one_or_more one or --set_value", "", False),
861 ("nargs --one_or_more one or more", "--", False),
862 ("nargs --set_value set value --", "", False),
863 ("nargs --set_value set value --one_or_more", "", False),
864 ("nargs --set_value set value", "--", False),
865 ("nargs --set_val set value", "--", False), # This exercises our abbreviated flag detection
866 ("nargs --range choices --", "", False),
867 ("nargs --range choices range --set_value", "", False),
868 ("nargs --range range", "--", False),
869 # Flag is not finished before moving on
870 ("hint --flag --", "", True),
871 ("hint --flag --help", "", True),
872 ("hint --flag", "--", True),
873 ("nargs --one_or_more --", "", True),
874 ("nargs --one_or_more --set_value", "", True),
875 ("nargs --one_or_more", "--", True),
876 ("nargs --set_value set --", "", True),
877 ("nargs --set_value set --one_or_more", "", True),
878 ("nargs --set_value set", "--", True),
879 ("nargs --set_val set", "--", True), # This exercises our abbreviated flag detection
880 ("nargs --range --", "", True),
881 ("nargs --range --set_value", "", True),
882 ("nargs --range", "--", True),
883 ],
884 )
885 def test_unfinished_flag_error(ac_app, command_and_args, text, is_error) -> None:
886 line = f"{command_and_args} {text}"
887 endidx = len(line)
888 begidx = endidx - len(text)
889
890 completions = ac_app.complete(text, line, begidx, endidx)
891 assert is_error == all(x in completions.error for x in ["Error: argument", "expected"])
892
893
894 def test_completion_table_metavar(ac_app) -> None:
895 # Test when metavar is None
896 text = ""
897 line = f"choices --no_metavar {text}"
898 endidx = len(line)
899 begidx = endidx - len(text)
900
901 completions = ac_app.complete(text, line, begidx, endidx)
902 assert completions.table is not None
903 assert completions.table.columns[0].header == "NO_METAVAR"
904
905 # Test when metavar is a string
906 text = ""
907 line = f"choices --str_metavar {text}"
908 endidx = len(line)
909 begidx = endidx - len(text)
910
911 completions = ac_app.complete(text, line, begidx, endidx)
912 assert completions.table is not None
913 assert completions.table.columns[0].header == ac_app.STR_METAVAR
914
915 # Test when metavar is a tuple
916 text = ""
917 line = f"choices --tuple_metavar {text}"
918 endidx = len(line)
919 begidx = endidx - len(text)
920
921 # We are completing the first argument of this flag. The first element in the tuple should be the column header.
922 completions = ac_app.complete(text, line, begidx, endidx)
923 assert completions.table is not None
924 assert completions.table.columns[0].header == ac_app.TUPLE_METAVAR[0].upper()
925
926 text = ""
927 line = f"choices --tuple_metavar token_1 {text}"
928 endidx = len(line)
929 begidx = endidx - len(text)
930
931 # We are completing the second argument of this flag. The second element in the tuple should be the column header.
932 completions = ac_app.complete(text, line, begidx, endidx)
933 assert completions.table is not None
934 assert completions.table.columns[0].header == ac_app.TUPLE_METAVAR[1].upper()
935
936 text = ""
937 line = f"choices --tuple_metavar token_1 token_2 {text}"
938 endidx = len(line)
939 begidx = endidx - len(text)
940
941 # We are completing the third argument of this flag. It should still be the second tuple element
942 # in the column header since the tuple only has two strings in it.
943 completions = ac_app.complete(text, line, begidx, endidx)
944 assert completions.table is not None
945 assert completions.table.columns[0].header == ac_app.TUPLE_METAVAR[1].upper()
946
947
948 @pytest.mark.parametrize(
949 ("command_and_args", "text", "has_hint"),
950 [
951 # Normal cases
952 ("hint", "", True),
953 ("hint --flag", "", True),
954 ("hint --suppressed_help", "", False),
955 ("hint --suppressed_hint", "", False),
956 # Hint because flag does not have enough values to be considered finished
957 ("nargs --one_or_more", "-", True),
958 # This flag has reached its minimum value count and therefore a new flag could start.
959 # However the flag can still consume values and the text is not a single prefix character.
960 # Therefore a hint will be shown.
961 ("nargs --one_or_more choices", "bad_completion", True),
962 # Like the previous case, but this time text is a single prefix character which will cause flag
963 # name completion to occur instead of a hint for the current flag.
964 ("nargs --one_or_more choices", "-", False),
965 # Hint because this is a REMAINDER flag and therefore no more flag name completions occur.
966 ("nargs --remainder", "-", True),
967 # No hint for the positional because text is a single prefix character which results in flag name completion
968 ("hint", "-", False),
969 # Hint because this is a REMAINDER positional and therefore no more flag name completions occur.
970 ("nargs the choices", "-", True),
971 ("nargs the choices remainder", "-", True),
972 ],
973 )
974 def test_autocomp_no_results_hint(ac_app, command_and_args, text, has_hint) -> None:
975 """Test whether _NoResultsErrors include hint text."""
976 line = f"{command_and_args} {text}"
977 endidx = len(line)
978 begidx = endidx - len(text)
979
980 completions = ac_app.complete(text, line, begidx, endidx)
981 if has_hint:
982 assert "Hint:\n" in completions.error
983 else:
984 assert not completions.error
985
986
987 def test_autocomp_hint_no_help_text(ac_app) -> None:
988 """Tests that a hint for an arg with no help text only includes the arg's name."""
989 text = ""
990 line = f"hint foo {text}"
991 endidx = len(line)
992 begidx = endidx - len(text)
993
994 completions = ac_app.complete(text, line, begidx, endidx)
995 assert completions.error.strip() == "Hint:\n no_help_pos"
996
997
998 @pytest.mark.parametrize(
999 ("args", "text"),
1000 [
1001 # Exercise a flag arg and choices function that raises a CompletionError
1002 ("--choice ", "choice"),
1003 # Exercise a positional arg and completer that raises a CompletionError
1004 ("", "completer"),
1005 ],
1006 )
1007 def test_completion_error(ac_app, args, text) -> None:
1008 line = f"raise_completion_error {args} {text}"
1009 endidx = len(line)
1010 begidx = endidx - len(text)
1011
1012 completions = ac_app.complete(text, line, begidx, endidx)
1013 assert f"{text} broke something" in completions.error
1014
1015
1016 @pytest.mark.parametrize(
1017 ("command_and_args", "expected"),
1018 [
1019 # Exercise a choices function that receives arg_tokens dictionary
1020 ("arg_tokens choice subcmd", ["choice", "subcmd"]),
1021 # Exercise a completer that receives arg_tokens dictionary
1022 ("arg_tokens completer subcmd fake", ["completer", "subcmd"]),
1023 # Exercise overriding parent_arg from the subcommand
1024 ("arg_tokens completer subcmd --parent_arg override fake", ["override", "subcmd"]),
1025 ],
1026 )
1027 def test_arg_tokens(ac_app, command_and_args, expected) -> None:
1028 text = ""
1029 line = f"{command_and_args} {text}"
1030 endidx = len(line)
1031 begidx = endidx - len(text)
1032
1033 completions = ac_app.complete(text, line, begidx, endidx)
1034 assert completions.to_strings() == Completions.from_values(expected).to_strings()
1035
1036
1037 @pytest.mark.parametrize(
1038 ("command_and_args", "text", "output_contains", "first_match"),
1039 [
1040 # Group isn't done. The optional positional's hint will show and flags will not complete.
1041 ("mutex", "", "the optional positional", None),
1042 # Group isn't done. Flag name will still complete.
1043 ("mutex", "--fl", "", "--flag"),
1044 # Group isn't done. Flag hint will show.
1045 ("mutex --flag", "", "the flag arg", None),
1046 # Group finished by optional positional. No flag name will complete.
1047 ("mutex pos_val", "--fl", "", None),
1048 # Group finished by optional positional. Error will display trying to complete the flag's value.
1049 ("mutex pos_val --flag", "", "f/--flag: not allowed with argument optional_pos", None),
1050 # Group finished by --flag. Optional positional will be skipped and last_arg will show its hint.
1051 ("mutex --flag flag_val", "", "the last arg", None),
1052 # Group finished by --flag. Other flag name won't complete.
1053 ("mutex --flag flag_val", "--oth", "", None),
1054 # Group finished by --flag. Error will display trying to complete other flag's value.
1055 ("mutex --flag flag_val --other", "", "-o/--other_flag: not allowed with argument -f/--flag", None),
1056 # Group finished by --flag. That same flag can be used again so it's hint will show.
1057 ("mutex --flag flag_val --flag", "", "the flag arg", None),
1058 ],
1059 )
1060 def test_complete_mutex_group(ac_app, command_and_args, text, output_contains, first_match) -> None:
1061 line = f"{command_and_args} {text}"
1062 endidx = len(line)
1063 begidx = endidx - len(text)
1064
1065 completions = ac_app.complete(text, line, begidx, endidx)
1066 if first_match is None:
1067 assert not completions
1068 else:
1069 assert first_match == completions[0].text
1070
1071 assert output_contains in completions.error
1072
1073
1074 def test_single_prefix_char() -> None:
1075 from cmd2.argparse_completer import (
1076 _single_prefix_char,
1077 )
1078
1079 parser = Cmd2ArgumentParser(prefix_chars="-+")
1080
1081 # Invalid
1082 assert not _single_prefix_char("", parser)
1083 assert not _single_prefix_char("--", parser)
1084 assert not _single_prefix_char("-+", parser)
1085 assert not _single_prefix_char("++has space", parser)
1086 assert not _single_prefix_char("foo", parser)
1087
1088 # Valid
1089 assert _single_prefix_char("-", parser)
1090 assert _single_prefix_char("+", parser)
1091
1092
1093 def test_looks_like_flag() -> None:
1094 from cmd2.argparse_completer import (
1095 _looks_like_flag,
1096 )
1097
1098 parser = Cmd2ArgumentParser()
1099
1100 # Does not start like a flag
1101 assert not _looks_like_flag("", parser)
1102 assert not _looks_like_flag("non-flag", parser)
1103 assert not _looks_like_flag("-", parser)
1104 assert not _looks_like_flag("--has space", parser)
1105 assert not _looks_like_flag("-2", parser)
1106
1107 # Does start like a flag
1108 assert _looks_like_flag("--", parser)
1109 assert _looks_like_flag("-flag", parser)
1110 assert _looks_like_flag("--flag", parser)
1111
1112
1113 def test_complete_command_no_tokens(ac_app) -> None:
1114 from cmd2.argparse_completer import (
1115 ArgparseCompleter,
1116 )
1117
1118 parser = Cmd2ArgumentParser()
1119 ac = ArgparseCompleter(parser, ac_app)
1120
1121 completions = ac.complete(text="", line="", begidx=0, endidx=0, tokens=[])
1122 assert not completions
1123
1124
1125 def test_complete_command_help_no_tokens(ac_app) -> None:
1126 from cmd2.argparse_completer import (
1127 ArgparseCompleter,
1128 )
1129
1130 parser = Cmd2ArgumentParser()
1131 ac = ArgparseCompleter(parser, ac_app)
1132
1133 completions = ac.complete_subcommand_help(text="", line="", begidx=0, endidx=0, tokens=[])
1134 assert not completions
1135
1136
1137 @pytest.mark.parametrize(
1138 ("flag", "expected"),
1139 [
1140 ("--provider", standalone_choices),
1141 ("--completer", standalone_completions),
1142 ],
1143 )
1144 def test_complete_standalone(ac_app, flag, expected) -> None:
1145 text = ""
1146 line = f"standalone {flag} {text}"
1147 endidx = len(line)
1148 begidx = endidx - len(text)
1149
1150 completions = ac_app.complete(text, line, begidx, endidx)
1151 assert completions.to_strings() == Completions.from_values(expected).to_strings()
1152
1153
1154 @pytest.mark.parametrize(
1155 ("subcommand", "flag", "display_meta"),
1156 [
1157 ("helpful", "", "my helpful text"),
1158 ("helpful", "--helpful_flag", "a helpful flag"),
1159 ("helpless", "", ""),
1160 ("helpless", "--helpless_flag", ""),
1161 ],
1162 )
1163 def test_display_meta(ac_app, subcommand, flag, display_meta) -> None:
1164 """Test that subcommands and flags can have display_meta data."""
1165 if flag:
1166 text = flag
1167 line = f"meta {subcommand} {text}"
1168 else:
1169 text = subcommand
1170 line = f"meta {text}"
1171
1172 endidx = len(line)
1173 begidx = endidx - len(text)
1174
1175 completions = ac_app.complete(text, line, begidx, endidx)
1176 assert completions[0].display_meta == display_meta
1177
1178
1179 def test_validate_table_data_no_table() -> None:
1180 action = argparse.Action(option_strings=["-f"], dest="foo")
1181 action.set_table_columns(None)
1182 arg_state = argparse_completer._ArgumentState(action)
1183 completions = Completions(
1184 [
1185 CompletionItem("item1"),
1186 CompletionItem("item2"),
1187 ]
1188 )
1189
1190 # This should not raise an exception
1191 argparse_completer.ArgparseCompleter._validate_table_data(arg_state, completions)
1192
1193
1194 def test_validate_table_data_missing_columns() -> None:
1195 action = argparse.Action(option_strings=["-f"], dest="foo")
1196 action.set_table_columns(None)
1197 arg_state = argparse_completer._ArgumentState(action)
1198
1199 completions = Completions(
1200 [
1201 CompletionItem("item1", table_data=["data1"]),
1202 CompletionItem("item2", table_data=["data2"]),
1203 ]
1204 )
1205
1206 with pytest.raises(
1207 ValueError,
1208 match="Argument 'foo' has CompletionItems with table_data, but no table_columns were defined",
1209 ):
1210 argparse_completer.ArgparseCompleter._validate_table_data(arg_state, completions)
1211
1212
1213 def test_validate_table_data_missing_item_data() -> None:
1214 action = argparse.Action(option_strings=["-f"], dest="foo")
1215 action.set_table_columns(["Col1"])
1216 arg_state = argparse_completer._ArgumentState(action)
1217
1218 completions = Completions(
1219 [
1220 CompletionItem("item1", table_data=["data1"]),
1221 CompletionItem("item2"), # Missing table_data
1222 ]
1223 )
1224
1225 with pytest.raises(
1226 ValueError,
1227 match="Argument 'foo' has table_columns defined, but the CompletionItem for 'item2' is missing table_data",
1228 ):
1229 argparse_completer.ArgparseCompleter._validate_table_data(arg_state, completions)
1230
1231
1232 def test_validate_table_data_length_mismatch() -> None:
1233 action = argparse.Action(option_strings=["-f"], dest="foo")
1234 action.set_table_columns(["Col1", "Col2"])
1235 arg_state = argparse_completer._ArgumentState(action)
1236
1237 completions = Completions(
1238 [
1239 CompletionItem("item1", table_data=["data1a", "data1b"]),
1240 CompletionItem("item2", table_data=["only_one"]),
1241 ]
1242 )
1243
1244 with pytest.raises(
1245 ValueError,
1246 match=r"Argument 'foo': table_data length \(1\) does not match table_columns length \(2\) for item 'item2'.",
1247 ):
1248 argparse_completer.ArgparseCompleter._validate_table_data(arg_state, completions)
1249
1250
1251 def test_validate_table_data_valid() -> None:
1252 action = argparse.Action(option_strings=["-f"], dest="foo")
1253 action.get_table_columns = lambda: ["Col1", "Col2"]
1254 arg_state = argparse_completer._ArgumentState(action)
1255
1256 completions = Completions(
1257 [
1258 CompletionItem("item1", table_data=["data1a", "data1b"]),
1259 CompletionItem("item2", table_data=["data2a", "data2b"]),
1260 ]
1261 )
1262
1263 # This should not raise an exception
1264 argparse_completer.ArgparseCompleter._validate_table_data(arg_state, completions)
1265
1266
1267 # Custom ArgparseCompleter-based class
1268 class CustomCompleter(argparse_completer.ArgparseCompleter):
1269 def _complete_flags(self, text: str, line: str, begidx: int, endidx: int, used_flags: set[str]) -> Completions:
1270 """Override so flags with 'complete_when_ready' set to True will complete only when app is ready"""
1271 # Find flags which should not be completed and place them in used_flags
1272 for flag in self._flags:
1273 action = self._flag_to_action[flag]
1274 app: CustomCompleterApp = cast(CustomCompleterApp, self._cmd_app)
1275 if action.get_complete_when_ready() and not app.is_ready:
1276 used_flags.append(flag)
1277
1278 return super()._complete_flags(text, line, begidx, endidx, used_flags)
1279
1280
1281 # Add a custom argparse action attribute
1282 argparse_utils.register_argparse_argument_parameter("complete_when_ready")
1283
1284
1285 # App used to test custom ArgparseCompleter types and custom argparse attributes
1286 class CustomCompleterApp(cmd2.Cmd):
1287 def __init__(self) -> None:
1288 super().__init__()
1289 self.is_ready = True
1290
1291 @staticmethod
1292 def _build_default_completer_parser() -> Cmd2ArgumentParser:
1293 """Build parser to test setting the app-wide default ArgparseCompleter type.
1294
1295 Use a factory so set_default_argparse_completer() can be called before parser initialization.
1296 """
1297 default_completer_parser = Cmd2ArgumentParser(description="Testing app-wide argparse completer")
1298 default_completer_parser.add_argument("--myflag", complete_when_ready=True)
1299 return default_completer_parser
1300
1301 @with_argparser(_build_default_completer_parser)
1302 def do_default_completer(self, args: argparse.Namespace) -> None:
1303 """Test command"""
1304
1305 # Parser that's used to test setting a custom completer at the parser level
1306 custom_completer_parser = Cmd2ArgumentParser(
1307 description="Testing parser-specific argparse completer", completer_class=CustomCompleter
1308 )
1309 custom_completer_parser.add_argument("--myflag", complete_when_ready=True)
1310
1311 @with_argparser(custom_completer_parser)
1312 def do_custom_completer(self, args: argparse.Namespace) -> None:
1313 """Test command"""
1314
1315 # Test as_subcommand_to decorator with custom completer
1316 top_parser = Cmd2ArgumentParser(description="Top Command")
1317 top_parser.add_subparsers(dest="subcommand", metavar="SUBCOMMAND", required=True)
1318
1319 @with_argparser(top_parser)
1320 def do_top(self, args: argparse.Namespace) -> None:
1321 """Top level command"""
1322 # Call handler for whatever subcommand was selected
1323 args.cmd2_subcommand_func(args)
1324
1325 # Parser for a subcommand with no custom completer type
1326 no_custom_completer_parser = Cmd2ArgumentParser(description="No custom completer")
1327 no_custom_completer_parser.add_argument("--myflag", complete_when_ready=True)
1328
1329 @cmd2.as_subcommand_to("top", "no_custom", no_custom_completer_parser, help="no custom completer")
1330 def _subcmd_no_custom(self, args: argparse.Namespace) -> None:
1331 pass
1332
1333 # Parser for a subcommand with a custom completer type
1334 custom_completer_parser2 = Cmd2ArgumentParser(description="Custom completer", completer_class=CustomCompleter)
1335 custom_completer_parser2.add_argument("--myflag", complete_when_ready=True)
1336
1337 @cmd2.as_subcommand_to("top", "custom", custom_completer_parser2, help="custom completer")
1338 def _subcmd_custom(self, args: argparse.Namespace) -> None:
1339 pass
1340
1341
1342 @pytest.fixture
1343 def custom_completer_app():
1344 return CustomCompleterApp()
1345
1346
1347 def test_default_custom_completer(custom_completer_app: CustomCompleterApp) -> None:
1348 """Test altering the app-wide default ArgparseCompleter type"""
1349 try:
1350 argparse_completer.set_default_argparse_completer(CustomCompleter)
1351
1352 text = "--m"
1353 line = f"default_completer {text}"
1354 endidx = len(line)
1355 begidx = endidx - len(text)
1356
1357 # The flag should complete because app is ready
1358 custom_completer_app.is_ready = True
1359 completions = custom_completer_app.complete(text, line, begidx, endidx)
1360 assert completions.items[0].text == "--myflag"
1361
1362 # The flag should not complete because app is not ready
1363 custom_completer_app.is_ready = False
1364 completions = custom_completer_app.complete(text, line, begidx, endidx)
1365 assert not completions
1366
1367 finally:
1368 # Restore the default completer
1369 argparse_completer.set_default_argparse_completer(argparse_completer.ArgparseCompleter)
1370
1371
1372 def test_custom_completer_type(custom_completer_app: CustomCompleterApp) -> None:
1373 """Test parser with a specific custom ArgparseCompleter type"""
1374 text = "--m"
1375 line = f"custom_completer {text}"
1376 endidx = len(line)
1377 begidx = endidx - len(text)
1378
1379 # The flag should complete because app is ready
1380 custom_completer_app.is_ready = True
1381 completions = custom_completer_app.complete(text, line, begidx, endidx)
1382 assert completions.items[0].text == "--myflag"
1383
1384 # The flag should not complete because app is not ready
1385 custom_completer_app.is_ready = False
1386 completions = custom_completer_app.complete(text, line, begidx, endidx)
1387 assert not completions
1388
1389
1390 def test_decorated_subcmd_custom_completer(custom_completer_app: CustomCompleterApp) -> None:
1391 """Tests custom completer type on a subcommand created with @cmd2.as_subcommand_to"""
1392 # First test the subcommand without the custom completer
1393 text = "--m"
1394 line = f"top no_custom {text}"
1395 endidx = len(line)
1396 begidx = endidx - len(text)
1397
1398 # The flag should complete regardless of ready state since this subcommand isn't using the custom completer
1399 custom_completer_app.is_ready = True
1400 completions = custom_completer_app.complete(text, line, begidx, endidx)
1401 assert completions.items[0].text == "--myflag"
1402
1403 custom_completer_app.is_ready = False
1404 completions = custom_completer_app.complete(text, line, begidx, endidx)
1405 assert completions.items[0].text == "--myflag"
1406
1407 # Now test the subcommand with the custom completer
1408 text = "--m"
1409 line = f"top custom {text}"
1410 endidx = len(line)
1411 begidx = endidx - len(text)
1412
1413 # The flag should complete because app is ready
1414 custom_completer_app.is_ready = True
1415 completions = custom_completer_app.complete(text, line, begidx, endidx)
1416 assert completions.items[0].text == "--myflag"
1417
1418 # The flag should not complete because app is not ready
1419 custom_completer_app.is_ready = False
1420 completions = custom_completer_app.complete(text, line, begidx, endidx)
1421 assert not completions
1422
1423
1424 def test_add_parser_custom_completer() -> None:
1425 """Tests setting a custom completer type on a subcommand using add_parser()"""
1426 parser = Cmd2ArgumentParser()
1427 subparsers = parser.add_subparsers()
1428
1429 no_custom_completer_parser: Cmd2ArgumentParser = subparsers.add_parser(name="no_custom_completer")
1430 assert no_custom_completer_parser.completer_class is argparse_completer.DEFAULT_ARGPARSE_COMPLETER
1431
1432 custom_completer_parser: Cmd2ArgumentParser = subparsers.add_parser(
1433 name="custom_completer", completer_class=CustomCompleter
1434 )
1435 assert custom_completer_parser.completer_class is CustomCompleter
1436
1437
1438 def test_completer_preserves_custom_order() -> None:
1439 """Test that completer returning Completions with is_sorted=True preserves custom item ordering."""
1440 custom_order = ("zebra", "apple", "banana")
1441
1442 class CustomApp(cmd2.Cmd):
1443 def custom_completer(self, text: str, line: str, begidx: int, endidx: int) -> Completions:
1444 return Completions.from_values(custom_order, is_sorted=True)
1445
1446 parser = Cmd2ArgumentParser()
1447 parser.add_argument("--custom", completer=custom_completer)
1448
1449 @with_argparser(parser)
1450 def do_test(self, args: argparse.Namespace) -> None:
1451 pass
1452
1453 app = CustomApp()
1454 text = ""
1455 line = f"test --custom {text}"
1456 endidx = len(line)
1457 begidx = endidx - len(text)
1458
1459 completions = app.complete(text, line, begidx, endidx)
1460
1461 assert completions.to_strings() == custom_order
1462
1463
1464 def test_choices_provider_preserves_custom_order() -> None:
1465 """Test that choices_provider returning Choices with is_sorted=True preserves custom item ordering."""
1466 custom_order = ("zebra", "apple", "banana")
1467
1468 class CustomApp(cmd2.Cmd):
1469 def custom_provider(self) -> Choices:
1470 return Choices.from_values(custom_order, is_sorted=True)
1471
1472 parser = Cmd2ArgumentParser()
1473 parser.add_argument("--custom", choices_provider=custom_provider)
1474
1475 @with_argparser(parser)
1476 def do_test(self, args: argparse.Namespace) -> None:
1477 pass
1478
1479 app = CustomApp()
1480 text = ""
1481 line = f"test --custom {text}"
1482 endidx = len(line)
1483 begidx = endidx - len(text)
1484
1485 completions = app.complete(text, line, begidx, endidx)
1486
1487 assert completions.to_strings() == custom_order