test_shell_completion.py
This file
Path
tests/test_shell_completion.py
560 lines · 17.4 KiB · Python
Last changed by
show correct auto complete value for nargs option in combination with flag option (#2816)Rowlando13before adoption4f936ac
History of this fileTake it
The walk stopped after 200 commits: lines older than 7476574 point at it.
Fix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa
line 1why, one step back1import textwrapClose contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
line 2why, one step back2import warningsFix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa
line 3why, one step back3from collections.abc import MappingClose contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
line 4why, one step back4reword locale encoding changelogDavid Lordbefore adoption7476574
lines 5–6why, one step back5import pytest6Merge branch '8.1.x'David Lordbefore adoption7271763
line 7why, one step back7import click.shell_completionreword locale encoding changelogDavid Lordbefore adoption7476574
lines 8–11why, one step back8from click.core import Argument9from click.core import Command10from click.core import Group11from click.core import OptionMerge branch '8.1.x'David Lordbefore adoption7271763
line 12why, one step back12from click.shell_completion import add_completion_classreword locale encoding changelogDavid Lordbefore adoption7476574
lines 13–44why, one step back13from click.shell_completion import CompletionItem14from click.shell_completion import ShellComplete15from click.types import Choice16from click.types import File17from click.types import Path181920def _get_completions(cli, args, incomplete):21 comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")22 return comp.get_completions(args, incomplete)232425def _get_words(cli, args, incomplete):26 return [c.value for c in _get_completions(cli, args, incomplete)]272829def 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 suggested36 assert _get_words(cli, ["-t", "a"], "-") == ["--help"]373839def 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"]4344fix shell completion for nested groups (#2935)David Lordbefore adoptionb7cf069
lines 45–74why, one step back45@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)56def 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) == expect7374reword locale encoding changelogDavid Lordbefore adoption7476574
lines 75–148why, one step back75def 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"]838485def 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 subcommands99 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"]102103104def 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"], "--") == []108109110def 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 completions120 assert _get_words(cli, [], "") == []121 assert _get_words(cli, [], "a") == []122 # first argument filled, now completion can happen123 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]124 assert _get_words(cli, ["x", "b"], "d") == ["d"]125126127def 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 validation139 assert _get_words(cli, ["x"], "b") == ["b"]140141142def 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"]147148Merge pull request #2041 from spanglerco/shell-completion-option-valuesDavid Lordbefore adoptionef11be6
lines 149–187why, one step back149def 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"]154155156def 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"]166167168def 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"]172173174def 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"], "-") == []186187reword locale encoding changelogDavid Lordbefore adoption7476574
lines 188–222why, one step back188@pytest.mark.parametrize(189 ("type", "expect"),190 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],191)192def 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) == 1196 c = out[0]197 assert c.value == "ab"198 assert c.type == expect199200201def test_absolute_path():202 cli = Command("cli", params=[Option(["-f"], type=Path())])203 out = _get_completions(cli, ["-f"], "/ab")204 assert len(out) == 1205 c = out[0]206 assert c.value == "/ab"207208209def 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 argument220 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]221222show correct auto complete value for nargs option in combination with flag option (#2816)Rowlando13before adoption4f936ac
lines 223–235why, one step back223def 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"]234235reword locale encoding changelogDavid Lordbefore adoption7476574
lines 236–368why, one step back236def test_option_custom():237 def custom(ctx, param, incomplete):238 return [incomplete.upper()]239240 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"]250251252def 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 again261 assert "-c" not in _get_words(cli, ["-c", "f"], "-")262263264def 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"], "") == []269270271def 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"]287288289def 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"]302303304def 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"]323324325def test_add_different_name():326 cli = Group("cli", commands={"renamed": Command("original")})327 words = _get_words(cli, [], "")328 assert "renamed" in words329 assert "original" not in words330331332def test_completion_item_data():333 c = CompletionItem("test", a=1)334 assert c.a == 1335 assert c.b is None336337338@pytest.fixture()339def _patch_for_completion(monkeypatch):340 monkeypatch.setattr(341 "click.shell_completion.BashComplete._check_version", lambda self: True342 )343344345@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])346@pytest.mark.usefixtures("_patch_for_completion")347def 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.output351352353@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 ],363)364@pytest.mark.usefixtures("_patch_for_completion")365def test_full_complete(runner, shell, env, expect):366 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])367 env["_CLI_COMPLETE"] = f"{shell}_complete"368 result = runner.invoke(cli, env=env)Fix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa
lines 369–441why, one step back369 assert result.output == expect370371372@pytest.mark.parametrize(373 ("env", "expect"),374 [375 (376 {"COMP_WORDS": "", "COMP_CWORD": "0"},377 textwrap.dedent(378 """\379 plain380 a381 _382 plain383 b384 bee385 plain386 c\\:d387 cee:dee388 plain389 c:e390 _391 """392 ),393 ),394 (395 {"COMP_WORDS": "a c", "COMP_CWORD": "1"},396 textwrap.dedent(397 """\398 plain399 c\\:d400 cee:dee401 plain402 c:e403 _404 """405 ),406 ),407 (408 {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},409 textwrap.dedent(410 """\411 plain412 c\\:d413 cee:dee414 plain415 c:e416 _417 """418 ),419 ),420 ],421)422@pytest.mark.usefixtures("_patch_for_completion")423def test_zsh_full_complete_with_colons(424 runner, env: Mapping[str, str], expect: str425) -> None:426 cli = Group(427 "cli",428 commands=[429 Command("a"),430 Command("b", help="bee"),431 Command("c:d", help="cee:dee"),432 Command("c:e"),433 ],434 )435 result = runner.invoke(436 cli,437 env={438 **env,439 "_CLI_COMPLETE": "zsh_complete",440 },441 )reword locale encoding changelogDavid Lordbefore adoption7476574
lines 442–466why, one step back442 assert result.output == expect443444445@pytest.mark.usefixtures("_patch_for_completion")446def test_context_settings(runner):447 def complete(ctx, param, incomplete):448 return ctx.obj["choices"]449450 cli = Command("cli", params=[Argument("x", shell_complete=complete)])451 result = runner.invoke(452 cli,453 obj={"choices": ["a", "b"]},454 env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},455 )456 assert result.output == "plain,a\nplain,b\n"457458459@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])460def test_choice_case_sensitive(value, expect):461 cli = Command(462 "cli",463 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],464 )465 completions = _get_words(cli, ["-a"], "a")466 assert completions == expectMerge branch '8.1.x'David Lordbefore adoption7271763
lines 467–536why, one step back467468469@pytest.fixture()470def _restore_available_shells(tmpdir):471 prev_available_shells = click.shell_completion._available_shells.copy()472 click.shell_completion._available_shells.clear()473 yield474 click.shell_completion._available_shells.clear()475 click.shell_completion._available_shells.update(prev_available_shells)476477478@pytest.mark.usefixtures("_restore_available_shells")479def test_add_completion_class():480 # At first, "mysh" is not in available shells481 assert "mysh" not in click.shell_completion._available_shells482483 class MyshComplete(ShellComplete):484 name = "mysh"485 source_template = "dummy source"486487 # "mysh" still not in available shells because it is not registered488 assert "mysh" not in click.shell_completion._available_shells489490 # Adding a completion class should return that class491 assert add_completion_class(MyshComplete) is MyshComplete492493 # Now, "mysh" is finally in available shells494 assert "mysh" in click.shell_completion._available_shells495 assert click.shell_completion._available_shells["mysh"] is MyshComplete496497498@pytest.mark.usefixtures("_restore_available_shells")499def test_add_completion_class_with_name():500 # At first, "mysh" is not in available shells501 assert "mysh" not in click.shell_completion._available_shells502 assert "not_mysh" not in click.shell_completion._available_shells503504 class MyshComplete(ShellComplete):505 name = "not_mysh"506 source_template = "dummy source"507508 # "mysh" and "not_mysh" are still not in available shells because509 # it is not registered yet510 assert "mysh" not in click.shell_completion._available_shells511 assert "not_mysh" not in click.shell_completion._available_shells512513 # Adding a completion class should return that class.514 # Because we are using the "name" parameter, the name isn't taken515 # from the class.516 assert add_completion_class(MyshComplete, name="mysh") is MyshComplete517518 # Now, "mysh" is finally in available shells519 assert "mysh" in click.shell_completion._available_shells520 assert "not_mysh" not in click.shell_completion._available_shells521 assert click.shell_completion._available_shells["mysh"] is MyshComplete522523524@pytest.mark.usefixtures("_restore_available_shells")525def test_add_completion_class_decorator():526 # At first, "mysh" is not in available shells527 assert "mysh" not in click.shell_completion._available_shells528529 @add_completion_class530 class MyshComplete(ShellComplete):531 name = "mysh"532 source_template = "dummy source"533534 # Using `add_completion_class` as a decorator adds the new shell immediately535 assert "mysh" in click.shell_completion._available_shells536 assert click.shell_completion._available_shells["mysh"] is MyshCompleteClose contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
lines 537–560why, one step back537538539# Don't make the ResourceWarning give an error540@pytest.mark.filterwarnings("default")541def test_files_closed(runner) -> None:542 with runner.isolated_filesystem():543 config_file = "foo.txt"544 with open(config_file, "w") as f:545 f.write("bar")546547 @click.group()548 @click.option(549 "--config-file",550 default=config_file,551 type=click.File(mode="r"),552 )553 @click.pass_context554 def cli(ctx, config_file):555 pass556557 with warnings.catch_warnings(record=True) as current_warnings:558 assert not current_warnings, "There should be no warnings to start"559 _get_completions(cli, args=[], incomplete="")560 assert not current_warnings, "There should be no warnings after either"