Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

416 lines · 13.8 KiB · Python

Last changed by

Merge branch '8.1.x'David Lordbefore adoption7271763

History of this file

Take it

1import pytest23import click.shell_completion4from click.core import Argument5from click.core import Command6from click.core import Group7from click.core import Option8from click.shell_completion import add_completion_class9from click.shell_completion import CompletionItem10from click.shell_completion import ShellComplete11from click.types import Choice12from click.types import File13from click.types import Path141516def _get_completions(cli, args, incomplete):17    comp = ShellComplete(cli, {}, cli.name, "_CLICK_COMPLETE")18    return comp.get_completions(args, incomplete)192021def _get_words(cli, args, incomplete):22    return [c.value for c in _get_completions(cli, args, incomplete)]232425def test_command():26    cli = Command("cli", params=[Option(["-t", "--test"])])27    assert _get_words(cli, [], "") == []28    assert _get_words(cli, [], "-") == ["-t", "--test", "--help"]29    assert _get_words(cli, [], "--") == ["--test", "--help"]30    assert _get_words(cli, [], "--t") == ["--test"]31    # -t has been seen, so --test isn't suggested32    assert _get_words(cli, ["-t", "a"], "-") == ["--help"]333435def test_group():36    cli = Group("cli", params=[Option(["-a"])], commands=[Command("x"), Command("y")])37    assert _get_words(cli, [], "") == ["x", "y"]38    assert _get_words(cli, [], "-") == ["-a", "--help"]394041def test_group_command_same_option():42    cli = Group(43        "cli", params=[Option(["-a"])], commands=[Command("x", params=[Option(["-a"])])]44    )45    assert _get_words(cli, [], "-") == ["-a", "--help"]46    assert _get_words(cli, ["-a", "a"], "-") == ["--help"]47    assert _get_words(cli, ["-a", "a", "x"], "-") == ["-a", "--help"]48    assert _get_words(cli, ["-a", "a", "x", "-a", "a"], "-") == ["--help"]495051def test_chained():52    cli = Group(53        "cli",54        chain=True,55        commands=[56            Command("set", params=[Option(["-y"])]),57            Command("start"),58            Group("get", commands=[Command("full")]),59        ],60    )61    assert _get_words(cli, [], "") == ["get", "set", "start"]62    assert _get_words(cli, [], "s") == ["set", "start"]63    assert _get_words(cli, ["set", "start"], "") == ["get"]64    # subcommands and parent subcommands65    assert _get_words(cli, ["get"], "") == ["full", "set", "start"]66    assert _get_words(cli, ["get", "full"], "") == ["set", "start"]67    assert _get_words(cli, ["get"], "s") == ["set", "start"]686970def test_help_option():71    cli = Group("cli", commands=[Command("with"), Command("no", add_help_option=False)])72    assert _get_words(cli, ["with"], "--") == ["--help"]73    assert _get_words(cli, ["no"], "--") == []747576def test_argument_order():77    cli = Command(78        "cli",79        params=[80            Argument(["plain"]),81            Argument(["c1"], type=Choice(["a1", "a2", "b"])),82            Argument(["c2"], type=Choice(["c1", "c2", "d"])),83        ],84    )85    # first argument has no completions86    assert _get_words(cli, [], "") == []87    assert _get_words(cli, [], "a") == []88    # first argument filled, now completion can happen89    assert _get_words(cli, ["x"], "a") == ["a1", "a2"]90    assert _get_words(cli, ["x", "b"], "d") == ["d"]919293def test_argument_default():94    cli = Command(95        "cli",96        add_help_option=False,97        params=[98            Argument(["a"], type=Choice(["a"]), default="a"),99            Argument(["b"], type=Choice(["b"]), default="b"),100        ],101    )102    assert _get_words(cli, [], "") == ["a"]103    assert _get_words(cli, ["a"], "b") == ["b"]104    # ignore type validation105    assert _get_words(cli, ["x"], "b") == ["b"]106107108def test_type_choice():109    cli = Command("cli", params=[Option(["-c"], type=Choice(["a1", "a2", "b"]))])110    assert _get_words(cli, ["-c"], "") == ["a1", "a2", "b"]111    assert _get_words(cli, ["-c"], "a") == ["a1", "a2"]112    assert _get_words(cli, ["-c"], "a2") == ["a2"]113114115def test_choice_special_characters():116    cli = Command("cli", params=[Option(["-c"], type=Choice(["!1", "!2", "+3"]))])117    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]118    assert _get_words(cli, ["-c"], "!") == ["!1", "!2"]119    assert _get_words(cli, ["-c"], "!2") == ["!2"]120121122def test_choice_conflicting_prefix():123    cli = Command(124        "cli",125        params=[126            Option(["-c"], type=Choice(["!1", "!2", "+3"])),127            Option(["+p"], is_flag=True),128        ],129    )130    assert _get_words(cli, ["-c"], "") == ["!1", "!2", "+3"]131    assert _get_words(cli, ["-c"], "+") == ["+p"]132133134def test_option_count():135    cli = Command("cli", params=[Option(["-c"], count=True)])136    assert _get_words(cli, ["-c"], "") == []137    assert _get_words(cli, ["-c"], "-") == ["--help"]138139140def test_option_optional():141    cli = Command(142        "cli",143        add_help_option=False,144        params=[145            Option(["--name"], is_flag=False, flag_value="value"),146            Option(["--flag"], is_flag=True),147        ],148    )149    assert _get_words(cli, ["--name"], "") == []150    assert _get_words(cli, ["--name"], "-") == ["--flag"]151    assert _get_words(cli, ["--name", "--flag"], "-") == []152153154@pytest.mark.parametrize(155    ("type", "expect"),156    [(File(), "file"), (Path(), "file"), (Path(file_okay=False), "dir")],157)158def test_path_types(type, expect):159    cli = Command("cli", params=[Option(["-f"], type=type)])160    out = _get_completions(cli, ["-f"], "ab")161    assert len(out) == 1162    c = out[0]163    assert c.value == "ab"164    assert c.type == expect165166167def test_absolute_path():168    cli = Command("cli", params=[Option(["-f"], type=Path())])169    out = _get_completions(cli, ["-f"], "/ab")170    assert len(out) == 1171    c = out[0]172    assert c.value == "/ab"173174175def test_option_flag():176    cli = Command(177        "cli",178        add_help_option=False,179        params=[180            Option(["--on/--off"]),181            Argument(["a"], type=Choice(["a1", "a2", "b"])),182        ],183    )184    assert _get_words(cli, [], "--") == ["--on", "--off"]185    # flag option doesn't take value, use choice argument186    assert _get_words(cli, ["--on"], "a") == ["a1", "a2"]187188189def test_option_custom():190    def custom(ctx, param, incomplete):191        return [incomplete.upper()]192193    cli = Command(194        "cli",195        params=[196            Argument(["x"]),197            Argument(["y"]),198            Argument(["z"], shell_complete=custom),199        ],200    )201    assert _get_words(cli, ["a", "b"], "") == [""]202    assert _get_words(cli, ["a", "b"], "c") == ["C"]203204205def test_option_multiple():206    cli = Command(207        "type",208        params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],209    )210    assert _get_words(cli, ["-m"], "") == ["a", "b"]211    assert "-m" in _get_words(cli, ["-m", "a"], "-")212    assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]213    # used single options aren't suggested again214    assert "-c" not in _get_words(cli, ["-c", "f"], "-")215216217def test_option_nargs():218    cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])219    assert _get_words(cli, ["-c"], "") == ["a", "b"]220    assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]221    assert _get_words(cli, ["-c", "a", "b"], "") == []222223224def test_argument_nargs():225    cli = Command(226        "cli",227        params=[228            Argument(["x"], type=Choice(["a", "b"]), nargs=2),229            Argument(["y"], type=Choice(["c", "d"]), nargs=-1),230            Option(["-z"]),231        ],232    )233    assert _get_words(cli, [], "") == ["a", "b"]234    assert _get_words(cli, ["a"], "") == ["a", "b"]235    assert _get_words(cli, ["a", "b"], "") == ["c", "d"]236    assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]237    assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]238    assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]239    assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]240241242def test_double_dash():243    cli = Command(244        "cli",245        add_help_option=False,246        params=[247            Option(["--opt"]),248            Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),249        ],250    )251    assert _get_words(cli, [], "-") == ["--opt"]252    assert _get_words(cli, ["value"], "-") == ["--opt"]253    assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]254    assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]255256257def test_hidden():258    cli = Group(259        "cli",260        commands=[261            Command(262                "hidden",263                add_help_option=False,264                hidden=True,265                params=[266                    Option(["-a"]),267                    Option(["-b"], type=Choice(["a", "b"]), hidden=True),268                ],269            )270        ],271    )272    assert "hidden" not in _get_words(cli, [], "")273    assert "hidden" not in _get_words(cli, [], "hidden")274    assert _get_words(cli, ["hidden"], "-") == ["-a"]275    assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]276277278def test_add_different_name():279    cli = Group("cli", commands={"renamed": Command("original")})280    words = _get_words(cli, [], "")281    assert "renamed" in words282    assert "original" not in words283284285def test_completion_item_data():286    c = CompletionItem("test", a=1)287    assert c.a == 1288    assert c.b is None289290291@pytest.fixture()292def _patch_for_completion(monkeypatch):293    monkeypatch.setattr(294        "click.shell_completion.BashComplete._check_version", lambda self: True295    )296297298@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])299@pytest.mark.usefixtures("_patch_for_completion")300def test_full_source(runner, shell):301    cli = Group("cli", commands=[Command("a"), Command("b")])302    result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})303    assert f"_CLI_COMPLETE={shell}_complete" in result.output304305306@pytest.mark.parametrize(307    ("shell", "env", "expect"),308    [309        ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),310        ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),311        ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),312        ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),313        ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),314        ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),315    ],316)317@pytest.mark.usefixtures("_patch_for_completion")318def test_full_complete(runner, shell, env, expect):319    cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])320    env["_CLI_COMPLETE"] = f"{shell}_complete"321    result = runner.invoke(cli, env=env)322    assert result.output == expect323324325@pytest.mark.usefixtures("_patch_for_completion")326def test_context_settings(runner):327    def complete(ctx, param, incomplete):328        return ctx.obj["choices"]329330    cli = Command("cli", params=[Argument("x", shell_complete=complete)])331    result = runner.invoke(332        cli,333        obj={"choices": ["a", "b"]},334        env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},335    )336    assert result.output == "plain,a\nplain,b\n"337338339@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])340def test_choice_case_sensitive(value, expect):341    cli = Command(342        "cli",343        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],344    )345    completions = _get_words(cli, ["-a"], "a")346    assert completions == expect347348349@pytest.fixture()350def _restore_available_shells(tmpdir):351    prev_available_shells = click.shell_completion._available_shells.copy()352    click.shell_completion._available_shells.clear()353    yield354    click.shell_completion._available_shells.clear()355    click.shell_completion._available_shells.update(prev_available_shells)356357358@pytest.mark.usefixtures("_restore_available_shells")359def test_add_completion_class():360    # At first, "mysh" is not in available shells361    assert "mysh" not in click.shell_completion._available_shells362363    class MyshComplete(ShellComplete):364        name = "mysh"365        source_template = "dummy source"366367    # "mysh" still not in available shells because it is not registered368    assert "mysh" not in click.shell_completion._available_shells369370    # Adding a completion class should return that class371    assert add_completion_class(MyshComplete) is MyshComplete372373    # Now, "mysh" is finally in available shells374    assert "mysh" in click.shell_completion._available_shells375    assert click.shell_completion._available_shells["mysh"] is MyshComplete376377378@pytest.mark.usefixtures("_restore_available_shells")379def test_add_completion_class_with_name():380    # At first, "mysh" is not in available shells381    assert "mysh" not in click.shell_completion._available_shells382    assert "not_mysh" not in click.shell_completion._available_shells383384    class MyshComplete(ShellComplete):385        name = "not_mysh"386        source_template = "dummy source"387388    # "mysh" and "not_mysh" are still not in available shells because389    # it is not registered yet390    assert "mysh" not in click.shell_completion._available_shells391    assert "not_mysh" not in click.shell_completion._available_shells392393    # Adding a completion class should return that class.394    # Because we are using the "name" parameter, the name isn't taken395    # from the class.396    assert add_completion_class(MyshComplete, name="mysh") is MyshComplete397398    # Now, "mysh" is finally in available shells399    assert "mysh" in click.shell_completion._available_shells400    assert "not_mysh" not in click.shell_completion._available_shells401    assert click.shell_completion._available_shells["mysh"] is MyshComplete402403404@pytest.mark.usefixtures("_restore_available_shells")405def test_add_completion_class_decorator():406    # At first, "mysh" is not in available shells407    assert "mysh" not in click.shell_completion._available_shells408409    @add_completion_class410    class MyshComplete(ShellComplete):411        name = "mysh"412        source_template = "dummy source"413414    # Using `add_completion_class` as a decorator adds the new shell immediately415    assert "mysh" in click.shell_completion._available_shells416    assert click.shell_completion._available_shells["mysh"] is MyshComplete