test_shell_completion.py
This file
Path
tests/test_shell_completion.py
316 lines · 10.2 KiB · Python
Last changed by
Merge pull request #1693 from felixnorden/1692-case-sensitive-shell-completionsDavid Lordbefore adoption5eb46cb
History of this fileTake it
1import sys23import pytest45from click.core import Argument6from click.core import Command7from click.core import Group8from click.core import Option9from click.shell_completion import CompletionItem10from click.shell_completion import ShellComplete11from click.types import Choice12from click.types import File13from click.types import Path141516def _get_completions(cli, args, incomplete):17 comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")18 return comp.get_completions(args, incomplete)192021def _get_words(cli, args, incomplete):22 return [c.value for c in _get_completions(cli, args, incomplete)]232425def test_command():26 cli = Command("cli", params=[Option(["-t", "--test"])])27 assert _get_words(cli, [], "") == []28 assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]29 assert _get_words(cli, [], "--") == ["--test", "--help"]30 assert _get_words(cli, [], "--t") == ["--test"]31 # -t has been seen, so --test isn't suggested32 assert _get_words(cli, ["-t", "a"], "-") == ["--help"]333435def test_group():36 cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])37 assert _get_words(cli, [], "") == ["x", "y"]38 assert _get_words(cli, [], "-") == ["-a", "--help"]394041def test_group_command_same_option():42 cli = Group(43 "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]44 )45 assert _get_words(cli, [], "-") == ["-a", "--help"]46 assert _get_words(cli, ["-a", "a"], "-") == ["--help"]47 assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]48 assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]495051def test_chained():52 cli = Group(53 "cli",54 chain=True,55 commands=[56 Command("set", params=[Option(["-y"])]),57 Command("start"),58 Group("get", commands=[Command("full")]),59 ],60 )61 assert _get_words(cli, [], "") == ["get", "set", "start"]62 assert _get_words(cli, [], "s") == ["set", "start"]63 assert _get_words(cli, ["set", "start"], "") == ["get"]64 # subcommands and parent subcommands65 assert _get_words(cli, ["get"], "") == ["full", "set", "start"]66 assert _get_words(cli, ["get", "full"], "") == ["set", "start"]67 assert _get_words(cli, ["get"], "s") == ["set", "start"]686970def test_help_option():71 cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])72 assert _get_words(cli, ["with"], "--") == ["--help"]73 assert _get_words(cli, ["no"], "--") == []747576def test_argument_order():77 cli = Command(78 "cli",79 params=[80 Argument(["plain"]),81 Argument(["c1"], type=Choice(["a1", "a2", "b"])),82 Argument(["c2"], type=Choice(["c1", "c2", "d"])),83 ],84 )85 # first argument has no completions86 assert _get_words(cli, [], "") == []87 assert _get_words(cli, [], "a") == []88 # first argument filled, now completion can happen89 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]90 assert _get_words(cli, ["x", "b"], "d") == ["d"]919293def test_argument_default():94 cli = Command(95 "cli",96 add_help_option=False,97 params=[98 Argument(["a"], type=Choice(["a"]), default="a"),99 Argument(["b"], type=Choice(["b"]), default="b"),100 ],101 )102 assert _get_words(cli, [], "") == ["a"]103 assert _get_words(cli, ["a"], "b") == ["b"]104 # ignore type validation105 assert _get_words(cli, ["x"], "b") == ["b"]106107108def test_type_choice():109 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])110 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]111 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]112 assert _get_words(cli, ["-c"], "a2") == ["a2"]113114115@pytest.mark.parametrize(116 ("type", "expect"),117 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],118)119def test_path_types(type, expect):120 cli = Command("cli", params=[Option(["-f"], type=type)])121 out = _get_completions(cli, ["-f"], "ab")122 assert len(out) == 1123 c = out[0]124 assert c.value == "ab"125 assert c.type == expect126127128def test_option_flag():129 cli = Command(130 "cli",131 add_help_option=False,132 params=[133 Option(["--on/--off"]),134 Argument(["a"], type=Choice(["a1", "a2", "b"])),135 ],136 )137 assert _get_words(cli, [], "--") == ["--on", "--off"]138 # flag option doesn't take value, use choice argument139 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]140141142def test_option_custom():143 def custom(ctx, param, incomplete):144 return [incomplete.upper()]145146 cli = Command(147 "cli",148 params=[149 Argument(["x"]),150 Argument(["y"]),151 Argument(["z"], shell_complete=custom),152 ],153 )154 assert _get_words(cli, ["a", "b"], "") == [""]155 assert _get_words(cli, ["a", "b"], "c") == ["C"]156157158def test_autocompletion_deprecated():159 # old function takes args and not param, returns all values, can mix160 # strings and tuples161 def custom(ctx, args, incomplete):162 assert isinstance(args, list)163 return [("art", "x"), "bat", "cat"]164165 with pytest.deprecated_call():166 cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])167168 assert _get_words(cli, [], "") == ["art", "bat", "cat"]169 assert _get_words(cli, [], "c") == ["cat"]170171172def test_option_multiple():173 cli = Command(174 "type",175 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],176 )177 assert _get_words(cli, ["-m"], "") == ["a", "b"]178 assert "-m" in _get_words(cli, ["-m", "a"], "-")179 assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]180 # used single options aren't suggested again181 assert "-c" not in _get_words(cli, ["-c", "f"], "-")182183184def test_option_nargs():185 cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])186 assert _get_words(cli, ["-c"], "") == ["a", "b"]187 assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]188 assert _get_words(cli, ["-c", "a", "b"], "") == []189190191def test_argument_nargs():192 cli = Command(193 "cli",194 params=[195 Argument(["x"], type=Choice(["a", "b"]), nargs=2),196 Argument(["y"], type=Choice(["c", "d"]), nargs=-1),197 Option(["-z"]),198 ],199 )200 assert _get_words(cli, [], "") == ["a", "b"]201 assert _get_words(cli, ["a"], "") == ["a", "b"]202 assert _get_words(cli, ["a", "b"], "") == ["c", "d"]203 assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]204 assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]205 assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]206 assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]207208209def test_double_dash():210 cli = Command(211 "cli",212 add_help_option=False,213 params=[214 Option(["--opt"]),215 Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),216 ],217 )218 assert _get_words(cli, [], "-") == ["--opt"]219 assert _get_words(cli, ["value"], "-") == ["--opt"]220 assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]221 assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]222223224def test_hidden():225 cli = Group(226 "cli",227 commands=[228 Command(229 "hidden",230 add_help_option=False,231 hidden=True,232 params=[233 Option(["-a"]),234 Option(["-b"], type=Choice(["a", "b"]), hidden=True),235 ],236 )237 ],238 )239 assert "hidden" not in _get_words(cli, [], "")240 assert "hidden" not in _get_words(cli, [], "hidden")241 assert _get_words(cli, ["hidden"], "-") == ["-a"]242 assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]243244245def test_add_different_name():246 cli = Group("cli", commands={"renamed": Command("original")})247 words = _get_words(cli, [], "")248 assert "renamed" in words249 assert "original" not in words250251252def test_completion_item_data():253 c = CompletionItem("test", a=1)254 assert c.a == 1255 assert c.b is None256257258@pytest.fixture()259def _patch_for_completion(monkeypatch):260 monkeypatch.setattr("click.core._fast_exit", sys.exit)261 monkeypatch.setattr(262 "click.shell_completion.BashComplete._check_version", lambda self: True263 )264265266@pytest.mark.parametrize(267 "shell", ["bash", "zsh", "fish"],268)269@pytest.mark.usefixtures("_patch_for_completion")270def test_full_source(runner, shell):271 cli = Group("cli", commands=[Command("a"), Command("b")])272 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})273 assert f"_CLI_COMPLETE={shell}_complete" in result.output274275276@pytest.mark.parametrize(277 ("shell", "env", "expect"),278 [279 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),280 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),281 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),282 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),283 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),284 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),285 ],286)287@pytest.mark.usefixtures("_patch_for_completion")288def test_full_complete(runner, shell, env, expect):289 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])290 env["_CLI_COMPLETE"] = f"{shell}_complete"291 result = runner.invoke(cli, env=env)292 assert result.output == expect293294295@pytest.mark.usefixtures("_patch_for_completion")296def test_context_settings(runner):297 def complete(ctx, param, incomplete):298 return ctx.obj["choices"]299300 cli = Command("cli", params=[Argument("x", shell_complete=complete)])301 result = runner.invoke(302 cli,303 obj={"choices": ["a", "b"]},304 env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},305 )306 assert result.output == "plain,a\nplain,b\n"307308309@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])310def test_choice_case_sensitive(value, expect):311 cli = Command(312 "cli",313 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],314 )315 completions = _get_words(cli, ["-a"], "a")316 assert completions == expect