Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

587 lines · 18.6 KiB · Python

Last changed by

Backport #3504 from `main` to `stable` branch (#3508)Kevin Deldyckebefore adoption648d7c4

History of this file

Take it

1import io2import textwrap3import warnings4from collections.abc import Mapping56import 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 CompletionItem15from click.shell_completion import FishComplete16from click.shell_completion import shell_complete17from click.shell_completion import ShellComplete18from click.types import Choice19from click.types import File20from click.types import Path212223def _get_completions(cli, args, incomplete):24    comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")25    return comp.get_completions(args, incomplete)262728def _get_words(cli, args, incomplete):29    return [c.value for c in _get_completions(cli, args, incomplete)]303132def test_command():33    cli = Command("cli", params=[Option(["-t", "--test"])])34    assert _get_words(cli, [], "") == []35    assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]36    assert _get_words(cli, [], "--") == ["--test", "--help"]37    assert _get_words(cli, [], "--t") == ["--test"]38    # -t has been seen, so --test isn't suggested39    assert _get_words(cli, ["-t", "a"], "-") == ["--help"]404142def test_group():43    cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])44    assert _get_words(cli, [], "") == ["x", "y"]45    assert _get_words(cli, [], "-") == ["-a", "--help"]464748@pytest.mark.parametrize(49    ("args", "word", "expect"),50    [51        ([], "", ["get"]),52        (["get"], "", ["full"]),53        (["get", "full"], "", ["data"]),54        (["get", "full"], "-", ["--verbose", "--help"]),55        (["get", "full", "data"], "", []),56        (["get", "full", "data"], "-", ["-a", "--help"]),57    ],58)59def test_nested_group(args: list[str], word: str, expect: list[str]) -> None:60    cli = Group(61        "cli",62        commands=[63            Group(64                "get",65                commands=[66                    Group(67                        "full",68                        params=[Option(["--verbose"])],69                        commands=[Command("data", params=[Option(["-a"])])],70                    )71                ],72            )73        ],74    )75    assert _get_words(cli, args, word) == expect767778def test_group_command_same_option():79    cli = Group(80        "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]81    )82    assert _get_words(cli, [], "-") == ["-a", "--help"]83    assert _get_words(cli, ["-a", "a"], "-") == ["--help"]84    assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]85    assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]868788def test_chained():89    cli = Group(90        "cli",91        chain=True,92        commands=[93            Command("set", params=[Option(["-y"])]),94            Command("start"),95            Group("get", commands=[Command("full")]),96        ],97    )98    assert _get_words(cli, [], "") == ["get", "set", "start"]99    assert _get_words(cli, [], "s") == ["set", "start"]100    assert _get_words(cli, ["set", "start"], "") == ["get"]101    # subcommands and parent subcommands102    assert _get_words(cli, ["get"], "") == ["full", "set", "start"]103    assert _get_words(cli, ["get", "full"], "") == ["set", "start"]104    assert _get_words(cli, ["get"], "s") == ["set", "start"]105106107def test_help_option():108    cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])109    assert _get_words(cli, ["with"], "--") == ["--help"]110    assert _get_words(cli, ["no"], "--") == []111112113def test_argument_order():114    cli = Command(115        "cli",116        params=[117            Argument(["plain"]),118            Argument(["c1"], type=Choice(["a1", "a2", "b"])),119            Argument(["c2"], type=Choice(["c1", "c2", "d"])),120        ],121    )122    # first argument has no completions123    assert _get_words(cli, [], "") == []124    assert _get_words(cli, [], "a") == []125    # first argument filled, now completion can happen126    assert _get_words(cli, ["x"], "a") == ["a1", "a2"]127    assert _get_words(cli, ["x", "b"], "d") == ["d"]128129130def test_argument_default():131    cli = Command(132        "cli",133        add_help_option=False,134        params=[135            Argument(["a"], type=Choice(["a"]), default="a"),136            Argument(["b"], type=Choice(["b"]), default="b"),137        ],138    )139    assert _get_words(cli, [], "") == ["a"]140    assert _get_words(cli, ["a"], "b") == ["b"]141    # ignore type validation142    assert _get_words(cli, ["x"], "b") == ["b"]143144145def test_type_choice():146    cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])147    assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]148    assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]149    assert _get_words(cli, ["-c"], "a2") == ["a2"]150151152def test_choice_special_characters():153    cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])154    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]155    assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]156    assert _get_words(cli, ["-c"], "!2") == ["!2"]157158159def test_choice_conflicting_prefix():160    cli = Command(161        "cli",162        params=[163            Option(["-c"], type=Choice(["!1", "!2", "+3"])),164            Option(["+p"], is_flag=True),165        ],166    )167    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]168    assert _get_words(cli, ["-c"], "+") == ["+p"]169170171def test_option_count():172    cli = Command("cli", params=[Option(["-c"], count=True)])173    assert _get_words(cli, ["-c"], "") == []174    assert _get_words(cli, ["-c"], "-") == ["--help"]175176177def test_option_optional():178    cli = Command(179        "cli",180        add_help_option=False,181        params=[182            Option(["--name"], is_flag=False, flag_value="value"),183            Option(["--flag"], is_flag=True),184        ],185    )186    assert _get_words(cli, ["--name"], "") == []187    assert _get_words(cli, ["--name"], "-") == ["--flag"]188    assert _get_words(cli, ["--name", "--flag"], "-") == []189190191@pytest.mark.parametrize(192    ("type", "expect"),193    [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],194)195def test_path_types(type, expect):196    cli = Command("cli", params=[Option(["-f"], type=type)])197    out = _get_completions(cli, ["-f"], "ab")198    assert len(out) == 1199    c = out[0]200    assert c.value == "ab"201    assert c.type == expect202203204def test_absolute_path():205    cli = Command("cli", params=[Option(["-f"], type=Path())])206    out = _get_completions(cli, ["-f"], "/ab")207    assert len(out) == 1208    c = out[0]209    assert c.value == "/ab"210211212def test_option_flag():213    cli = Command(214        "cli",215        add_help_option=False,216        params=[217            Option(["--on/--off"]),218            Argument(["a"], type=Choice(["a1", "a2", "b"])),219        ],220    )221    assert _get_words(cli, [], "--") == ["--on", "--off"]222    # flag option doesn't take value, use choice argument223    assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]224225226def test_flag_option_with_nargs_option():227    cli = Command(228        "cli",229        add_help_option=False,230        params=[231            Argument(["a"], type=Choice(["a1", "a2", "b"])),232            Option(["--flag"], is_flag=True),233            Option(["-c"], type=Choice(["p", "q"]), nargs=2),234        ],235    )236    assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]237238239def test_option_custom():240    def custom(ctx, param, incomplete):241        return [incomplete.upper()]242243    cli = Command(244        "cli",245        params=[246            Argument(["x"]),247            Argument(["y"]),248            Argument(["z"], shell_complete=custom),249        ],250    )251    assert _get_words(cli, ["a", "b"], "") == [""]252    assert _get_words(cli, ["a", "b"], "c") == ["C"]253254255def test_option_multiple():256    cli = Command(257        "type",258        params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],259    )260    assert _get_words(cli, ["-m"], "") == ["a", "b"]261    assert "-m" in _get_words(cli, ["-m", "a"], "-")262    assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]263    # used single options aren't suggested again264    assert "-c" not in _get_words(cli, ["-c", "f"], "-")265266267def test_option_nargs():268    cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])269    assert _get_words(cli, ["-c"], "") == ["a", "b"]270    assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]271    assert _get_words(cli, ["-c", "a", "b"], "") == []272273274def test_argument_nargs():275    cli = Command(276        "cli",277        params=[278            Argument(["x"], type=Choice(["a", "b"]), nargs=2),279            Argument(["y"], type=Choice(["c", "d"]), nargs=-1),280            Option(["-z"]),281        ],282    )283    assert _get_words(cli, [], "") == ["a", "b"]284    assert _get_words(cli, ["a"], "") == ["a", "b"]285    assert _get_words(cli, ["a", "b"], "") == ["c", "d"]286    assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]287    assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]288    assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]289    assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]290291292def test_double_dash():293    cli = Command(294        "cli",295        add_help_option=False,296        params=[297            Option(["--opt"]),298            Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),299        ],300    )301    assert _get_words(cli, [], "-") == ["--opt"]302    assert _get_words(cli, ["value"], "-") == ["--opt"]303    assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]304    assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]305306307def test_hidden():308    cli = Group(309        "cli",310        commands=[311            Command(312                "hidden",313                add_help_option=False,314                hidden=True,315                params=[316                    Option(["-a"]),317                    Option(["-b"], type=Choice(["a", "b"]), hidden=True),318                ],319            )320        ],321    )322    assert "hidden" not in _get_words(cli, [], "")323    assert "hidden" not in _get_words(cli, [], "hidden")324    assert _get_words(cli, ["hidden"], "-") == ["-a"]325    assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]326327328def test_add_different_name():329    cli = Group("cli", commands={"renamed": Command("original")})330    words = _get_words(cli, [], "")331    assert "renamed" in words332    assert "original" not in words333334335def test_completion_item_data():336    c = CompletionItem("test", a=1)337    assert c.a == 1338    assert c.b is None339340341@pytest.fixture()342def _patch_for_completion(monkeypatch):343    monkeypatch.setattr(344        "click.shell_completion.BashComplete._check_version", lambda self: True345    )346347348@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])349@pytest.mark.usefixtures("_patch_for_completion")350def test_full_source(runner, shell):351    cli = Group("cli", commands=[Command("a"), Command("b")])352    result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})353    assert f"_CLI_COMPLETE={shell}_complete" in result.output354355356@pytest.mark.parametrize(357    ("shell", "env", "expect"),358    [359        ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),360        ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),361        ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),362        ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),363        ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),364        ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),365        ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),366    ],367)368@pytest.mark.usefixtures("_patch_for_completion")369def test_full_complete(runner, shell, env, expect):370    cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])371    env["_CLI_COMPLETE"] = f"{shell}_complete"372    result = runner.invoke(cli, env=env)373    assert result.output == expect374375376def test_source_uses_lf_line_endings(monkeypatch):377    stdout = io.BytesIO()378    stream = io.TextIOWrapper(stdout, encoding="utf-8", newline="\r\n")379    monkeypatch.setattr("click.utils._default_text_stdout", lambda: stream)380381    cli = Group("cli", commands=[Command("a"), Command("b")])382    assert shell_complete(cli, {}, "cli", "_CLI_COMPLETE", "zsh_source") == 0383384    stream.flush()385    output = stdout.getvalue()386    assert b"\r\n" not in output387    assert b"\n" in output388389390@pytest.mark.parametrize(391    ("env", "expect"),392    [393        (394            {"COMP_WORDS": "", "COMP_CWORD": "0"},395            textwrap.dedent(396                """\397                    plain398                    a399                    _400                    plain401                    b402                    bee403                    plain404                    c\\:d405                    cee:dee406                    plain407                    c:e408                    _409                """410            ),411        ),412        (413            {"COMP_WORDS": "a c", "COMP_CWORD": "1"},414            textwrap.dedent(415                """\416                    plain417                    c\\:d418                    cee:dee419                    plain420                    c:e421                    _422                """423            ),424        ),425        (426            {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},427            textwrap.dedent(428                """\429                    plain430                    c\\:d431                    cee:dee432                    plain433                    c:e434                    _435                """436            ),437        ),438    ],439)440@pytest.mark.usefixtures("_patch_for_completion")441def test_zsh_full_complete_with_colons(442    runner, env: Mapping[str, str], expect: str443) -> None:444    cli = Group(445        "cli",446        commands=[447            Command("a"),448            Command("b", help="bee"),449            Command("c:d", help="cee:dee"),450            Command("c:e"),451        ],452    )453    result = runner.invoke(454        cli,455        env={456            **env,457            "_CLI_COMPLETE": "zsh_complete",458        },459    )460    assert result.output == expect461462463@pytest.mark.usefixtures("_patch_for_completion")464def test_context_settings(runner):465    def complete(ctx, param, incomplete):466        return ctx.obj["choices"]467468    cli = Command("cli", params=[Argument("x", shell_complete=complete)])469    result = runner.invoke(470        cli,471        obj={"choices": ["a", "b"]},472        env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},473    )474    assert result.output == "plain,a\nplain,b\n"475476477# case_sensitive=False normalizes values to lowercase, matching remains case insensitive478@pytest.mark.parametrize(("value", "expect"), [(False, ["au", "al"]), (True, ["al"])])479def test_choice_case_sensitive(value, expect):480    cli = Command(481        "cli",482        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],483    )484    completions = _get_words(cli, ["-a"], "a")485    assert completions == expect486487488@pytest.fixture()489def _restore_available_shells(tmpdir):490    prev_available_shells = click.shell_completion._available_shells.copy()491    click.shell_completion._available_shells.clear()492    yield493    click.shell_completion._available_shells.clear()494    click.shell_completion._available_shells.update(prev_available_shells)495496497@pytest.mark.usefixtures("_restore_available_shells")498def test_add_completion_class():499    # At first, "mysh" is not in available shells500    assert "mysh" not in click.shell_completion._available_shells501502    class MyshComplete(ShellComplete):503        name = "mysh"504        source_template = "dummy source"505506    # "mysh" still not in available shells because it is not registered507    assert "mysh" not in click.shell_completion._available_shells508509    # Adding a completion class should return that class510    assert add_completion_class(MyshComplete) is MyshComplete511512    # Now, "mysh" is finally in available shells513    assert "mysh" in click.shell_completion._available_shells514    assert click.shell_completion._available_shells["mysh"] is MyshComplete515516517@pytest.mark.usefixtures("_restore_available_shells")518def test_add_completion_class_with_name():519    # At first, "mysh" is not in available shells520    assert "mysh" not in click.shell_completion._available_shells521    assert "not_mysh" not in click.shell_completion._available_shells522523    class MyshComplete(ShellComplete):524        name = "not_mysh"525        source_template = "dummy source"526527    # "mysh" and "not_mysh" are still not in available shells because528    # it is not registered yet529    assert "mysh" not in click.shell_completion._available_shells530    assert "not_mysh" not in click.shell_completion._available_shells531532    # Adding a completion class should return that class.533    # Because we are using the "name" parameter, the name isn't taken534    # from the class.535    assert add_completion_class(MyshComplete, name="mysh") is MyshComplete536537    # Now, "mysh" is finally in available shells538    assert "mysh" in click.shell_completion._available_shells539    assert "not_mysh" not in click.shell_completion._available_shells540    assert click.shell_completion._available_shells["mysh"] is MyshComplete541542543@pytest.mark.usefixtures("_restore_available_shells")544def test_add_completion_class_decorator():545    # At first, "mysh" is not in available shells546    assert "mysh" not in click.shell_completion._available_shells547548    @add_completion_class549    class MyshComplete(ShellComplete):550        name = "mysh"551        source_template = "dummy source"552553    # Using `add_completion_class` as a decorator adds the new shell immediately554    assert "mysh" in click.shell_completion._available_shells555    assert click.shell_completion._available_shells["mysh"] is MyshComplete556557558# Don't make the ResourceWarning give an error559@pytest.mark.filterwarnings("default")560def test_files_closed(runner) -> None:561    with runner.isolated_filesystem():562        config_file = "foo.txt"563        with open(config_file, "w") as f:564            f.write("bar")565566        @click.group()567        @click.option(568            "--config-file",569            default=config_file,570            type=click.File(mode="r"),571        )572        @click.pass_context573        def cli(ctx, config_file):574            pass575576        with warnings.catch_warnings(record=True) as current_warnings:577            assert not current_warnings, "There should be no warnings to start"578            _get_completions(cli, args=[], incomplete="")579            assert not current_warnings, "There should be no warnings after either"580581582def test_fish_format_completion_escapes_help():583    fc = FishComplete(Command("x"), {}, "x", "_X_COMPLETE")584    item = CompletionItem("--at", help="first\nsecond\tthird")585    # The newline is escaped to the literal characters backslash-n and the tab586    # becomes a space, so each completion stays on one line for fish.587    assert fc.format_completion(item) == "plain,--at\tfirst\\nsecond third"