Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

305 lines · 9.8 KiB · Python

Last changed by

Merge pull request #2130 from pallets/remove-deprecated-codeDavid Lordbefore adoption6411f42

History of this file

Take it

1import pytest23from click.core import Argument4from click.core import Command5from click.core import Group6from click.core import Option7from click.shell_completion import CompletionItem8from click.shell_completion import ShellComplete9from click.types import Choice10from click.types import File11from click.types import Path121314def _get_completions(cli, args, incomplete):15    comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")16    return comp.get_completions(args, incomplete)171819def _get_words(cli, args, incomplete):20    return [c.value for c in _get_completions(cli, args, incomplete)]212223def test_command():24    cli = Command("cli", params=[Option(["-t", "--test"])])25    assert _get_words(cli, [], "") == []26    assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]27    assert _get_words(cli, [], "--") == ["--test", "--help"]28    assert _get_words(cli, [], "--t") == ["--test"]29    # -t has been seen, so --test isn't suggested30    assert _get_words(cli, ["-t", "a"], "-") == ["--help"]313233def test_group():34    cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])35    assert _get_words(cli, [], "") == ["x", "y"]36    assert _get_words(cli, [], "-") == ["-a", "--help"]373839def test_group_command_same_option():40    cli = Group(41        "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]42    )43    assert _get_words(cli, [], "-") == ["-a", "--help"]44    assert _get_words(cli, ["-a", "a"], "-") == ["--help"]45    assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]46    assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]474849def test_chained():50    cli = Group(51        "cli",52        chain=True,53        commands=[54            Command("set", params=[Option(["-y"])]),55            Command("start"),56            Group("get", commands=[Command("full")]),57        ],58    )59    assert _get_words(cli, [], "") == ["get", "set", "start"]60    assert _get_words(cli, [], "s") == ["set", "start"]61    assert _get_words(cli, ["set", "start"], "") == ["get"]62    # subcommands and parent subcommands63    assert _get_words(cli, ["get"], "") == ["full", "set", "start"]64    assert _get_words(cli, ["get", "full"], "") == ["set", "start"]65    assert _get_words(cli, ["get"], "s") == ["set", "start"]666768def test_help_option():69    cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])70    assert _get_words(cli, ["with"], "--") == ["--help"]71    assert _get_words(cli, ["no"], "--") == []727374def test_argument_order():75    cli = Command(76        "cli",77        params=[78            Argument(["plain"]),79            Argument(["c1"], type=Choice(["a1", "a2", "b"])),80            Argument(["c2"], type=Choice(["c1", "c2", "d"])),81        ],82    )83    # first argument has no completions84    assert _get_words(cli, [], "") == []85    assert _get_words(cli, [], "a") == []86    # first argument filled, now completion can happen87    assert _get_words(cli, ["x"], "a") == ["a1", "a2"]88    assert _get_words(cli, ["x", "b"], "d") == ["d"]899091def test_argument_default():92    cli = Command(93        "cli",94        add_help_option=False,95        params=[96            Argument(["a"], type=Choice(["a"]), default="a"),97            Argument(["b"], type=Choice(["b"]), default="b"),98        ],99    )100    assert _get_words(cli, [], "") == ["a"]101    assert _get_words(cli, ["a"], "b") == ["b"]102    # ignore type validation103    assert _get_words(cli, ["x"], "b") == ["b"]104105106def test_type_choice():107    cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])108    assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]109    assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]110    assert _get_words(cli, ["-c"], "a2") == ["a2"]111112113@pytest.mark.parametrize(114    ("type", "expect"),115    [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],116)117def test_path_types(type, expect):118    cli = Command("cli", params=[Option(["-f"], type=type)])119    out = _get_completions(cli, ["-f"], "ab")120    assert len(out) == 1121    c = out[0]122    assert c.value == "ab"123    assert c.type == expect124125126def test_absolute_path():127    cli = Command("cli", params=[Option(["-f"], type=Path())])128    out = _get_completions(cli, ["-f"], "/ab")129    assert len(out) == 1130    c = out[0]131    assert c.value == "/ab"132133134def test_option_flag():135    cli = Command(136        "cli",137        add_help_option=False,138        params=[139            Option(["--on/--off"]),140            Argument(["a"], type=Choice(["a1", "a2", "b"])),141        ],142    )143    assert _get_words(cli, [], "--") == ["--on", "--off"]144    # flag option doesn't take value, use choice argument145    assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]146147148def test_option_custom():149    def custom(ctx, param, incomplete):150        return [incomplete.upper()]151152    cli = Command(153        "cli",154        params=[155            Argument(["x"]),156            Argument(["y"]),157            Argument(["z"], shell_complete=custom),158        ],159    )160    assert _get_words(cli, ["a", "b"], "") == [""]161    assert _get_words(cli, ["a", "b"], "c") == ["C"]162163164def test_option_multiple():165    cli = Command(166        "type",167        params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],168    )169    assert _get_words(cli, ["-m"], "") == ["a", "b"]170    assert "-m" in _get_words(cli, ["-m", "a"], "-")171    assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]172    # used single options aren't suggested again173    assert "-c" not in _get_words(cli, ["-c", "f"], "-")174175176def test_option_nargs():177    cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])178    assert _get_words(cli, ["-c"], "") == ["a", "b"]179    assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]180    assert _get_words(cli, ["-c", "a", "b"], "") == []181182183def test_argument_nargs():184    cli = Command(185        "cli",186        params=[187            Argument(["x"], type=Choice(["a", "b"]), nargs=2),188            Argument(["y"], type=Choice(["c", "d"]), nargs=-1),189            Option(["-z"]),190        ],191    )192    assert _get_words(cli, [], "") == ["a", "b"]193    assert _get_words(cli, ["a"], "") == ["a", "b"]194    assert _get_words(cli, ["a", "b"], "") == ["c", "d"]195    assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]196    assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]197    assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]198    assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]199200201def test_double_dash():202    cli = Command(203        "cli",204        add_help_option=False,205        params=[206            Option(["--opt"]),207            Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),208        ],209    )210    assert _get_words(cli, [], "-") == ["--opt"]211    assert _get_words(cli, ["value"], "-") == ["--opt"]212    assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]213    assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]214215216def test_hidden():217    cli = Group(218        "cli",219        commands=[220            Command(221                "hidden",222                add_help_option=False,223                hidden=True,224                params=[225                    Option(["-a"]),226                    Option(["-b"], type=Choice(["a", "b"]), hidden=True),227                ],228            )229        ],230    )231    assert "hidden" not in _get_words(cli, [], "")232    assert "hidden" not in _get_words(cli, [], "hidden")233    assert _get_words(cli, ["hidden"], "-") == ["-a"]234    assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]235236237def test_add_different_name():238    cli = Group("cli", commands={"renamed": Command("original")})239    words = _get_words(cli, [], "")240    assert "renamed" in words241    assert "original" not in words242243244def test_completion_item_data():245    c = CompletionItem("test", a=1)246    assert c.a == 1247    assert c.b is None248249250@pytest.fixture()251def _patch_for_completion(monkeypatch):252    monkeypatch.setattr(253        "click.shell_completion.BashComplete._check_version", lambda self: True254    )255256257@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])258@pytest.mark.usefixtures("_patch_for_completion")259def test_full_source(runner, shell):260    cli = Group("cli", commands=[Command("a"), Command("b")])261    result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})262    assert f"_CLI_COMPLETE={shell}_complete" in result.output263264265@pytest.mark.parametrize(266    ("shell", "env", "expect"),267    [268        ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),269        ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),270        ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),271        ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),272        ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),273        ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),274    ],275)276@pytest.mark.usefixtures("_patch_for_completion")277def test_full_complete(runner, shell, env, expect):278    cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])279    env["_CLI_COMPLETE"] = f"{shell}_complete"280    result = runner.invoke(cli, env=env)281    assert result.output == expect282283284@pytest.mark.usefixtures("_patch_for_completion")285def test_context_settings(runner):286    def complete(ctx, param, incomplete):287        return ctx.obj["choices"]288289    cli = Command("cli", params=[Argument("x", shell_complete=complete)])290    result = runner.invoke(291        cli,292        obj={"choices": ["a", "b"]},293        env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},294    )295    assert result.output == "plain,a\nplain,b\n"296297298@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])299def test_choice_case_sensitive(value, expect):300    cli = Command(301        "cli",302        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],303    )304    completions = _get_words(cli, ["-a"], "a")305    assert completions == expect