Debian Codegraph @

tests/test_shell_completion.py

raw
1 import textwrap
2 import warnings
3 from collections.abc import Mapping
4
5 import pytest
6
7 import click.shell_completion
8 from click.core import Argument
9 from click.core import Command
10 from click.core import Group
11 from click.core import Option
12 from click.shell_completion import add_completion_class
13 from click.shell_completion import CompletionItem
14 from click.shell_completion import ShellComplete
15 from click.types import Choice
16 from click.types import File
17 from click.types import Path
18
19
20 def _get_completions(cli, args, incomplete):
21 comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")
22 return comp.get_completions(args, incomplete)
23
24
25 def _get_words(cli, args, incomplete):
26 return [c.value for c in _get_completions(cli, args, incomplete)]
27
28
29 def test_command():
30 cli = Command("cli", params=[Option(["-t", "--test"])])
31 assert _get_words(cli, [], "") == []
32 assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]
33 assert _get_words(cli, [], "--") == ["--test", "--help"]
34 assert _get_words(cli, [], "--t") == ["--test"]
35 # -t has been seen, so --test isn't suggested
36 assert _get_words(cli, ["-t", "a"], "-") == ["--help"]
37
38
39 def test_group():
40 cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])
41 assert _get_words(cli, [], "") == ["x", "y"]
42 assert _get_words(cli, [], "-") == ["-a", "--help"]
43
44
45 @pytest.mark.parametrize(
46 ("args", "word", "expect"),
47 [
48 ([], "", ["get"]),
49 (["get"], "", ["full"]),
50 (["get", "full"], "", ["data"]),
51 (["get", "full"], "-", ["--verbose", "--help"]),
52 (["get", "full", "data"], "", []),
53 (["get", "full", "data"], "-", ["-a", "--help"]),
54 ],
55 )
56 def test_nested_group(args: list[str], word: str, expect: list[str]) -> None:
57 cli = Group(
58 "cli",
59 commands=[
60 Group(
61 "get",
62 commands=[
63 Group(
64 "full",
65 params=[Option(["--verbose"])],
66 commands=[Command("data", params=[Option(["-a"])])],
67 )
68 ],
69 )
70 ],
71 )
72 assert _get_words(cli, args, word) == expect
73
74
75 def test_group_command_same_option():
76 cli = Group(
77 "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]
78 )
79 assert _get_words(cli, [], "-") == ["-a", "--help"]
80 assert _get_words(cli, ["-a", "a"], "-") == ["--help"]
81 assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]
82 assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]
83
84
85 def test_chained():
86 cli = Group(
87 "cli",
88 chain=True,
89 commands=[
90 Command("set", params=[Option(["-y"])]),
91 Command("start"),
92 Group("get", commands=[Command("full")]),
93 ],
94 )
95 assert _get_words(cli, [], "") == ["get", "set", "start"]
96 assert _get_words(cli, [], "s") == ["set", "start"]
97 assert _get_words(cli, ["set", "start"], "") == ["get"]
98 # subcommands and parent subcommands
99 assert _get_words(cli, ["get"], "") == ["full", "set", "start"]
100 assert _get_words(cli, ["get", "full"], "") == ["set", "start"]
101 assert _get_words(cli, ["get"], "s") == ["set", "start"]
102
103
104 def test_help_option():
105 cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])
106 assert _get_words(cli, ["with"], "--") == ["--help"]
107 assert _get_words(cli, ["no"], "--") == []
108
109
110 def test_argument_order():
111 cli = Command(
112 "cli",
113 params=[
114 Argument(["plain"]),
115 Argument(["c1"], type=Choice(["a1", "a2", "b"])),
116 Argument(["c2"], type=Choice(["c1", "c2", "d"])),
117 ],
118 )
119 # first argument has no completions
120 assert _get_words(cli, [], "") == []
121 assert _get_words(cli, [], "a") == []
122 # first argument filled, now completion can happen
123 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]
124 assert _get_words(cli, ["x", "b"], "d") == ["d"]
125
126
127 def test_argument_default():
128 cli = Command(
129 "cli",
130 add_help_option=False,
131 params=[
132 Argument(["a"], type=Choice(["a"]), default="a"),
133 Argument(["b"], type=Choice(["b"]), default="b"),
134 ],
135 )
136 assert _get_words(cli, [], "") == ["a"]
137 assert _get_words(cli, ["a"], "b") == ["b"]
138 # ignore type validation
139 assert _get_words(cli, ["x"], "b") == ["b"]
140
141
142 def test_type_choice():
143 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])
144 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]
145 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]
146 assert _get_words(cli, ["-c"], "a2") == ["a2"]
147
148
149 def test_choice_special_characters():
150 cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])
151 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]
152 assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]
153 assert _get_words(cli, ["-c"], "!2") == ["!2"]
154
155
156 def test_choice_conflicting_prefix():
157 cli = Command(
158 "cli",
159 params=[
160 Option(["-c"], type=Choice(["!1", "!2", "+3"])),
161 Option(["+p"], is_flag=True),
162 ],
163 )
164 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]
165 assert _get_words(cli, ["-c"], "+") == ["+p"]
166
167
168 def test_option_count():
169 cli = Command("cli", params=[Option(["-c"], count=True)])
170 assert _get_words(cli, ["-c"], "") == []
171 assert _get_words(cli, ["-c"], "-") == ["--help"]
172
173
174 def test_option_optional():
175 cli = Command(
176 "cli",
177 add_help_option=False,
178 params=[
179 Option(["--name"], is_flag=False, flag_value="value"),
180 Option(["--flag"], is_flag=True),
181 ],
182 )
183 assert _get_words(cli, ["--name"], "") == []
184 assert _get_words(cli, ["--name"], "-") == ["--flag"]
185 assert _get_words(cli, ["--name", "--flag"], "-") == []
186
187
188 @pytest.mark.parametrize(
189 ("type", "expect"),
190 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],
191 )
192 def test_path_types(type, expect):
193 cli = Command("cli", params=[Option(["-f"], type=type)])
194 out = _get_completions(cli, ["-f"], "ab")
195 assert len(out) == 1
196 c = out[0]
197 assert c.value == "ab"
198 assert c.type == expect
199
200
201 def test_absolute_path():
202 cli = Command("cli", params=[Option(["-f"], type=Path())])
203 out = _get_completions(cli, ["-f"], "/ab")
204 assert len(out) == 1
205 c = out[0]
206 assert c.value == "/ab"
207
208
209 def test_option_flag():
210 cli = Command(
211 "cli",
212 add_help_option=False,
213 params=[
214 Option(["--on/--off"]),
215 Argument(["a"], type=Choice(["a1", "a2", "b"])),
216 ],
217 )
218 assert _get_words(cli, [], "--") == ["--on", "--off"]
219 # flag option doesn't take value, use choice argument
220 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]
221
222
223 def test_flag_option_with_nargs_option():
224 cli = Command(
225 "cli",
226 add_help_option=False,
227 params=[
228 Argument(["a"], type=Choice(["a1", "a2", "b"])),
229 Option(["--flag"], is_flag=True),
230 Option(["-c"], type=Choice(["p", "q"]), nargs=2),
231 ],
232 )
233 assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]
234
235
236 def test_option_custom():
237 def custom(ctx, param, incomplete):
238 return [incomplete.upper()]
239
240 cli = Command(
241 "cli",
242 params=[
243 Argument(["x"]),
244 Argument(["y"]),
245 Argument(["z"], shell_complete=custom),
246 ],
247 )
248 assert _get_words(cli, ["a", "b"], "") == [""]
249 assert _get_words(cli, ["a", "b"], "c") == ["C"]
250
251
252 def test_option_multiple():
253 cli = Command(
254 "type",
255 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],
256 )
257 assert _get_words(cli, ["-m"], "") == ["a", "b"]
258 assert "-m" in _get_words(cli, ["-m", "a"], "-")
259 assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]
260 # used single options aren't suggested again
261 assert "-c" not in _get_words(cli, ["-c", "f"], "-")
262
263
264 def test_option_nargs():
265 cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])
266 assert _get_words(cli, ["-c"], "") == ["a", "b"]
267 assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]
268 assert _get_words(cli, ["-c", "a", "b"], "") == []
269
270
271 def test_argument_nargs():
272 cli = Command(
273 "cli",
274 params=[
275 Argument(["x"], type=Choice(["a", "b"]), nargs=2),
276 Argument(["y"], type=Choice(["c", "d"]), nargs=-1),
277 Option(["-z"]),
278 ],
279 )
280 assert _get_words(cli, [], "") == ["a", "b"]
281 assert _get_words(cli, ["a"], "") == ["a", "b"]
282 assert _get_words(cli, ["a", "b"], "") == ["c", "d"]
283 assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]
284 assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]
285 assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]
286 assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]
287
288
289 def test_double_dash():
290 cli = Command(
291 "cli",
292 add_help_option=False,
293 params=[
294 Option(["--opt"]),
295 Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),
296 ],
297 )
298 assert _get_words(cli, [], "-") == ["--opt"]
299 assert _get_words(cli, ["value"], "-") == ["--opt"]
300 assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]
301 assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]
302
303
304 def test_hidden():
305 cli = Group(
306 "cli",
307 commands=[
308 Command(
309 "hidden",
310 add_help_option=False,
311 hidden=True,
312 params=[
313 Option(["-a"]),
314 Option(["-b"], type=Choice(["a", "b"]), hidden=True),
315 ],
316 )
317 ],
318 )
319 assert "hidden" not in _get_words(cli, [], "")
320 assert "hidden" not in _get_words(cli, [], "hidden")
321 assert _get_words(cli, ["hidden"], "-") == ["-a"]
322 assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]
323
324
325 def test_add_different_name():
326 cli = Group("cli", commands={"renamed": Command("original")})
327 words = _get_words(cli, [], "")
328 assert "renamed" in words
329 assert "original" not in words
330
331
332 def test_completion_item_data():
333 c = CompletionItem("test", a=1)
334 assert c.a == 1
335 assert c.b is None
336
337
338 @pytest.fixture()
339 def _patch_for_completion(monkeypatch):
340 monkeypatch.setattr(
341 "click.shell_completion.BashComplete._check_version", lambda self: True
342 )
343
344
345 @pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])
346 @pytest.mark.usefixtures("_patch_for_completion")
347 def test_full_source(runner, shell):
348 cli = Group("cli", commands=[Command("a"), Command("b")])
349 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})
350 assert f"_CLI_COMPLETE={shell}_complete" in result.output
351
352
353 @pytest.mark.parametrize(
354 ("shell", "env", "expect"),
355 [
356 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),
357 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),
358 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),
359 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),
360 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),
361 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),
362 ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),
363 ],
364 )
365 @pytest.mark.usefixtures("_patch_for_completion")
366 def test_full_complete(runner, shell, env, expect):
367 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])
368 env["_CLI_COMPLETE"] = f"{shell}_complete"
369 result = runner.invoke(cli, env=env)
370 assert result.output == expect
371
372
373 @pytest.mark.parametrize(
374 ("env", "expect"),
375 [
376 (
377 {"COMP_WORDS": "", "COMP_CWORD": "0"},
378 textwrap.dedent(
379 """\
380 plain
381 a
382 _
383 plain
384 b
385 bee
386 plain
387 c\\:d
388 cee:dee
389 plain
390 c:e
391 _
392 """
393 ),
394 ),
395 (
396 {"COMP_WORDS": "a c", "COMP_CWORD": "1"},
397 textwrap.dedent(
398 """\
399 plain
400 c\\:d
401 cee:dee
402 plain
403 c:e
404 _
405 """
406 ),
407 ),
408 (
409 {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},
410 textwrap.dedent(
411 """\
412 plain
413 c\\:d
414 cee:dee
415 plain
416 c:e
417 _
418 """
419 ),
420 ),
421 ],
422 )
423 @pytest.mark.usefixtures("_patch_for_completion")
424 def test_zsh_full_complete_with_colons(
425 runner, env: Mapping[str, str], expect: str
426 ) -> None:
427 cli = Group(
428 "cli",
429 commands=[
430 Command("a"),
431 Command("b", help="bee"),
432 Command("c:d", help="cee:dee"),
433 Command("c:e"),
434 ],
435 )
436 result = runner.invoke(
437 cli,
438 env={
439 **env,
440 "_CLI_COMPLETE": "zsh_complete",
441 },
442 )
443 assert result.output == expect
444
445
446 @pytest.mark.usefixtures("_patch_for_completion")
447 def test_context_settings(runner):
448 def complete(ctx, param, incomplete):
449 return ctx.obj["choices"]
450
451 cli = Command("cli", params=[Argument("x", shell_complete=complete)])
452 result = runner.invoke(
453 cli,
454 obj={"choices": ["a", "b"]},
455 env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},
456 )
457 assert result.output == "plain,a\nplain,b\n"
458
459
460 @pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])
461 def test_choice_case_sensitive(value, expect):
462 cli = Command(
463 "cli",
464 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],
465 )
466 completions = _get_words(cli, ["-a"], "a")
467 assert completions == expect
468
469
470 @pytest.fixture()
471 def _restore_available_shells(tmpdir):
472 prev_available_shells = click.shell_completion._available_shells.copy()
473 click.shell_completion._available_shells.clear()
474 yield
475 click.shell_completion._available_shells.clear()
476 click.shell_completion._available_shells.update(prev_available_shells)
477
478
479 @pytest.mark.usefixtures("_restore_available_shells")
480 def test_add_completion_class():
481 # At first, "mysh" is not in available shells
482 assert "mysh" not in click.shell_completion._available_shells
483
484 class MyshComplete(ShellComplete):
485 name = "mysh"
486 source_template = "dummy source"
487
488 # "mysh" still not in available shells because it is not registered
489 assert "mysh" not in click.shell_completion._available_shells
490
491 # Adding a completion class should return that class
492 assert add_completion_class(MyshComplete) is MyshComplete
493
494 # Now, "mysh" is finally in available shells
495 assert "mysh" in click.shell_completion._available_shells
496 assert click.shell_completion._available_shells["mysh"] is MyshComplete
497
498
499 @pytest.mark.usefixtures("_restore_available_shells")
500 def test_add_completion_class_with_name():
501 # At first, "mysh" is not in available shells
502 assert "mysh" not in click.shell_completion._available_shells
503 assert "not_mysh" not in click.shell_completion._available_shells
504
505 class MyshComplete(ShellComplete):
506 name = "not_mysh"
507 source_template = "dummy source"
508
509 # "mysh" and "not_mysh" are still not in available shells because
510 # it is not registered yet
511 assert "mysh" not in click.shell_completion._available_shells
512 assert "not_mysh" not in click.shell_completion._available_shells
513
514 # Adding a completion class should return that class.
515 # Because we are using the "name" parameter, the name isn't taken
516 # from the class.
517 assert add_completion_class(MyshComplete, name="mysh") is MyshComplete
518
519 # Now, "mysh" is finally in available shells
520 assert "mysh" in click.shell_completion._available_shells
521 assert "not_mysh" not in click.shell_completion._available_shells
522 assert click.shell_completion._available_shells["mysh"] is MyshComplete
523
524
525 @pytest.mark.usefixtures("_restore_available_shells")
526 def test_add_completion_class_decorator():
527 # At first, "mysh" is not in available shells
528 assert "mysh" not in click.shell_completion._available_shells
529
530 @add_completion_class
531 class MyshComplete(ShellComplete):
532 name = "mysh"
533 source_template = "dummy source"
534
535 # Using `add_completion_class` as a decorator adds the new shell immediately
536 assert "mysh" in click.shell_completion._available_shells
537 assert click.shell_completion._available_shells["mysh"] is MyshComplete
538
539
540 # Don't make the ResourceWarning give an error
541 @pytest.mark.filterwarnings("default")
542 def test_files_closed(runner) -> None:
543 with runner.isolated_filesystem():
544 config_file = "foo.txt"
545 with open(config_file, "w") as f:
546 f.write("bar")
547
548 @click.group()
549 @click.option(
550 "--config-file",
551 default=config_file,
552 type=click.File(mode="r"),
553 )
554 @click.pass_context
555 def cli(ctx, config_file):
556 pass
557
558 with warnings.catch_warnings(record=True) as current_warnings:
559 assert not current_warnings, "There should be no warnings to start"
560 _get_completions(cli, args=[], incomplete="")
561 assert not current_warnings, "There should be no warnings after either"