Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

547 lines · 17.1 KiB · Python

Last changed by

Fix Zsh completions with colons (#2846)Marco Riccibefore adoptiona1235aa

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_option_custom():224    def custom(ctx, param, incomplete):225        return [incomplete.upper()]226227    cli = Command(228        "cli",229        params=[230            Argument(["x"]),231            Argument(["y"]),232            Argument(["z"], shell_complete=custom),233        ],234    )235    assert _get_words(cli, ["a", "b"], "") == [""]236    assert _get_words(cli, ["a", "b"], "c") == ["C"]237238239def test_option_multiple():240    cli = Command(241        "type",242        params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],243    )244    assert _get_words(cli, ["-m"], "") == ["a", "b"]245    assert "-m" in _get_words(cli, ["-m", "a"], "-")246    assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]247    # used single options aren't suggested again248    assert "-c" not in _get_words(cli, ["-c", "f"], "-")249250251def test_option_nargs():252    cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])253    assert _get_words(cli, ["-c"], "") == ["a", "b"]254    assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]255    assert _get_words(cli, ["-c", "a", "b"], "") == []256257258def test_argument_nargs():259    cli = Command(260        "cli",261        params=[262            Argument(["x"], type=Choice(["a", "b"]), nargs=2),263            Argument(["y"], type=Choice(["c", "d"]), nargs=-1),264            Option(["-z"]),265        ],266    )267    assert _get_words(cli, [], "") == ["a", "b"]268    assert _get_words(cli, ["a"], "") == ["a", "b"]269    assert _get_words(cli, ["a", "b"], "") == ["c", "d"]270    assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]271    assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]272    assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]273    assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]274275276def test_double_dash():277    cli = Command(278        "cli",279        add_help_option=False,280        params=[281            Option(["--opt"]),282            Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),283        ],284    )285    assert _get_words(cli, [], "-") == ["--opt"]286    assert _get_words(cli, ["value"], "-") == ["--opt"]287    assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]288    assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]289290291def test_hidden():292    cli = Group(293        "cli",294        commands=[295            Command(296                "hidden",297                add_help_option=False,298                hidden=True,299                params=[300                    Option(["-a"]),301                    Option(["-b"], type=Choice(["a", "b"]), hidden=True),302                ],303            )304        ],305    )306    assert "hidden" not in _get_words(cli, [], "")307    assert "hidden" not in _get_words(cli, [], "hidden")308    assert _get_words(cli, ["hidden"], "-") == ["-a"]309    assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]310311312def test_add_different_name():313    cli = Group("cli", commands={"renamed": Command("original")})314    words = _get_words(cli, [], "")315    assert "renamed" in words316    assert "original" not in words317318319def test_completion_item_data():320    c = CompletionItem("test", a=1)321    assert c.a == 1322    assert c.b is None323324325@pytest.fixture()326def _patch_for_completion(monkeypatch):327    monkeypatch.setattr(328        "click.shell_completion.BashComplete._check_version", lambda self: True329    )330331332@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])333@pytest.mark.usefixtures("_patch_for_completion")334def test_full_source(runner, shell):335    cli = Group("cli", commands=[Command("a"), Command("b")])336    result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})337    assert f"_CLI_COMPLETE={shell}_complete" in result.output338339340@pytest.mark.parametrize(341    ("shell", "env", "expect"),342    [343        ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),344        ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),345        ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),346        ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),347        ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),348        ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),349    ],350)351@pytest.mark.usefixtures("_patch_for_completion")352def test_full_complete(runner, shell, env, expect):353    cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])354    env["_CLI_COMPLETE"] = f"{shell}_complete"355    result = runner.invoke(cli, env=env)356    assert result.output == expect357358359@pytest.mark.parametrize(360    ("env", "expect"),361    [362        (363            {"COMP_WORDS": "", "COMP_CWORD": "0"},364            textwrap.dedent(365                """\366                    plain367                    a368                    _369                    plain370                    b371                    bee372                    plain373                    c\\:d374                    cee:dee375                    plain376                    c:e377                    _378                """379            ),380        ),381        (382            {"COMP_WORDS": "a c", "COMP_CWORD": "1"},383            textwrap.dedent(384                """\385                    plain386                    c\\:d387                    cee:dee388                    plain389                    c:e390                    _391                """392            ),393        ),394        (395            {"COMP_WORDS": "a c:", "COMP_CWORD": "1"},396            textwrap.dedent(397                """\398                    plain399                    c\\:d400                    cee:dee401                    plain402                    c:e403                    _404                """405            ),406        ),407    ],408)409@pytest.mark.usefixtures("_patch_for_completion")410def test_zsh_full_complete_with_colons(411    runner, env: Mapping[str, str], expect: str412) -> None:413    cli = Group(414        "cli",415        commands=[416            Command("a"),417            Command("b", help="bee"),418            Command("c:d", help="cee:dee"),419            Command("c:e"),420        ],421    )422    result = runner.invoke(423        cli,424        env={425            **env,426            "_CLI_COMPLETE": "zsh_complete",427        },428    )429    assert result.output == expect430431432@pytest.mark.usefixtures("_patch_for_completion")433def test_context_settings(runner):434    def complete(ctx, param, incomplete):435        return ctx.obj["choices"]436437    cli = Command("cli", params=[Argument("x", shell_complete=complete)])438    result = runner.invoke(439        cli,440        obj={"choices": ["a", "b"]},441        env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},442    )443    assert result.output == "plain,a\nplain,b\n"444445446@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])447def test_choice_case_sensitive(value, expect):448    cli = Command(449        "cli",450        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],451    )452    completions = _get_words(cli, ["-a"], "a")453    assert completions == expect454455456@pytest.fixture()457def _restore_available_shells(tmpdir):458    prev_available_shells = click.shell_completion._available_shells.copy()459    click.shell_completion._available_shells.clear()460    yield461    click.shell_completion._available_shells.clear()462    click.shell_completion._available_shells.update(prev_available_shells)463464465@pytest.mark.usefixtures("_restore_available_shells")466def test_add_completion_class():467    # At first, "mysh" is not in available shells468    assert "mysh" not in click.shell_completion._available_shells469470    class MyshComplete(ShellComplete):471        name = "mysh"472        source_template = "dummy source"473474    # "mysh" still not in available shells because it is not registered475    assert "mysh" not in click.shell_completion._available_shells476477    # Adding a completion class should return that class478    assert add_completion_class(MyshComplete) is MyshComplete479480    # Now, "mysh" is finally in available shells481    assert "mysh" in click.shell_completion._available_shells482    assert click.shell_completion._available_shells["mysh"] is MyshComplete483484485@pytest.mark.usefixtures("_restore_available_shells")486def test_add_completion_class_with_name():487    # At first, "mysh" is not in available shells488    assert "mysh" not in click.shell_completion._available_shells489    assert "not_mysh" not in click.shell_completion._available_shells490491    class MyshComplete(ShellComplete):492        name = "not_mysh"493        source_template = "dummy source"494495    # "mysh" and "not_mysh" are still not in available shells because496    # it is not registered yet497    assert "mysh" not in click.shell_completion._available_shells498    assert "not_mysh" not in click.shell_completion._available_shells499500    # Adding a completion class should return that class.501    # Because we are using the "name" parameter, the name isn't taken502    # from the class.503    assert add_completion_class(MyshComplete, name="mysh") is MyshComplete504505    # Now, "mysh" is finally in available shells506    assert "mysh" in click.shell_completion._available_shells507    assert "not_mysh" not in click.shell_completion._available_shells508    assert click.shell_completion._available_shells["mysh"] is MyshComplete509510511@pytest.mark.usefixtures("_restore_available_shells")512def test_add_completion_class_decorator():513    # At first, "mysh" is not in available shells514    assert "mysh" not in click.shell_completion._available_shells515516    @add_completion_class517    class MyshComplete(ShellComplete):518        name = "mysh"519        source_template = "dummy source"520521    # Using `add_completion_class` as a decorator adds the new shell immediately522    assert "mysh" in click.shell_completion._available_shells523    assert click.shell_completion._available_shells["mysh"] is MyshComplete524525526# Don't make the ResourceWarning give an error527@pytest.mark.filterwarnings("default")528def test_files_closed(runner) -> None:529    with runner.isolated_filesystem():530        config_file = "foo.txt"531        with open(config_file, "w") as f:532            f.write("bar")533534        @click.group()535        @click.option(536            "--config-file",537            default=config_file,538            type=click.File(mode="r"),539        )540        @click.pass_context541        def cli(ctx, config_file):542            pass543544        with warnings.catch_warnings(record=True) as current_warnings:545            assert not current_warnings, "There should be no warnings to start"546            _get_completions(cli, args=[], incomplete="")547            assert not current_warnings, "There should be no warnings after either"