Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

472 lines · 15.4 KiB · Python

Last changed by

fix shell completion for nested groups (#2935)David Lordbefore adoptionb7cf069

History of this file

Take it

The walk stopped after 200 commits: lines older than 08ecfd0 point at it.

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 1–2why, one step back
1import warnings
2

keep !r format for nowDavid Lordbefore adoption08ecfd0

lines 3–4why, one step back
3import pytest
4

Merge branch '8.1.x'David Lordbefore adoption7271763

line 5why, one step back
5import click.shell_completion

keep !r format for nowDavid Lordbefore adoption08ecfd0

lines 6–9why, one step back
6from click.core import Argument
7from click.core import Command8from click.core import Group9from click.core import Option

Merge branch '8.1.x'David Lordbefore adoption7271763

line 10why, one step back
10from click.shell_completion import add_completion_class

keep !r format for nowDavid Lordbefore adoption08ecfd0

lines 11–42why, one step back
11from click.shell_completion import CompletionItem
12from click.shell_completion import ShellComplete13from click.types import Choice14from click.types import File15from click.types import Path161718def _get_completions(cli, args, incomplete):19 comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")20 return comp.get_completions(args, incomplete)212223def _get_words(cli, args, incomplete):24 return [c.value for c in _get_completions(cli, args, incomplete)]252627def test_command():28 cli = Command("cli", params=[Option(["-t", "--test"])])29 assert _get_words(cli, [], "") == []30 assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]31 assert _get_words(cli, [], "--") == ["--test", "--help"]32 assert _get_words(cli, [], "--t") == ["--test"]33 # -t has been seen, so --test isn't suggested34 assert _get_words(cli, ["-t", "a"], "-") == ["--help"]353637def test_group():38 cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])39 assert _get_words(cli, [], "") == ["x", "y"]40 assert _get_words(cli, [], "-") == ["-a", "--help"]4142

fix shell completion for nested groups (#2935)David Lordbefore adoptionb7cf069

lines 43–72why, one step back
43@pytest.mark.parametrize(
44 ("args", "word", "expect"),45 [46 ([], "", ["get"]),47 (["get"], "", ["full"]),48 (["get", "full"], "", ["data"]),49 (["get", "full"], "-", ["--verbose", "--help"]),50 (["get", "full", "data"], "", []),51 (["get", "full", "data"], "-", ["-a", "--help"]),52 ],53)54def test_nested_group(args: list[str], word: str, expect: list[str]) -> None:55 cli = Group(56 "cli",57 commands=[58 Group(59 "get",60 commands=[61 Group(62 "full",63 params=[Option(["--verbose"])],64 commands=[Command("data", params=[Option(["-a"])])],65 )66 ],67 )68 ],69 )70 assert _get_words(cli, args, word) == expect7172

keep !r format for nowDavid Lordbefore adoption08ecfd0

lines 73–146why, one step back
73def test_group_command_same_option():
74 cli = Group(75 "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]76 )77 assert _get_words(cli, [], "-") == ["-a", "--help"]78 assert _get_words(cli, ["-a", "a"], "-") == ["--help"]79 assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]80 assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]818283def test_chained():84 cli = Group(85 "cli",86 chain=True,87 commands=[88 Command("set", params=[Option(["-y"])]),89 Command("start"),90 Group("get", commands=[Command("full")]),91 ],92 )93 assert _get_words(cli, [], "") == ["get", "set", "start"]94 assert _get_words(cli, [], "s") == ["set", "start"]95 assert _get_words(cli, ["set", "start"], "") == ["get"]96 # subcommands and parent subcommands97 assert _get_words(cli, ["get"], "") == ["full", "set", "start"]98 assert _get_words(cli, ["get", "full"], "") == ["set", "start"]99 assert _get_words(cli, ["get"], "s") == ["set", "start"]100101102def test_help_option():103 cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])104 assert _get_words(cli, ["with"], "--") == ["--help"]105 assert _get_words(cli, ["no"], "--") == []106107108def test_argument_order():109 cli = Command(110 "cli",111 params=[112 Argument(["plain"]),113 Argument(["c1"], type=Choice(["a1", "a2", "b"])),114 Argument(["c2"], type=Choice(["c1", "c2", "d"])),115 ],116 )117 # first argument has no completions118 assert _get_words(cli, [], "") == []119 assert _get_words(cli, [], "a") == []120 # first argument filled, now completion can happen121 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]122 assert _get_words(cli, ["x", "b"], "d") == ["d"]123124125def test_argument_default():126 cli = Command(127 "cli",128 add_help_option=False,129 params=[130 Argument(["a"], type=Choice(["a"]), default="a"),131 Argument(["b"], type=Choice(["b"]), default="b"),132 ],133 )134 assert _get_words(cli, [], "") == ["a"]135 assert _get_words(cli, ["a"], "b") == ["b"]136 # ignore type validation137 assert _get_words(cli, ["x"], "b") == ["b"]138139140def test_type_choice():141 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])142 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]143 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]144 assert _get_words(cli, ["-c"], "a2") == ["a2"]145146

Merge pull request #2041 from spanglerco/shell-completion-option-valuesDavid Lordbefore adoptionef11be6

lines 147–185why, one step back
147def test_choice_special_characters():
148 cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])149 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]150 assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]151 assert _get_words(cli, ["-c"], "!2") == ["!2"]152153154def test_choice_conflicting_prefix():155 cli = Command(156 "cli",157 params=[158 Option(["-c"], type=Choice(["!1", "!2", "+3"])),159 Option(["+p"], is_flag=True),160 ],161 )162 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]163 assert _get_words(cli, ["-c"], "+") == ["+p"]164165166def test_option_count():167 cli = Command("cli", params=[Option(["-c"], count=True)])168 assert _get_words(cli, ["-c"], "") == []169 assert _get_words(cli, ["-c"], "-") == ["--help"]170171172def test_option_optional():173 cli = Command(174 "cli",175 add_help_option=False,176 params=[177 Option(["--name"], is_flag=False, flag_value="value"),178 Option(["--flag"], is_flag=True),179 ],180 )181 assert _get_words(cli, ["--name"], "") == []182 assert _get_words(cli, ["--name"], "-") == ["--flag"]183 assert _get_words(cli, ["--name", "--flag"], "-") == []184185

keep !r format for nowDavid Lordbefore adoption08ecfd0

lines 186–378why, one step back
186@pytest.mark.parametrize(
187 ("type", "expect"),188 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],189)190def test_path_types(type, expect):191 cli = Command("cli", params=[Option(["-f"], type=type)])192 out = _get_completions(cli, ["-f"], "ab")193 assert len(out) == 1194 c = out[0]195 assert c.value == "ab"196 assert c.type == expect197198199def test_absolute_path():200 cli = Command("cli", params=[Option(["-f"], type=Path())])201 out = _get_completions(cli, ["-f"], "/ab")202 assert len(out) == 1203 c = out[0]204 assert c.value == "/ab"205206207def test_option_flag():208 cli = Command(209 "cli",210 add_help_option=False,211 params=[212 Option(["--on/--off"]),213 Argument(["a"], type=Choice(["a1", "a2", "b"])),214 ],215 )216 assert _get_words(cli, [], "--") == ["--on", "--off"]217 # flag option doesn't take value, use choice argument218 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]219220221def test_option_custom():222 def custom(ctx, param, incomplete):223 return [incomplete.upper()]224225 cli = Command(226 "cli",227 params=[228 Argument(["x"]),229 Argument(["y"]),230 Argument(["z"], shell_complete=custom),231 ],232 )233 assert _get_words(cli, ["a", "b"], "") == [""]234 assert _get_words(cli, ["a", "b"], "c") == ["C"]235236237def test_option_multiple():238 cli = Command(239 "type",240 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],241 )242 assert _get_words(cli, ["-m"], "") == ["a", "b"]243 assert "-m" in _get_words(cli, ["-m", "a"], "-")244 assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]245 # used single options aren't suggested again246 assert "-c" not in _get_words(cli, ["-c", "f"], "-")247248249def test_option_nargs():250 cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])251 assert _get_words(cli, ["-c"], "") == ["a", "b"]252 assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]253 assert _get_words(cli, ["-c", "a", "b"], "") == []254255256def test_argument_nargs():257 cli = Command(258 "cli",259 params=[260 Argument(["x"], type=Choice(["a", "b"]), nargs=2),261 Argument(["y"], type=Choice(["c", "d"]), nargs=-1),262 Option(["-z"]),263 ],264 )265 assert _get_words(cli, [], "") == ["a", "b"]266 assert _get_words(cli, ["a"], "") == ["a", "b"]267 assert _get_words(cli, ["a", "b"], "") == ["c", "d"]268 assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]269 assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]270 assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]271 assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]272273274def test_double_dash():275 cli = Command(276 "cli",277 add_help_option=False,278 params=[279 Option(["--opt"]),280 Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),281 ],282 )283 assert _get_words(cli, [], "-") == ["--opt"]284 assert _get_words(cli, ["value"], "-") == ["--opt"]285 assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]286 assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]287288289def test_hidden():290 cli = Group(291 "cli",292 commands=[293 Command(294 "hidden",295 add_help_option=False,296 hidden=True,297 params=[298 Option(["-a"]),299 Option(["-b"], type=Choice(["a", "b"]), hidden=True),300 ],301 )302 ],303 )304 assert "hidden" not in _get_words(cli, [], "")305 assert "hidden" not in _get_words(cli, [], "hidden")306 assert _get_words(cli, ["hidden"], "-") == ["-a"]307 assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]308309310def test_add_different_name():311 cli = Group("cli", commands={"renamed": Command("original")})312 words = _get_words(cli, [], "")313 assert "renamed" in words314 assert "original" not in words315316317def test_completion_item_data():318 c = CompletionItem("test", a=1)319 assert c.a == 1320 assert c.b is None321322323@pytest.fixture()324def _patch_for_completion(monkeypatch):325 monkeypatch.setattr(326 "click.shell_completion.BashComplete._check_version", lambda self: True327 )328329330@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])331@pytest.mark.usefixtures("_patch_for_completion")332def test_full_source(runner, shell):333 cli = Group("cli", commands=[Command("a"), Command("b")])334 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})335 assert f"_CLI_COMPLETE={shell}_complete" in result.output336337338@pytest.mark.parametrize(339 ("shell", "env", "expect"),340 [341 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),342 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),343 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),344 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),345 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),346 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),347 ],348)349@pytest.mark.usefixtures("_patch_for_completion")350def test_full_complete(runner, shell, env, expect):351 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])352 env["_CLI_COMPLETE"] = f"{shell}_complete"353 result = runner.invoke(cli, env=env)354 assert result.output == expect355356357@pytest.mark.usefixtures("_patch_for_completion")358def test_context_settings(runner):359 def complete(ctx, param, incomplete):360 return ctx.obj["choices"]361362 cli = Command("cli", params=[Argument("x", shell_complete=complete)])363 result = runner.invoke(364 cli,365 obj={"choices": ["a", "b"]},366 env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},367 )368 assert result.output == "plain,a\nplain,b\n"369370371@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])372def test_choice_case_sensitive(value, expect):373 cli = Command(374 "cli",375 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],376 )377 completions = _get_words(cli, ["-a"], "a")378 assert completions == expect

Merge branch '8.1.x'David Lordbefore adoption7271763

lines 379–448why, one step back
379
380381@pytest.fixture()382def _restore_available_shells(tmpdir):383 prev_available_shells = click.shell_completion._available_shells.copy()384 click.shell_completion._available_shells.clear()385 yield386 click.shell_completion._available_shells.clear()387 click.shell_completion._available_shells.update(prev_available_shells)388389390@pytest.mark.usefixtures("_restore_available_shells")391def test_add_completion_class():392 # At first, "mysh" is not in available shells393 assert "mysh" not in click.shell_completion._available_shells394395 class MyshComplete(ShellComplete):396 name = "mysh"397 source_template = "dummy source"398399 # "mysh" still not in available shells because it is not registered400 assert "mysh" not in click.shell_completion._available_shells401402 # Adding a completion class should return that class403 assert add_completion_class(MyshComplete) is MyshComplete404405 # Now, "mysh" is finally in available shells406 assert "mysh" in click.shell_completion._available_shells407 assert click.shell_completion._available_shells["mysh"] is MyshComplete408409410@pytest.mark.usefixtures("_restore_available_shells")411def test_add_completion_class_with_name():412 # At first, "mysh" is not in available shells413 assert "mysh" not in click.shell_completion._available_shells414 assert "not_mysh" not in click.shell_completion._available_shells415416 class MyshComplete(ShellComplete):417 name = "not_mysh"418 source_template = "dummy source"419420 # "mysh" and "not_mysh" are still not in available shells because421 # it is not registered yet422 assert "mysh" not in click.shell_completion._available_shells423 assert "not_mysh" not in click.shell_completion._available_shells424425 # Adding a completion class should return that class.426 # Because we are using the "name" parameter, the name isn't taken427 # from the class.428 assert add_completion_class(MyshComplete, name="mysh") is MyshComplete429430 # Now, "mysh" is finally in available shells431 assert "mysh" in click.shell_completion._available_shells432 assert "not_mysh" not in click.shell_completion._available_shells433 assert click.shell_completion._available_shells["mysh"] is MyshComplete434435436@pytest.mark.usefixtures("_restore_available_shells")437def test_add_completion_class_decorator():438 # At first, "mysh" is not in available shells439 assert "mysh" not in click.shell_completion._available_shells440441 @add_completion_class442 class MyshComplete(ShellComplete):443 name = "mysh"444 source_template = "dummy source"445446 # Using `add_completion_class` as a decorator adds the new shell immediately447 assert "mysh" in click.shell_completion._available_shells448 assert click.shell_completion._available_shells["mysh"] is MyshComplete

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 449–472why, one step back
449
450451# Don't make the ResourceWarning give an error452@pytest.mark.filterwarnings("default")453def test_files_closed(runner) -> None:454 with runner.isolated_filesystem():455 config_file = "foo.txt"456 with open(config_file, "w") as f:457 f.write("bar")458459 @click.group()460 @click.option(461 "--config-file",462 default=config_file,463 type=click.File(mode="r"),464 )465 @click.pass_context466 def cli(ctx, config_file):467 pass468469 with warnings.catch_warnings(record=True) as current_warnings:470 assert not current_warnings, "There should be no warnings to start"471 _get_completions(cli, args=[], incomplete="")472 assert not current_warnings, "There should be no warnings after either"