Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

617 lines · 20.0 KiB · Python

Last changed by

Merge main into stable (#3800)Rowlando13before adoption420c8fb

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 PowerShellComplete17from click.shell_completion import shell_complete18from click.shell_completion import ShellComplete19from click.types import Choice20from click.types import File21from click.types import Path222324def _get_completions(cli, args, incomplete):25    comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")26    return comp.get_completions(args, incomplete)272829def _get_words(cli, args, incomplete):30    return [c.value for c in _get_completions(cli, args, incomplete)]313233def test_command():34    cli = Command("cli", params=[Option(["-t", "--test"])])35    assert _get_words(cli, [], "") == []36    assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]37    assert _get_words(cli, [], "--") == ["--test", "--help"]38    assert _get_words(cli, [], "--t") == ["--test"]39    # -t has been seen, so --test isn't suggested40    assert _get_words(cli, ["-t", "a"], "-") == ["--help"]414243def test_group():44    cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])45    assert _get_words(cli, [], "") == ["x", "y"]46    assert _get_words(cli, [], "-") == ["-a", "--help"]474849@pytest.mark.parametrize(50    ("args", "word", "expect"),51    [52        ([], "", ["get"]),53        (["get"], "", ["full"]),54        (["get", "full"], "", ["data"]),55        (["get", "full"], "-", ["--verbose", "--help"]),56        (["get", "full", "data"], "", []),57        (["get", "full", "data"], "-", ["-a", "--help"]),58    ],59)60def test_nested_group(args: list[str], word: str, expect: list[str]) -> None:61    cli = Group(62        "cli",63        commands=[64            Group(65                "get",66                commands=[67                    Group(68                        "full",69                        params=[Option(["--verbose"])],70                        commands=[Command("data", params=[Option(["-a"])])],71                    )72                ],73            )74        ],75    )76    assert _get_words(cli, args, word) == expect777879def test_group_command_same_option():80    cli = Group(81        "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]82    )83    assert _get_words(cli, [], "-") == ["-a", "--help"]84    assert _get_words(cli, ["-a", "a"], "-") == ["--help"]85    assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]86    assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]878889def test_chained():90    cli = Group(91        "cli",92        chain=True,93        commands=[94            Command("set", params=[Option(["-y"])]),95            Command("start"),96            Group("get", commands=[Command("full")]),97        ],98    )99    assert _get_words(cli, [], "") == ["get", "set", "start"]100    assert _get_words(cli, [], "s") == ["set", "start"]101    assert _get_words(cli, ["set", "start"], "") == ["get"]102    # subcommands and parent subcommands103    assert _get_words(cli, ["get"], "") == ["full", "set", "start"]104    assert _get_words(cli, ["get", "full"], "") == ["set", "start"]105    assert _get_words(cli, ["get"], "s") == ["set", "start"]106107108def test_help_option():109    cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])110    assert _get_words(cli, ["with"], "--") == ["--help"]111    assert _get_words(cli, ["no"], "--") == []112113114def test_argument_order():115    cli = Command(116        "cli",117        params=[118            Argument(["plain"]),119            Argument(["c1"], type=Choice(["a1", "a2", "b"])),120            Argument(["c2"], type=Choice(["c1", "c2", "d"])),121        ],122    )123    # first argument has no completions124    assert _get_words(cli, [], "") == []125    assert _get_words(cli, [], "a") == []126    # first argument filled, now completion can happen127    assert _get_words(cli, ["x"], "a") == ["a1", "a2"]128    assert _get_words(cli, ["x", "b"], "d") == ["d"]129130131def test_argument_default():132    cli = Command(133        "cli",134        add_help_option=False,135        params=[136            Argument(["a"], type=Choice(["a"]), default="a"),137            Argument(["b"], type=Choice(["b"]), default="b"),138        ],139    )140    assert _get_words(cli, [], "") == ["a"]141    assert _get_words(cli, ["a"], "b") == ["b"]142    # ignore type validation143    assert _get_words(cli, ["x"], "b") == ["b"]144145146def test_type_choice():147    cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])148    assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]149    assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]150    assert _get_words(cli, ["-c"], "a2") == ["a2"]151152153def test_choice_special_characters():154    cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])155    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]156    assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]157    assert _get_words(cli, ["-c"], "!2") == ["!2"]158159160def test_choice_conflicting_prefix():161    cli = Command(162        "cli",163        params=[164            Option(["-c"], type=Choice(["!1", "!2", "+3"])),165            Option(["+p"], is_flag=True),166        ],167    )168    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]169    assert _get_words(cli, ["-c"], "+") == ["+p"]170171172def test_option_count():173    cli = Command("cli", params=[Option(["-c"], count=True)])174    assert _get_words(cli, ["-c"], "") == []175    assert _get_words(cli, ["-c"], "-") == ["--help"]176177178def test_option_optional():179    cli = Command(180        "cli",181        add_help_option=False,182        params=[183            Option(["--name"], is_flag=False, flag_value="value"),184            Option(["--flag"], is_flag=True),185        ],186    )187    assert _get_words(cli, ["--name"], "") == []188    assert _get_words(cli, ["--name"], "-") == ["--flag"]189    assert _get_words(cli, ["--name", "--flag"], "-") == []190191192@pytest.mark.parametrize(193    ("type", "expect"),194    [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],195)196def test_path_types(type, expect):197    cli = Command("cli", params=[Option(["-f"], type=type)])198    out = _get_completions(cli, ["-f"], "ab")199    assert len(out) == 1200    c = out[0]201    assert c.value == "ab"202    assert c.type == expect203204205def test_absolute_path():206    cli = Command("cli", params=[Option(["-f"], type=Path())])207    out = _get_completions(cli, ["-f"], "/ab")208    assert len(out) == 1209    c = out[0]210    assert c.value == "/ab"211212213def test_option_flag():214    cli = Command(215        "cli",216        add_help_option=False,217        params=[218            Option(["--on/--off"]),219            Argument(["a"], type=Choice(["a1", "a2", "b"])),220        ],221    )222    assert _get_words(cli, [], "--") == ["--on", "--off"]223    # flag option doesn't take value, use choice argument224    assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]225226227def test_flag_option_with_nargs_option():228    cli = Command(229        "cli",230        add_help_option=False,231        params=[232            Argument(["a"], type=Choice(["a1", "a2", "b"])),233            Option(["--flag"], is_flag=True),234            Option(["-c"], type=Choice(["p", "q"]), nargs=2),235        ],236    )237    assert _get_words(cli, ["a1", "--flag", "-c"], "") == ["p", "q"]238239240def test_option_custom():241    def custom(ctx, param, incomplete):242        return [incomplete.upper()]243244    cli = Command(245        "cli",246        params=[247            Argument(["x"]),248            Argument(["y"]),249            Argument(["z"], shell_complete=custom),250        ],251    )252    assert _get_words(cli, ["a", "b"], "") == [""]253    assert _get_words(cli, ["a", "b"], "c") == ["C"]254255256def test_option_multiple():257    cli = Command(258        "type",259        params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],260    )261    assert _get_words(cli, ["-m"], "") == ["a", "b"]262    assert "-m" in _get_words(cli, ["-m", "a"], "-")263    assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]264    # used single options aren't suggested again265    assert "-c" not in _get_words(cli, ["-c", "f"], "-")266267268def test_option_nargs():269    cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])270    assert _get_words(cli, ["-c"], "") == ["a", "b"]271    assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]272    assert _get_words(cli, ["-c", "a", "b"], "") == []273274275def test_argument_nargs():276    cli = Command(277        "cli",278        params=[279            Argument(["x"], type=Choice(["a", "b"]), nargs=2),280            Argument(["y"], type=Choice(["c", "d"]), nargs=-1),281            Option(["-z"]),282        ],283    )284    assert _get_words(cli, [], "") == ["a", "b"]285    assert _get_words(cli, ["a"], "") == ["a", "b"]286    assert _get_words(cli, ["a", "b"], "") == ["c", "d"]287    assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]288    assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]289    assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]290    assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]291292293def test_double_dash():294    cli = Command(295        "cli",296        add_help_option=False,297        params=[298            Option(["--opt"]),299            Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),300        ],301    )302    assert _get_words(cli, [], "-") == ["--opt"]303    assert _get_words(cli, ["value"], "-") == ["--opt"]304    assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]305    assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]306307308def test_hidden():309    cli = Group(310        "cli",311        commands=[312            Command(313                "hidden",314                add_help_option=False,315                hidden=True,316                params=[317                    Option(["-a"]),318                    Option(["-b"], type=Choice(["a", "b"]), hidden=True),319                ],320            )321        ],322    )323    assert "hidden" not in _get_words(cli, [], "")324    assert "hidden" not in _get_words(cli, [], "hidden")325    assert _get_words(cli, ["hidden"], "-") == ["-a"]326    assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]327328329def test_add_different_name():330    cli = Group("cli", commands={"renamed": Command("original")})331    words = _get_words(cli, [], "")332    assert "renamed" in words333    assert "original" not in words334335336def test_completion_item_data():337    c = CompletionItem("test", a=1)338    assert c.a == 1339    assert c.b is None340341342@pytest.fixture()343def _patch_for_completion(monkeypatch):344    monkeypatch.setattr(345        "click.shell_completion.BashComplete._check_version", lambda self: True346    )347348349@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])350@pytest.mark.usefixtures("_patch_for_completion")351def test_full_source(runner, shell):352    cli = Group("cli", commands=[Command("a"), Command("b")])353    result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})354    assert f"_CLI_COMPLETE={shell}_complete" in result.output355356357def test_full_source_powershell(runner):358    # The PowerShell source script sets the completion env var via359    # `$env:_CLI_COMPLETE = 'powershell_complete'`, so the substring360    # `_CLI_COMPLETE=powershell_complete` used by test_full_source above361    # is not present. Assert on the PowerShell-specific markers instead.362    cli = Group("cli", commands=[Command("a"), Command("b")])363    result = runner.invoke(cli, env={"_CLI_COMPLETE": "powershell_source"})364    assert "Register-ArgumentCompleter" in result.output365    assert "powershell_complete" in result.output366367368@pytest.mark.parametrize(369    ("shell", "env", "expect"),370    [371        ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),372        ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),373        ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),374        ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),375        ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),376        ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),377        ("fish", {"COMP_WORDS": 'a "b', "COMP_CWORD": '"b'}, "plain,b\tbee\n"),378        (379            "powershell",380            {"COMP_WORDS": "", "COMP_CWORD": "0"},381            "plain\na\n_\nplain\nb\nbee\n",382        ),383        ("powershell", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),384    ],385)386@pytest.mark.usefixtures("_patch_for_completion")387def test_full_complete(runner, shell, env, expect):388    cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])389    env["_CLI_COMPLETE"] = f"{shell}_complete"390    result = runner.invoke(cli, env=env)391    assert result.output == expect392393394def test_source_uses_lf_line_endings(monkeypatch):395    stdout = io.BytesIO()396    stream = io.TextIOWrapper(stdout, encoding="utf-8", newline="\r\n")397    monkeypatch.setattr("click.utils._default_text_stdout", lambda: stream)398399    cli = Group("cli", commands=[Command("a"), Command("b")])400    assert shell_complete(cli, {}, "cli", "_CLI_COMPLETE", "zsh_source") == 0401402    stream.flush()403    output = stdout.getvalue()404    assert b"\r\n" not in output405    assert b"\n" in output406407408@pytest.mark.parametrize(409    ("env", "expect"),410    [411        (412            {"COMP_WORDS": "", "COMP_CWORD": "0"},413            textwrap.dedent(414                """\415                    plain416                    a417                    _418                    plain419                    b420                    bee421                    plain422                    c\\:d423                    cee:dee424                    plain425                    c:e426                    _427                """428            ),429        ),430        (431            {"COMP_WORDS": "a c", "COMP_CWORD": "1"},432            textwrap.dedent(433                """\434                    plain435                    c\\:d436                    cee:dee437                    plain438                    c:e439                    _440                """441            ),442        ),443        (444            {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},445            textwrap.dedent(446                """\447                    plain448                    c\\:d449                    cee:dee450                    plain451                    c:e452                    _453                """454            ),455        ),456    ],457)458@pytest.mark.usefixtures("_patch_for_completion")459def test_zsh_full_complete_with_colons(460    runner, env: Mapping[str, str], expect: str461) -> None:462    cli = Group(463        "cli",464        commands=[465            Command("a"),466            Command("b", help="bee"),467            Command("c:d", help="cee:dee"),468            Command("c:e"),469        ],470    )471    result = runner.invoke(472        cli,473        env={474            **env,475            "_CLI_COMPLETE": "zsh_complete",476        },477    )478    assert result.output == expect479480481@pytest.mark.usefixtures("_patch_for_completion")482def test_context_settings(runner):483    def complete(ctx, param, incomplete):484        return ctx.obj["choices"]485486    cli = Command("cli", params=[Argument("x", shell_complete=complete)])487    result = runner.invoke(488        cli,489        obj={"choices": ["a", "b"]},490        env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},491    )492    assert result.output == "plain,a\nplain,b\n"493494495# case_sensitive=False normalizes values to lowercase, matching remains case insensitive496@pytest.mark.parametrize(("value", "expect"), [(False, ["au", "al"]), (True, ["al"])])497def test_choice_case_sensitive(value, expect):498    cli = Command(499        "cli",500        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],501    )502    completions = _get_words(cli, ["-a"], "a")503    assert completions == expect504505506@pytest.fixture()507def _restore_available_shells(tmpdir):508    prev_available_shells = click.shell_completion._available_shells.copy()509    click.shell_completion._available_shells.clear()510    yield511    click.shell_completion._available_shells.clear()512    click.shell_completion._available_shells.update(prev_available_shells)513514515@pytest.mark.usefixtures("_restore_available_shells")516def test_add_completion_class():517    # At first, "mysh" is not in available shells518    assert "mysh" not in click.shell_completion._available_shells519520    class MyshComplete(ShellComplete):521        name = "mysh"522        source_template = "dummy source"523524    # "mysh" still not in available shells because it is not registered525    assert "mysh" not in click.shell_completion._available_shells526527    # Adding a completion class should return that class528    assert add_completion_class(MyshComplete) is MyshComplete529530    # Now, "mysh" is finally in available shells531    assert "mysh" in click.shell_completion._available_shells532    assert click.shell_completion._available_shells["mysh"] is MyshComplete533534535@pytest.mark.usefixtures("_restore_available_shells")536def test_add_completion_class_with_name():537    # At first, "mysh" is not in available shells538    assert "mysh" not in click.shell_completion._available_shells539    assert "not_mysh" not in click.shell_completion._available_shells540541    class MyshComplete(ShellComplete):542        name = "not_mysh"543        source_template = "dummy source"544545    # "mysh" and "not_mysh" are still not in available shells because546    # it is not registered yet547    assert "mysh" not in click.shell_completion._available_shells548    assert "not_mysh" not in click.shell_completion._available_shells549550    # Adding a completion class should return that class.551    # Because we are using the "name" parameter, the name isn't taken552    # from the class.553    assert add_completion_class(MyshComplete, name="mysh") is MyshComplete554555    # Now, "mysh" is finally in available shells556    assert "mysh" in click.shell_completion._available_shells557    assert "not_mysh" not in click.shell_completion._available_shells558    assert click.shell_completion._available_shells["mysh"] is MyshComplete559560561@pytest.mark.usefixtures("_restore_available_shells")562def test_add_completion_class_decorator():563    # At first, "mysh" is not in available shells564    assert "mysh" not in click.shell_completion._available_shells565566    @add_completion_class567    class MyshComplete(ShellComplete):568        name = "mysh"569        source_template = "dummy source"570571    # Using `add_completion_class` as a decorator adds the new shell immediately572    assert "mysh" in click.shell_completion._available_shells573    assert click.shell_completion._available_shells["mysh"] is MyshComplete574575576# Don't make the ResourceWarning give an error577@pytest.mark.filterwarnings("default::ResourceWarning")578def test_files_closed(tmp_path) -> None:579    config_file = str(tmp_path / "foo.txt")580    with open(config_file, "w") as f:581        f.write("bar")582583    @click.group()584    @click.option(585        "--config-file",586        default=config_file,587        type=click.File(mode="r"),588    )589    @click.pass_context590    def cli(ctx, config_file):591        pass592593    with warnings.catch_warnings(record=True) as current_warnings:594        assert not current_warnings, "There should be no warnings to start"595        _get_completions(cli, args=[], incomplete="")596        assert not current_warnings, "There should be no warnings after either"597598599def test_fish_format_completion_escapes_help():600    fc = FishComplete(Command("x"), {}, "x", "_X_COMPLETE")601    item = CompletionItem("--at", help="first\nsecond\tthird")602    # The newline is escaped to the literal characters backslash-n and the tab603    # becomes a space, so each completion stays on one line for fish.604    assert fc.format_completion(item) == "plain,--at\tfirst\\nsecond third"605606607def test_powershell_format_completion_escapes_help():608    pc = PowerShellComplete(Command("x"), {}, "x", "_X_COMPLETE")609    # Newlines (LF and CRLF) collapse to spaces so the help text stays610    # on a single line and doesn't break the 3-lines-per-item framing611    # consumed by the PowerShell completion script.612    item = CompletionItem("--at", help="first\nsecond\r\nthird")613    assert pc.format_completion(item) == "plain\n--at\nfirst second  third"614    # Items without help text use the "_" sentinel, matching the format615    # produced by ZshComplete.616    item = CompletionItem("--at")617    assert pc.format_completion(item) == "plain\n--at\n_"