test_shell_completion.py
This file
Path
tests/test_shell_completion.py
442 lines · 14.6 KiB · Python
Last changed by
Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
History of this fileTake it
The walk stopped after 200 commits: lines older than ddcabdd point at it.
Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
lines 1–2why, one step back1import warnings2Merge pull request #1991 from pallets/pre-commit-ci-update-configDavid Lordbefore adoptionddcabdd
lines 3–4why, one step back3import pytest4Merge branch '8.1.x'David Lordbefore adoption7271763
line 5why, one step back5import click.shell_completionMerge pull request #1991 from pallets/pre-commit-ci-update-configDavid Lordbefore adoptionddcabdd
lines 6–9why, one step back6from click.core import Argument7from click.core import Command8from click.core import Group9from click.core import OptionMerge branch '8.1.x'David Lordbefore adoption7271763
line 10why, one step back10from click.shell_completion import add_completion_classMerge pull request #1991 from pallets/pre-commit-ci-update-configDavid Lordbefore adoptionddcabdd
lines 11–116why, one step back11from click.shell_completion import CompletionItem12from 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"]414243def test_group_command_same_option():44 cli = Group(45 "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]46 )47 assert _get_words(cli, [], "-") == ["-a", "--help"]48 assert _get_words(cli, ["-a", "a"], "-") == ["--help"]49 assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]50 assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]515253def test_chained():54 cli = Group(55 "cli",56 chain=True,57 commands=[58 Command("set", params=[Option(["-y"])]),59 Command("start"),60 Group("get", commands=[Command("full")]),61 ],62 )63 assert _get_words(cli, [], "") == ["get", "set", "start"]64 assert _get_words(cli, [], "s") == ["set", "start"]65 assert _get_words(cli, ["set", "start"], "") == ["get"]66 # subcommands and parent subcommands67 assert _get_words(cli, ["get"], "") == ["full", "set", "start"]68 assert _get_words(cli, ["get", "full"], "") == ["set", "start"]69 assert _get_words(cli, ["get"], "s") == ["set", "start"]707172def test_help_option():73 cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])74 assert _get_words(cli, ["with"], "--") == ["--help"]75 assert _get_words(cli, ["no"], "--") == []767778def test_argument_order():79 cli = Command(80 "cli",81 params=[82 Argument(["plain"]),83 Argument(["c1"], type=Choice(["a1", "a2", "b"])),84 Argument(["c2"], type=Choice(["c1", "c2", "d"])),85 ],86 )87 # first argument has no completions88 assert _get_words(cli, [], "") == []89 assert _get_words(cli, [], "a") == []90 # first argument filled, now completion can happen91 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]92 assert _get_words(cli, ["x", "b"], "d") == ["d"]939495def test_argument_default():96 cli = Command(97 "cli",98 add_help_option=False,99 params=[100 Argument(["a"], type=Choice(["a"]), default="a"),101 Argument(["b"], type=Choice(["b"]), default="b"),102 ],103 )104 assert _get_words(cli, [], "") == ["a"]105 assert _get_words(cli, ["a"], "b") == ["b"]106 # ignore type validation107 assert _get_words(cli, ["x"], "b") == ["b"]108109110def test_type_choice():111 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])112 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]113 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]114 assert _get_words(cli, ["-c"], "a2") == ["a2"]115116Merge pull request #2041 from spanglerco/shell-completion-option-valuesDavid Lordbefore adoptionef11be6
lines 117–155why, one step back117def test_choice_special_characters():118 cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])119 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]120 assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]121 assert _get_words(cli, ["-c"], "!2") == ["!2"]122123124def test_choice_conflicting_prefix():125 cli = Command(126 "cli",127 params=[128 Option(["-c"], type=Choice(["!1", "!2", "+3"])),129 Option(["+p"], is_flag=True),130 ],131 )132 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]133 assert _get_words(cli, ["-c"], "+") == ["+p"]134135136def test_option_count():137 cli = Command("cli", params=[Option(["-c"], count=True)])138 assert _get_words(cli, ["-c"], "") == []139 assert _get_words(cli, ["-c"], "-") == ["--help"]140141142def test_option_optional():143 cli = Command(144 "cli",145 add_help_option=False,146 params=[147 Option(["--name"], is_flag=False, flag_value="value"),148 Option(["--flag"], is_flag=True),149 ],150 )151 assert _get_words(cli, ["--name"], "") == []152 assert _get_words(cli, ["--name"], "-") == ["--flag"]153 assert _get_words(cli, ["--name", "--flag"], "-") == []154155Merge pull request #1991 from pallets/pre-commit-ci-update-configDavid Lordbefore adoptionddcabdd
lines 156–348why, one step back156@pytest.mark.parametrize(157 ("type", "expect"),158 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],159)160def test_path_types(type, expect):161 cli = Command("cli", params=[Option(["-f"], type=type)])162 out = _get_completions(cli, ["-f"], "ab")163 assert len(out) == 1164 c = out[0]165 assert c.value == "ab"166 assert c.type == expect167168169def test_absolute_path():170 cli = Command("cli", params=[Option(["-f"], type=Path())])171 out = _get_completions(cli, ["-f"], "/ab")172 assert len(out) == 1173 c = out[0]174 assert c.value == "/ab"175176177def test_option_flag():178 cli = Command(179 "cli",180 add_help_option=False,181 params=[182 Option(["--on/--off"]),183 Argument(["a"], type=Choice(["a1", "a2", "b"])),184 ],185 )186 assert _get_words(cli, [], "--") == ["--on", "--off"]187 # flag option doesn't take value, use choice argument188 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]189190191def test_option_custom():192 def custom(ctx, param, incomplete):193 return [incomplete.upper()]194195 cli = Command(196 "cli",197 params=[198 Argument(["x"]),199 Argument(["y"]),200 Argument(["z"], shell_complete=custom),201 ],202 )203 assert _get_words(cli, ["a", "b"], "") == [""]204 assert _get_words(cli, ["a", "b"], "c") == ["C"]205206207def test_option_multiple():208 cli = Command(209 "type",210 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],211 )212 assert _get_words(cli, ["-m"], "") == ["a", "b"]213 assert "-m" in _get_words(cli, ["-m", "a"], "-")214 assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]215 # used single options aren't suggested again216 assert "-c" not in _get_words(cli, ["-c", "f"], "-")217218219def test_option_nargs():220 cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])221 assert _get_words(cli, ["-c"], "") == ["a", "b"]222 assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]223 assert _get_words(cli, ["-c", "a", "b"], "") == []224225226def test_argument_nargs():227 cli = Command(228 "cli",229 params=[230 Argument(["x"], type=Choice(["a", "b"]), nargs=2),231 Argument(["y"], type=Choice(["c", "d"]), nargs=-1),232 Option(["-z"]),233 ],234 )235 assert _get_words(cli, [], "") == ["a", "b"]236 assert _get_words(cli, ["a"], "") == ["a", "b"]237 assert _get_words(cli, ["a", "b"], "") == ["c", "d"]238 assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]239 assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]240 assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]241 assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]242243244def test_double_dash():245 cli = Command(246 "cli",247 add_help_option=False,248 params=[249 Option(["--opt"]),250 Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),251 ],252 )253 assert _get_words(cli, [], "-") == ["--opt"]254 assert _get_words(cli, ["value"], "-") == ["--opt"]255 assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]256 assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]257258259def test_hidden():260 cli = Group(261 "cli",262 commands=[263 Command(264 "hidden",265 add_help_option=False,266 hidden=True,267 params=[268 Option(["-a"]),269 Option(["-b"], type=Choice(["a", "b"]), hidden=True),270 ],271 )272 ],273 )274 assert "hidden" not in _get_words(cli, [], "")275 assert "hidden" not in _get_words(cli, [], "hidden")276 assert _get_words(cli, ["hidden"], "-") == ["-a"]277 assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]278279280def test_add_different_name():281 cli = Group("cli", commands={"renamed": Command("original")})282 words = _get_words(cli, [], "")283 assert "renamed" in words284 assert "original" not in words285286287def test_completion_item_data():288 c = CompletionItem("test", a=1)289 assert c.a == 1290 assert c.b is None291292293@pytest.fixture()294def _patch_for_completion(monkeypatch):295 monkeypatch.setattr(296 "click.shell_completion.BashComplete._check_version", lambda self: True297 )298299300@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])301@pytest.mark.usefixtures("_patch_for_completion")302def test_full_source(runner, shell):303 cli = Group("cli", commands=[Command("a"), Command("b")])304 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})305 assert f"_CLI_COMPLETE={shell}_complete" in result.output306307308@pytest.mark.parametrize(309 ("shell", "env", "expect"),310 [311 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),312 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),313 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),314 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),315 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),316 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),317 ],318)319@pytest.mark.usefixtures("_patch_for_completion")320def test_full_complete(runner, shell, env, expect):321 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])322 env["_CLI_COMPLETE"] = f"{shell}_complete"323 result = runner.invoke(cli, env=env)324 assert result.output == expect325326327@pytest.mark.usefixtures("_patch_for_completion")328def test_context_settings(runner):329 def complete(ctx, param, incomplete):330 return ctx.obj["choices"]331332 cli = Command("cli", params=[Argument("x", shell_complete=complete)])333 result = runner.invoke(334 cli,335 obj={"choices": ["a", "b"]},336 env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},337 )338 assert result.output == "plain,a\nplain,b\n"339340341@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])342def test_choice_case_sensitive(value, expect):343 cli = Command(344 "cli",345 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],346 )347 completions = _get_words(cli, ["-a"], "a")348 assert completions == expectMerge branch '8.1.x'David Lordbefore adoption7271763
lines 349–418why, one step back349350351@pytest.fixture()352def _restore_available_shells(tmpdir):353 prev_available_shells = click.shell_completion._available_shells.copy()354 click.shell_completion._available_shells.clear()355 yield356 click.shell_completion._available_shells.clear()357 click.shell_completion._available_shells.update(prev_available_shells)358359360@pytest.mark.usefixtures("_restore_available_shells")361def test_add_completion_class():362 # At first, "mysh" is not in available shells363 assert "mysh" not in click.shell_completion._available_shells364365 class MyshComplete(ShellComplete):366 name = "mysh"367 source_template = "dummy source"368369 # "mysh" still not in available shells because it is not registered370 assert "mysh" not in click.shell_completion._available_shells371372 # Adding a completion class should return that class373 assert add_completion_class(MyshComplete) is MyshComplete374375 # Now, "mysh" is finally in available shells376 assert "mysh" in click.shell_completion._available_shells377 assert click.shell_completion._available_shells["mysh"] is MyshComplete378379380@pytest.mark.usefixtures("_restore_available_shells")381def test_add_completion_class_with_name():382 # At first, "mysh" is not in available shells383 assert "mysh" not in click.shell_completion._available_shells384 assert "not_mysh" not in click.shell_completion._available_shells385386 class MyshComplete(ShellComplete):387 name = "not_mysh"388 source_template = "dummy source"389390 # "mysh" and "not_mysh" are still not in available shells because391 # it is not registered yet392 assert "mysh" not in click.shell_completion._available_shells393 assert "not_mysh" not in click.shell_completion._available_shells394395 # Adding a completion class should return that class.396 # Because we are using the "name" parameter, the name isn't taken397 # from the class.398 assert add_completion_class(MyshComplete, name="mysh") is MyshComplete399400 # Now, "mysh" is finally in available shells401 assert "mysh" in click.shell_completion._available_shells402 assert "not_mysh" not in click.shell_completion._available_shells403 assert click.shell_completion._available_shells["mysh"] is MyshComplete404405406@pytest.mark.usefixtures("_restore_available_shells")407def test_add_completion_class_decorator():408 # At first, "mysh" is not in available shells409 assert "mysh" not in click.shell_completion._available_shells410411 @add_completion_class412 class MyshComplete(ShellComplete):413 name = "mysh"414 source_template = "dummy source"415416 # Using `add_completion_class` as a decorator adds the new shell immediately417 assert "mysh" in click.shell_completion._available_shells418 assert click.shell_completion._available_shells["mysh"] is MyshCompleteClose contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
lines 419–442why, one step back419420421# Don't make the ResourceWarning give an error422@pytest.mark.filterwarnings("default")423def test_files_closed(runner) -> None:424 with runner.isolated_filesystem():425 config_file = "foo.txt"426 with open(config_file, "w") as f:427 f.write("bar")428429 @click.group()430 @click.option(431 "--config-file",432 default=config_file,433 type=click.File(mode="r"),434 )435 @click.pass_context436 def cli(ctx, config_file):437 pass438439 with warnings.catch_warnings(record=True) as current_warnings:440 assert not current_warnings, "There should be no warnings to start"441 _get_completions(cli, args=[], incomplete="")442 assert not current_warnings, "There should be no warnings after either"