test_shell_completion.py
This file
Path
tests/test_shell_completion.py
578 lines · 18.1 KiB · Python
Last changed by
Fix broken fish completion and multiline help stringSitiyoubefore adoptionb7e5fd4
History of this fileTake it
The walk stopped after 200 commits: lines older than 7ac7e2a point at it.
apply Unix line endings for shell completion output for windows compat (#3466)David Lordbefore adoptione0d1678
line 1why, one step back1import ioFix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa
line 2why, one step back2import textwrapClose contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
line 3why, one step back3import warningsFix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa
line 4why, one step back4from collections.abc import MappingClose contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
line 5why, one step back5remove extraneous test envsDavid Lordbefore adoption7ac7e2a
lines 6–14why, one step back6import pytest78import click.shell_completion9from click.core import Argument10from click.core import Command11from click.core import Group12from click.core import Option13from click.shell_completion import add_completion_class14from click.shell_completion import CompletionItemapply Unix line endings for shell completion output for windows compat (#3466)David Lordbefore adoptione0d1678
line 15why, one step back15from click.shell_completion import shell_completeremove extraneous test envsDavid Lordbefore adoption7ac7e2a
lines 16–46why, one step back16from click.shell_completion import ShellComplete17from click.types import Choice18from click.types import File19from click.types import Path202122def _get_completions(cli, args, incomplete):23 comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")24 return comp.get_completions(args, incomplete)252627def _get_words(cli, args, incomplete):28 return [c.value for c in _get_completions(cli, args, incomplete)]293031def test_command():32 cli = Command("cli", params=[Option(["-t", "--test"])])33 assert _get_words(cli, [], "") == []34 assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]35 assert _get_words(cli, [], "--") == ["--test", "--help"]36 assert _get_words(cli, [], "--t") == ["--test"]37 # -t has been seen, so --test isn't suggested38 assert _get_words(cli, ["-t", "a"], "-") == ["--help"]394041def test_group():42 cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])43 assert _get_words(cli, [], "") == ["x", "y"]44 assert _get_words(cli, [], "-") == ["-a", "--help"]4546fix shell completion for nested groups (#2935)David Lordbefore adoptionb7cf069
lines 47–76why, one step back47@pytest.mark.parametrize(48 ("args", "word", "expect"),49 [50 ([], "", ["get"]),51 (["get"], "", ["full"]),52 (["get", "full"], "", ["data"]),53 (["get", "full"], "-", ["--verbose", "--help"]),54 (["get", "full", "data"], "", []),55 (["get", "full", "data"], "-", ["-a", "--help"]),56 ],57)58def test_nested_group(args: list[str], word: str, expect: list[str]) -> None:59 cli = Group(60 "cli",61 commands=[62 Group(63 "get",64 commands=[65 Group(66 "full",67 params=[Option(["--verbose"])],68 commands=[Command("data", params=[Option(["-a"])])],69 )70 ],71 )72 ],73 )74 assert _get_words(cli, args, word) == expect7576remove extraneous test envsDavid Lordbefore adoption7ac7e2a
lines 77–224why, one step back77def test_group_command_same_option():78 cli = Group(79 "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]80 )81 assert _get_words(cli, [], "-") == ["-a", "--help"]82 assert _get_words(cli, ["-a", "a"], "-") == ["--help"]83 assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]84 assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]858687def test_chained():88 cli = Group(89 "cli",90 chain=True,91 commands=[92 Command("set", params=[Option(["-y"])]),93 Command("start"),94 Group("get", commands=[Command("full")]),95 ],96 )97 assert _get_words(cli, [], "") == ["get", "set", "start"]98 assert _get_words(cli, [], "s") == ["set", "start"]99 assert _get_words(cli, ["set", "start"], "") == ["get"]100 # subcommands and parent subcommands101 assert _get_words(cli, ["get"], "") == ["full", "set", "start"]102 assert _get_words(cli, ["get", "full"], "") == ["set", "start"]103 assert _get_words(cli, ["get"], "s") == ["set", "start"]104105106def test_help_option():107 cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])108 assert _get_words(cli, ["with"], "--") == ["--help"]109 assert _get_words(cli, ["no"], "--") == []110111112def test_argument_order():113 cli = Command(114 "cli",115 params=[116 Argument(["plain"]),117 Argument(["c1"], type=Choice(["a1", "a2", "b"])),118 Argument(["c2"], type=Choice(["c1", "c2", "d"])),119 ],120 )121 # first argument has no completions122 assert _get_words(cli, [], "") == []123 assert _get_words(cli, [], "a") == []124 # first argument filled, now completion can happen125 assert _get_words(cli, ["x"], "a") == ["a1", "a2"]126 assert _get_words(cli, ["x", "b"], "d") == ["d"]127128129def test_argument_default():130 cli = Command(131 "cli",132 add_help_option=False,133 params=[134 Argument(["a"], type=Choice(["a"]), default="a"),135 Argument(["b"], type=Choice(["b"]), default="b"),136 ],137 )138 assert _get_words(cli, [], "") == ["a"]139 assert _get_words(cli, ["a"], "b") == ["b"]140 # ignore type validation141 assert _get_words(cli, ["x"], "b") == ["b"]142143144def test_type_choice():145 cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])146 assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]147 assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]148 assert _get_words(cli, ["-c"], "a2") == ["a2"]149150151def test_choice_special_characters():152 cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])153 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]154 assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]155 assert _get_words(cli, ["-c"], "!2") == ["!2"]156157158def test_choice_conflicting_prefix():159 cli = Command(160 "cli",161 params=[162 Option(["-c"], type=Choice(["!1", "!2", "+3"])),163 Option(["+p"], is_flag=True),164 ],165 )166 assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]167 assert _get_words(cli, ["-c"], "+") == ["+p"]168169170def test_option_count():171 cli = Command("cli", params=[Option(["-c"], count=True)])172 assert _get_words(cli, ["-c"], "") == []173 assert _get_words(cli, ["-c"], "-") == ["--help"]174175176def test_option_optional():177 cli = Command(178 "cli",179 add_help_option=False,180 params=[181 Option(["--name"], is_flag=False, flag_value="value"),182 Option(["--flag"], is_flag=True),183 ],184 )185 assert _get_words(cli, ["--name"], "") == []186 assert _get_words(cli, ["--name"], "-") == ["--flag"]187 assert _get_words(cli, ["--name", "--flag"], "-") == []188189190@pytest.mark.parametrize(191 ("type", "expect"),192 [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],193)194def test_path_types(type, expect):195 cli = Command("cli", params=[Option(["-f"], type=type)])196 out = _get_completions(cli, ["-f"], "ab")197 assert len(out) == 1198 c = out[0]199 assert c.value == "ab"200 assert c.type == expect201202203def test_absolute_path():204 cli = Command("cli", params=[Option(["-f"], type=Path())])205 out = _get_completions(cli, ["-f"], "/ab")206 assert len(out) == 1207 c = out[0]208 assert c.value == "/ab"209210211def test_option_flag():212 cli = Command(213 "cli",214 add_help_option=False,215 params=[216 Option(["--on/--off"]),217 Argument(["a"], type=Choice(["a1", "a2", "b"])),218 ],219 )220 assert _get_words(cli, [], "--") == ["--on", "--off"]221 # flag option doesn't take value, use choice argument222 assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]223224show correct auto complete value for nargs option in combination with flag option (#2816)Rowlando13before adoption4f936ac
lines 225–237why, one step back225def test_flag_option_with_nargs_option():226 cli = Command(227 "cli",228 add_help_option=False,229 params=[230 Argument(["a"], type=Choice(["a1", "a2", "b"])),231 Option(["--flag"], is_flag=True),232 Option(["-c"], type=Choice(["p", "q"]), nargs=2),233 ],234 )235 assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]236237remove extraneous test envsDavid Lordbefore adoption7ac7e2a
lines 238–361why, one step back238def test_option_custom():239 def custom(ctx, param, incomplete):240 return [incomplete.upper()]241242 cli = Command(243 "cli",244 params=[245 Argument(["x"]),246 Argument(["y"]),247 Argument(["z"], shell_complete=custom),248 ],249 )250 assert _get_words(cli, ["a", "b"], "") == [""]251 assert _get_words(cli, ["a", "b"], "c") == ["C"]252253254def test_option_multiple():255 cli = Command(256 "type",257 params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],258 )259 assert _get_words(cli, ["-m"], "") == ["a", "b"]260 assert "-m" in _get_words(cli, ["-m", "a"], "-")261 assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]262 # used single options aren't suggested again263 assert "-c" not in _get_words(cli, ["-c", "f"], "-")264265266def test_option_nargs():267 cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])268 assert _get_words(cli, ["-c"], "") == ["a", "b"]269 assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]270 assert _get_words(cli, ["-c", "a", "b"], "") == []271272273def test_argument_nargs():274 cli = Command(275 "cli",276 params=[277 Argument(["x"], type=Choice(["a", "b"]), nargs=2),278 Argument(["y"], type=Choice(["c", "d"]), nargs=-1),279 Option(["-z"]),280 ],281 )282 assert _get_words(cli, [], "") == ["a", "b"]283 assert _get_words(cli, ["a"], "") == ["a", "b"]284 assert _get_words(cli, ["a", "b"], "") == ["c", "d"]285 assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]286 assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]287 assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]288 assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]289290291def test_double_dash():292 cli = Command(293 "cli",294 add_help_option=False,295 params=[296 Option(["--opt"]),297 Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),298 ],299 )300 assert _get_words(cli, [], "-") == ["--opt"]301 assert _get_words(cli, ["value"], "-") == ["--opt"]302 assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]303 assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]304305306def test_hidden():307 cli = Group(308 "cli",309 commands=[310 Command(311 "hidden",312 add_help_option=False,313 hidden=True,314 params=[315 Option(["-a"]),316 Option(["-b"], type=Choice(["a", "b"]), hidden=True),317 ],318 )319 ],320 )321 assert "hidden" not in _get_words(cli, [], "")322 assert "hidden" not in _get_words(cli, [], "hidden")323 assert _get_words(cli, ["hidden"], "-") == ["-a"]324 assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]325326327def test_add_different_name():328 cli = Group("cli", commands={"renamed": Command("original")})329 words = _get_words(cli, [], "")330 assert "renamed" in words331 assert "original" not in words332333334def test_completion_item_data():335 c = CompletionItem("test", a=1)336 assert c.a == 1337 assert c.b is None338339340@pytest.fixture()341def _patch_for_completion(monkeypatch):342 monkeypatch.setattr(343 "click.shell_completion.BashComplete._check_version", lambda self: True344 )345346347@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])348@pytest.mark.usefixtures("_patch_for_completion")349def test_full_source(runner, shell):350 cli = Group("cli", commands=[Command("a"), Command("b")])351 result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})352 assert f"_CLI_COMPLETE={shell}_complete" in result.output353354355@pytest.mark.parametrize(356 ("shell", "env", "expect"),357 [358 ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),359 ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),360 ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),361 ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),Fix broken fish completion and multiline help stringSitiyoubefore adoptionb7e5fd4
lines 362–364why, one step back362 ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),363 ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),364 ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),remove extraneous test envsDavid Lordbefore adoption7ac7e2a
lines 365–371why, one step back365 ],366)367@pytest.mark.usefixtures("_patch_for_completion")368def test_full_complete(runner, shell, env, expect):369 cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])370 env["_CLI_COMPLETE"] = f"{shell}_complete"371 result = runner.invoke(cli, env=env)Fix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa
line 372why, one step back372 assert result.output == expectapply Unix line endings for shell completion output for windows compat (#3466)David Lordbefore adoptione0d1678
lines 373–386why, one step back373374375def test_source_uses_lf_line_endings(monkeypatch):376 stdout = io.BytesIO()377 stream = io.TextIOWrapper(stdout, encoding="utf-8", newline="\r\n")378 monkeypatch.setattr("click.utils._default_text_stdout", lambda: stream)379380 cli = Group("cli", commands=[Command("a"), Command("b")])381 assert shell_complete(cli, {}, "cli", "_CLI_COMPLETE", "zsh_source") == 0382383 stream.flush()384 output = stdout.getvalue()385 assert b"\r\n" not in output386 assert b"\n" in outputFix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa
lines 387–458why, one step back387388389@pytest.mark.parametrize(390 ("env", "expect"),391 [392 (393 {"COMP_WORDS": "", "COMP_CWORD": "0"},394 textwrap.dedent(395 """\396 plain397 a398 _399 plain400 b401 bee402 plain403 c\\:d404 cee:dee405 plain406 c:e407 _408 """409 ),410 ),411 (412 {"COMP_WORDS": "a c", "COMP_CWORD": "1"},413 textwrap.dedent(414 """\415 plain416 c\\:d417 cee:dee418 plain419 c:e420 _421 """422 ),423 ),424 (425 {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},426 textwrap.dedent(427 """\428 plain429 c\\:d430 cee:dee431 plain432 c:e433 _434 """435 ),436 ),437 ],438)439@pytest.mark.usefixtures("_patch_for_completion")440def test_zsh_full_complete_with_colons(441 runner, env: Mapping[str, str], expect: str442) -> None:443 cli = Group(444 "cli",445 commands=[446 Command("a"),447 Command("b", help="bee"),448 Command("c:d", help="cee:dee"),449 Command("c:e"),450 ],451 )452 result = runner.invoke(453 cli,454 env={455 **env,456 "_CLI_COMPLETE": "zsh_complete",457 },458 )remove extraneous test envsDavid Lordbefore adoption7ac7e2a
lines 459–475why, one step back459 assert result.output == expect460461462@pytest.mark.usefixtures("_patch_for_completion")463def test_context_settings(runner):464 def complete(ctx, param, incomplete):465 return ctx.obj["choices"]466467 cli = Command("cli", params=[Argument("x", shell_complete=complete)])468 result = runner.invoke(469 cli,470 obj={"choices": ["a", "b"]},471 env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},472 )473 assert result.output == "plain,a\nplain,b\n"474475shell autocomplete uses normalize_choice() (#3471)David Lordbefore adoption3c12ce7
lines 476–477why, one step back476# case_sensitive=False normalizes values to lowercase, matching remains case insensitive477@pytest.mark.parametrize(("value", "expect"), [(False, ["au", "al"]), (True, ["al"])])remove extraneous test envsDavid Lordbefore adoption7ac7e2a
lines 478–554why, one step back478def test_choice_case_sensitive(value, expect):479 cli = Command(480 "cli",481 params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],482 )483 completions = _get_words(cli, ["-a"], "a")484 assert completions == expect485486487@pytest.fixture()488def _restore_available_shells(tmpdir):489 prev_available_shells = click.shell_completion._available_shells.copy()490 click.shell_completion._available_shells.clear()491 yield492 click.shell_completion._available_shells.clear()493 click.shell_completion._available_shells.update(prev_available_shells)494495496@pytest.mark.usefixtures("_restore_available_shells")497def test_add_completion_class():498 # At first, "mysh" is not in available shells499 assert "mysh" not in click.shell_completion._available_shells500501 class MyshComplete(ShellComplete):502 name = "mysh"503 source_template = "dummy source"504505 # "mysh" still not in available shells because it is not registered506 assert "mysh" not in click.shell_completion._available_shells507508 # Adding a completion class should return that class509 assert add_completion_class(MyshComplete) is MyshComplete510511 # Now, "mysh" is finally in available shells512 assert "mysh" in click.shell_completion._available_shells513 assert click.shell_completion._available_shells["mysh"] is MyshComplete514515516@pytest.mark.usefixtures("_restore_available_shells")517def test_add_completion_class_with_name():518 # At first, "mysh" is not in available shells519 assert "mysh" not in click.shell_completion._available_shells520 assert "not_mysh" not in click.shell_completion._available_shells521522 class MyshComplete(ShellComplete):523 name = "not_mysh"524 source_template = "dummy source"525526 # "mysh" and "not_mysh" are still not in available shells because527 # it is not registered yet528 assert "mysh" not in click.shell_completion._available_shells529 assert "not_mysh" not in click.shell_completion._available_shells530531 # Adding a completion class should return that class.532 # Because we are using the "name" parameter, the name isn't taken533 # from the class.534 assert add_completion_class(MyshComplete, name="mysh") is MyshComplete535536 # Now, "mysh" is finally in available shells537 assert "mysh" in click.shell_completion._available_shells538 assert "not_mysh" not in click.shell_completion._available_shells539 assert click.shell_completion._available_shells["mysh"] is MyshComplete540541542@pytest.mark.usefixtures("_restore_available_shells")543def test_add_completion_class_decorator():544 # At first, "mysh" is not in available shells545 assert "mysh" not in click.shell_completion._available_shells546547 @add_completion_class548 class MyshComplete(ShellComplete):549 name = "mysh"550 source_template = "dummy source"551552 # Using `add_completion_class` as a decorator adds the new shell immediately553 assert "mysh" in click.shell_completion._available_shells554 assert click.shell_completion._available_shells["mysh"] is MyshCompleteClose contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd
lines 555–578why, one step back555556557# Don't make the ResourceWarning give an error558@pytest.mark.filterwarnings("default")559def test_files_closed(runner) -> None:560 with runner.isolated_filesystem():561 config_file = "foo.txt"562 with open(config_file, "w") as f:563 f.write("bar")564565 @click.group()566 @click.option(567 "--config-file",568 default=config_file,569 type=click.File(mode="r"),570 )571 @click.pass_context572 def cli(ctx, config_file):573 pass574575 with warnings.catch_warnings(record=True) as current_warnings:576 assert not current_warnings, "There should be no warnings to start"577 _get_completions(cli, args=[], incomplete="")578 assert not current_warnings, "There should be no warnings after either"