Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

561 lines · 17.5 KiB · Python

Last changed by

Fix completions for quoted/escaped parameters in Fish (#3013)Hans Lehnertbefore adoption701b313

History of this file

Take it

1import textwrap2import warnings3from collections.abc import Mapping45import pytest67import click.shell_completion8from click.core import Argument9from click.core import Command10from click.core import Group11from click.core import Option12from click.shell_completion import add_completion_class13from click.shell_completion import CompletionItem14from click.shell_completion import ShellComplete15from click.types import Choice16from click.types import File17from click.types import Path181920def _get_completions(cli, args, incomplete):21    comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")22    return comp.get_completions(args, incomplete)232425def _get_words(cli, args, incomplete):26    return [c.value for c in _get_completions(cli, args, incomplete)]272829def test_command():30    cli = Command("cli", params=[Option(["-t", "--test"])])31    assert _get_words(cli, [], "") == []32    assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]33    assert _get_words(cli, [], "--") == ["--test", "--help"]34    assert _get_words(cli, [], "--t") == ["--test"]35    # -t has been seen, so --test isn't suggested36    assert _get_words(cli, ["-t", "a"], "-") == ["--help"]373839def test_group():40    cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])41    assert _get_words(cli, [], "") == ["x", "y"]42    assert _get_words(cli, [], "-") == ["-a", "--help"]434445@pytest.mark.parametrize(46    ("args", "word", "expect"),47    [48        ([], "", ["get"]),49        (["get"], "", ["full"]),50        (["get", "full"], "", ["data"]),51        (["get", "full"], "-", ["--verbose", "--help"]),52        (["get", "full", "data"], "", []),53        (["get", "full", "data"], "-", ["-a", "--help"]),54    ],55)56def test_nested_group(args: list[str], word: str, expect: list[str]) -> None:57    cli = Group(58        "cli",59        commands=[60            Group(61                "get",62                commands=[63                    Group(64                        "full",65                        params=[Option(["--verbose"])],66                        commands=[Command("data", params=[Option(["-a"])])],67                    )68                ],69            )70        ],71    )72    assert _get_words(cli, args, word) == expect737475def test_group_command_same_option():76    cli = Group(77        "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]78    )79    assert _get_words(cli, [], "-") == ["-a", "--help"]80    assert _get_words(cli, ["-a", "a"], "-") == ["--help"]81    assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]82    assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]838485def test_chained():86    cli = Group(87        "cli",88        chain=True,89        commands=[90            Command("set", params=[Option(["-y"])]),91            Command("start"),92            Group("get", commands=[Command("full")]),93        ],94    )95    assert _get_words(cli, [], "") == ["get", "set", "start"]96    assert _get_words(cli, [], "s") == ["set", "start"]97    assert _get_words(cli, ["set", "start"], "") == ["get"]98    # subcommands and parent subcommands99    assert _get_words(cli, ["get"], "") == ["full", "set", "start"]100    assert _get_words(cli, ["get", "full"], "") == ["set", "start"]101    assert _get_words(cli, ["get"], "s") == ["set", "start"]102103104def test_help_option():105    cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])106    assert _get_words(cli, ["with"], "--") == ["--help"]107    assert _get_words(cli, ["no"], "--") == []108109110def test_argument_order():111    cli = Command(112        "cli",113        params=[114            Argument(["plain"]),115            Argument(["c1"], type=Choice(["a1", "a2", "b"])),116            Argument(["c2"], type=Choice(["c1", "c2", "d"])),117        ],118    )119    # first argument has no completions120    assert _get_words(cli, [], "") == []121    assert _get_words(cli, [], "a") == []122    # first argument filled, now completion can happen123    assert _get_words(cli, ["x"], "a") == ["a1", "a2"]124    assert _get_words(cli, ["x", "b"], "d") == ["d"]125126127def test_argument_default():128    cli = Command(129        "cli",130        add_help_option=False,131        params=[132            Argument(["a"], type=Choice(["a"]), default="a"),133            Argument(["b"], type=Choice(["b"]), default="b"),134        ],135    )136    assert _get_words(cli, [], "") == ["a"]137    assert _get_words(cli, ["a"], "b") == ["b"]138    # ignore type validation139    assert _get_words(cli, ["x"], "b") == ["b"]140141142def test_type_choice():143    cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])144    assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]145    assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]146    assert _get_words(cli, ["-c"], "a2") == ["a2"]147148149def test_choice_special_characters():150    cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])151    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]152    assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]153    assert _get_words(cli, ["-c"], "!2") == ["!2"]154155156def test_choice_conflicting_prefix():157    cli = Command(158        "cli",159        params=[160            Option(["-c"], type=Choice(["!1", "!2", "+3"])),161            Option(["+p"], is_flag=True),162        ],163    )164    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]165    assert _get_words(cli, ["-c"], "+") == ["+p"]166167168def test_option_count():169    cli = Command("cli", params=[Option(["-c"], count=True)])170    assert _get_words(cli, ["-c"], "") == []171    assert _get_words(cli, ["-c"], "-") == ["--help"]172173174def test_option_optional():175    cli = Command(176        "cli",177        add_help_option=False,178        params=[179            Option(["--name"], is_flag=False, flag_value="value"),180            Option(["--flag"], is_flag=True),181        ],182    )183    assert _get_words(cli, ["--name"], "") == []184    assert _get_words(cli, ["--name"], "-") == ["--flag"]185    assert _get_words(cli, ["--name", "--flag"], "-") == []186187188@pytest.mark.parametrize(189    ("type", "expect"),190    [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],191)192def test_path_types(type, expect):193    cli = Command("cli", params=[Option(["-f"], type=type)])194    out = _get_completions(cli, ["-f"], "ab")195    assert len(out) == 1196    c = out[0]197    assert c.value == "ab"198    assert c.type == expect199200201def test_absolute_path():202    cli = Command("cli", params=[Option(["-f"], type=Path())])203    out = _get_completions(cli, ["-f"], "/ab")204    assert len(out) == 1205    c = out[0]206    assert c.value == "/ab"207208209def test_option_flag():210    cli = Command(211        "cli",212        add_help_option=False,213        params=[214            Option(["--on/--off"]),215            Argument(["a"], type=Choice(["a1", "a2", "b"])),216        ],217    )218    assert _get_words(cli, [], "--") == ["--on", "--off"]219    # flag option doesn't take value, use choice argument220    assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]221222223def test_flag_option_with_nargs_option():224    cli = Command(225        "cli",226        add_help_option=False,227        params=[228            Argument(["a"], type=Choice(["a1", "a2", "b"])),229            Option(["--flag"], is_flag=True),230            Option(["-c"], type=Choice(["p", "q"]), nargs=2),231        ],232    )233    assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]234235236def test_option_custom():237    def custom(ctx, param, incomplete):238        return [incomplete.upper()]239240    cli = Command(241        "cli",242        params=[243            Argument(["x"]),244            Argument(["y"]),245            Argument(["z"], shell_complete=custom),246        ],247    )248    assert _get_words(cli, ["a", "b"], "") == [""]249    assert _get_words(cli, ["a", "b"], "c") == ["C"]250251252def test_option_multiple():253    cli = Command(254        "type",255        params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],256    )257    assert _get_words(cli, ["-m"], "") == ["a", "b"]258    assert "-m" in _get_words(cli, ["-m", "a"], "-")259    assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]260    # used single options aren't suggested again261    assert "-c" not in _get_words(cli, ["-c", "f"], "-")262263264def test_option_nargs():265    cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])266    assert _get_words(cli, ["-c"], "") == ["a", "b"]267    assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]268    assert _get_words(cli, ["-c", "a", "b"], "") == []269270271def test_argument_nargs():272    cli = Command(273        "cli",274        params=[275            Argument(["x"], type=Choice(["a", "b"]), nargs=2),276            Argument(["y"], type=Choice(["c", "d"]), nargs=-1),277            Option(["-z"]),278        ],279    )280    assert _get_words(cli, [], "") == ["a", "b"]281    assert _get_words(cli, ["a"], "") == ["a", "b"]282    assert _get_words(cli, ["a", "b"], "") == ["c", "d"]283    assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]284    assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]285    assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]286    assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]287288289def test_double_dash():290    cli = Command(291        "cli",292        add_help_option=False,293        params=[294            Option(["--opt"]),295            Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),296        ],297    )298    assert _get_words(cli, [], "-") == ["--opt"]299    assert _get_words(cli, ["value"], "-") == ["--opt"]300    assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]301    assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]302303304def test_hidden():305    cli = Group(306        "cli",307        commands=[308            Command(309                "hidden",310                add_help_option=False,311                hidden=True,312                params=[313                    Option(["-a"]),314                    Option(["-b"], type=Choice(["a", "b"]), hidden=True),315                ],316            )317        ],318    )319    assert "hidden" not in _get_words(cli, [], "")320    assert "hidden" not in _get_words(cli, [], "hidden")321    assert _get_words(cli, ["hidden"], "-") == ["-a"]322    assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]323324325def test_add_different_name():326    cli = Group("cli", commands={"renamed": Command("original")})327    words = _get_words(cli, [], "")328    assert "renamed" in words329    assert "original" not in words330331332def test_completion_item_data():333    c = CompletionItem("test", a=1)334    assert c.a == 1335    assert c.b is None336337338@pytest.fixture()339def _patch_for_completion(monkeypatch):340    monkeypatch.setattr(341        "click.shell_completion.BashComplete._check_version", lambda self: True342    )343344345@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])346@pytest.mark.usefixtures("_patch_for_completion")347def test_full_source(runner, shell):348    cli = Group("cli", commands=[Command("a"), Command("b")])349    result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})350    assert f"_CLI_COMPLETE={shell}_complete" in result.output351352353@pytest.mark.parametrize(354    ("shell", "env", "expect"),355    [356        ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),357        ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),358        ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),359        ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),360        ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),361        ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),362        ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),363    ],364)365@pytest.mark.usefixtures("_patch_for_completion")366def test_full_complete(runner, shell, env, expect):367    cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])368    env["_CLI_COMPLETE"] = f"{shell}_complete"369    result = runner.invoke(cli, env=env)370    assert result.output == expect371372373@pytest.mark.parametrize(374    ("env", "expect"),375    [376        (377            {"COMP_WORDS": "", "COMP_CWORD": "0"},378            textwrap.dedent(379                """\380                    plain381                    a382                    _383                    plain384                    b385                    bee386                    plain387                    c\\:d388                    cee:dee389                    plain390                    c:e391                    _392                """393            ),394        ),395        (396            {"COMP_WORDS": "a c", "COMP_CWORD": "1"},397            textwrap.dedent(398                """\399                    plain400                    c\\:d401                    cee:dee402                    plain403                    c:e404                    _405                """406            ),407        ),408        (409            {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},410            textwrap.dedent(411                """\412                    plain413                    c\\:d414                    cee:dee415                    plain416                    c:e417                    _418                """419            ),420        ),421    ],422)423@pytest.mark.usefixtures("_patch_for_completion")424def test_zsh_full_complete_with_colons(425    runner, env: Mapping[str, str], expect: str426) -> None:427    cli = Group(428        "cli",429        commands=[430            Command("a"),431            Command("b", help="bee"),432            Command("c:d", help="cee:dee"),433            Command("c:e"),434        ],435    )436    result = runner.invoke(437        cli,438        env={439            **env,440            "_CLI_COMPLETE": "zsh_complete",441        },442    )443    assert result.output == expect444445446@pytest.mark.usefixtures("_patch_for_completion")447def test_context_settings(runner):448    def complete(ctx, param, incomplete):449        return ctx.obj["choices"]450451    cli = Command("cli", params=[Argument("x", shell_complete=complete)])452    result = runner.invoke(453        cli,454        obj={"choices": ["a", "b"]},455        env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},456    )457    assert result.output == "plain,a\nplain,b\n"458459460@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])461def test_choice_case_sensitive(value, expect):462    cli = Command(463        "cli",464        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],465    )466    completions = _get_words(cli, ["-a"], "a")467    assert completions == expect468469470@pytest.fixture()471def _restore_available_shells(tmpdir):472    prev_available_shells = click.shell_completion._available_shells.copy()473    click.shell_completion._available_shells.clear()474    yield475    click.shell_completion._available_shells.clear()476    click.shell_completion._available_shells.update(prev_available_shells)477478479@pytest.mark.usefixtures("_restore_available_shells")480def test_add_completion_class():481    # At first, "mysh" is not in available shells482    assert "mysh" not in click.shell_completion._available_shells483484    class MyshComplete(ShellComplete):485        name = "mysh"486        source_template = "dummy source"487488    # "mysh" still not in available shells because it is not registered489    assert "mysh" not in click.shell_completion._available_shells490491    # Adding a completion class should return that class492    assert add_completion_class(MyshComplete) is MyshComplete493494    # Now, "mysh" is finally in available shells495    assert "mysh" in click.shell_completion._available_shells496    assert click.shell_completion._available_shells["mysh"] is MyshComplete497498499@pytest.mark.usefixtures("_restore_available_shells")500def test_add_completion_class_with_name():501    # At first, "mysh" is not in available shells502    assert "mysh" not in click.shell_completion._available_shells503    assert "not_mysh" not in click.shell_completion._available_shells504505    class MyshComplete(ShellComplete):506        name = "not_mysh"507        source_template = "dummy source"508509    # "mysh" and "not_mysh" are still not in available shells because510    # it is not registered yet511    assert "mysh" not in click.shell_completion._available_shells512    assert "not_mysh" not in click.shell_completion._available_shells513514    # Adding a completion class should return that class.515    # Because we are using the "name" parameter, the name isn't taken516    # from the class.517    assert add_completion_class(MyshComplete, name="mysh") is MyshComplete518519    # Now, "mysh" is finally in available shells520    assert "mysh" in click.shell_completion._available_shells521    assert "not_mysh" not in click.shell_completion._available_shells522    assert click.shell_completion._available_shells["mysh"] is MyshComplete523524525@pytest.mark.usefixtures("_restore_available_shells")526def test_add_completion_class_decorator():527    # At first, "mysh" is not in available shells528    assert "mysh" not in click.shell_completion._available_shells529530    @add_completion_class531    class MyshComplete(ShellComplete):532        name = "mysh"533        source_template = "dummy source"534535    # Using `add_completion_class` as a decorator adds the new shell immediately536    assert "mysh" in click.shell_completion._available_shells537    assert click.shell_completion._available_shells["mysh"] is MyshComplete538539540# Don't make the ResourceWarning give an error541@pytest.mark.filterwarnings("default")542def test_files_closed(runner) -> None:543    with runner.isolated_filesystem():544        config_file = "foo.txt"545        with open(config_file, "w") as f:546            f.write("bar")547548        @click.group()549        @click.option(550            "--config-file",551            default=config_file,552            type=click.File(mode="r"),553        )554        @click.pass_context555        def cli(ctx, config_file):556            pass557558        with warnings.catch_warnings(record=True) as current_warnings:559            assert not current_warnings, "There should be no warnings to start"560            _get_completions(cli, args=[], incomplete="")561            assert not current_warnings, "There should be no warnings after either"