test_shell_completion.py
This file
Path
tests/test_shell_completion.py
322 lines · 10.3 KiB · Python
Last changed by
Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd
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_absolute_path():129 cli = Command("cli", params=[Option(["-f"], type=Path())])130 out = _get_completions(cli, ["-f"], "/ab")131 assert len(out) == 1132 c = out[0]133 assert c.value == "/ab"134135136def test_option_flag():137 cli = Command(138 "cli",139 add_help_option=False,140 params=[141 Option(["--on/--off"]),142 Argument(["a"], type=Choice(["a1", "a2", "b"])),143 ],144 )145 assert _get_words(cli, [], "--") == ["--on", "--off"]146 # flag option doesn't take value, use choice argument147 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]148149150def test_option_custom():151 def custom(ctx, param, incomplete):152 return [incomplete.upper()]153154 cli = Command(155 "cli",156 params=[157 Argument(["x"]),158 Argument(["y"]),159 Argument(["z"], shell_complete=custom),160 ],161 )162 assert _get_words(cli, ["a", "b"], "") == [""]163 assert _get_words(cli, ["a", "b"], "c") == ["C"]164165166def test_autocompletion_deprecated():167 # old function takes args and not param, returns all values, can mix168 # strings and tuples169 def custom(ctx, args, incomplete):170 assert isinstance(args, list)171 return [("art", "x"), "bat", "cat"]172173 with pytest.deprecated_call():174 cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])175176 assert _get_words(cli, [], "") == ["art", "bat", "cat"]177 assert _get_words(cli, [], "c") == ["cat"]178179180def test_option_multiple():181 cli = Command(182 "type",183 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],184 )185 assert _get_words(cli, ["-m"], "") == ["a", "b"]186 assert "-m" in _get_words(cli, ["-m", "a"], "-")187 assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]188 # used single options aren't suggested again189 assert "-c" not in _get_words(cli, ["-c", "f"], "-")190191192def test_option_nargs():193 cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])194 assert _get_words(cli, ["-c"], "") == ["a", "b"]195 assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]196 assert _get_words(cli, ["-c", "a", "b"], "") == []197198199def test_argument_nargs():200 cli = Command(201 "cli",202 params=[203 Argument(["x"], type=Choice(["a", "b"]), nargs=2),204 Argument(["y"], type=Choice(["c", "d"]), nargs=-1),205 Option(["-z"]),206 ],207 )208 assert _get_words(cli, [], "") == ["a", "b"]209 assert _get_words(cli, ["a"], "") == ["a", "b"]210 assert _get_words(cli, ["a", "b"], "") == ["c", "d"]211 assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]212 assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]213 assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]214 assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]215216217def test_double_dash():218 cli = Command(219 "cli",220 add_help_option=False,221 params=[222 Option(["--opt"]),223 Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),224 ],225 )226 assert _get_words(cli, [], "-") == ["--opt"]227 assert _get_words(cli, ["value"], "-") == ["--opt"]228 assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]229 assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]230231232def test_hidden():233 cli = Group(234 "cli",235 commands=[236 Command(237 "hidden",238 add_help_option=False,239 hidden=True,240 params=[241 Option(["-a"]),242 Option(["-b"], type=Choice(["a", "b"]), hidden=True),243 ],244 )245 ],246 )247 assert "hidden" not in _get_words(cli, [], "")248 assert "hidden" not in _get_words(cli, [], "hidden")249 assert _get_words(cli, ["hidden"], "-") == ["-a"]250 assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]251252253def test_add_different_name():254 cli = Group("cli", commands={"renamed": Command("original")})255 words = _get_words(cli, [], "")256 assert "renamed" in words257 assert "original" not in words258259260def test_completion_item_data():261 c = CompletionItem("test", a=1)262 assert c.a == 1263 assert c.b is None264265266@pytest.fixture()267def _patch_for_completion(monkeypatch):268 monkeypatch.setattr("click.core._fast_exit", sys.exit)269 monkeypatch.setattr(270 "click.shell_completion.BashComplete._check_version", lambda self: True271 )272273274@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])275@pytest.mark.usefixtures("_patch_for_completion")276def test_full_source(runner, shell):277 cli = Group("cli", commands=[Command("a"), Command("b")])278 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})279 assert f"_CLI_COMPLETE={shell}_complete" in result.output280281282@pytest.mark.parametrize(283 ("shell", "env", "expect"),284 [285 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),286 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),287 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),288 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),289 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),290 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),291 ],292)293@pytest.mark.usefixtures("_patch_for_completion")294def test_full_complete(runner, shell, env, expect):295 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])296 env["_CLI_COMPLETE"] = f"{shell}_complete"297 result = runner.invoke(cli, env=env)298 assert result.output == expect299300301@pytest.mark.usefixtures("_patch_for_completion")302def test_context_settings(runner):303 def complete(ctx, param, incomplete):304 return ctx.obj["choices"]305306 cli = Command("cli", params=[Argument("x", shell_complete=complete)])307 result = runner.invoke(308 cli,309 obj={"choices": ["a", "b"]},310 env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},311 )312 assert result.output == "plain,a\nplain,b\n"313314315@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])316def test_choice_case_sensitive(value, expect):317 cli = Command(318 "cli",319 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],320 )321 completions = _get_words(cli, ["-a"], "a")322 assert completions == expect