Skip to content
Myr

test_shell_completion.py

This file

Path

tests/test_shell_completion.py

319 lines · 10.3 KiB · Python

Last changed by

Merge pull request #2030 from taranlu-houzz/remove_fast_exitDavid Lordbefore adoption6b61b74

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_autocompletion_deprecated():165    # old function takes args and not param, returns all values, can mix166    # strings and tuples167    def custom(ctx, args, incomplete):168        assert isinstance(args, list)169        return [("art", "x"), "bat", "cat"]170171    with pytest.deprecated_call():172        cli = Command("cli", params=[Argument(["x"], autocompletion=custom)])173174    assert _get_words(cli, [], "") == ["art", "bat", "cat"]175    assert _get_words(cli, [], "c") == ["cat"]176177178def test_option_multiple():179    cli = Command(180        "type",181        params=[Option(["-m"], type=Choice(["a", "b"]), multiple=True), Option(["-f"])],182    )183    assert _get_words(cli, ["-m"], "") == ["a", "b"]184    assert "-m" in _get_words(cli, ["-m", "a"], "-")185    assert _get_words(cli, ["-m", "a", "-m"], "") == ["a", "b"]186    # used single options aren't suggested again187    assert "-c" not in _get_words(cli, ["-c", "f"], "-")188189190def test_option_nargs():191    cli = Command("cli", params=[Option(["-c"], type=Choice(["a", "b"]), nargs=2)])192    assert _get_words(cli, ["-c"], "") == ["a", "b"]193    assert _get_words(cli, ["-c", "a"], "") == ["a", "b"]194    assert _get_words(cli, ["-c", "a", "b"], "") == []195196197def test_argument_nargs():198    cli = Command(199        "cli",200        params=[201            Argument(["x"], type=Choice(["a", "b"]), nargs=2),202            Argument(["y"], type=Choice(["c", "d"]), nargs=-1),203            Option(["-z"]),204        ],205    )206    assert _get_words(cli, [], "") == ["a", "b"]207    assert _get_words(cli, ["a"], "") == ["a", "b"]208    assert _get_words(cli, ["a", "b"], "") == ["c", "d"]209    assert _get_words(cli, ["a", "b", "c"], "") == ["c", "d"]210    assert _get_words(cli, ["a", "b", "c", "d"], "") == ["c", "d"]211    assert _get_words(cli, ["a", "-z", "1"], "") == ["a", "b"]212    assert _get_words(cli, ["a", "-z", "1", "b"], "") == ["c", "d"]213214215def test_double_dash():216    cli = Command(217        "cli",218        add_help_option=False,219        params=[220            Option(["--opt"]),221            Argument(["name"], type=Choice(["name", "--", "-o", "--opt"])),222        ],223    )224    assert _get_words(cli, [], "-") == ["--opt"]225    assert _get_words(cli, ["value"], "-") == ["--opt"]226    assert _get_words(cli, [], "") == ["name", "--", "-o", "--opt"]227    assert _get_words(cli, ["--"], "") == ["name", "--", "-o", "--opt"]228229230def test_hidden():231    cli = Group(232        "cli",233        commands=[234            Command(235                "hidden",236                add_help_option=False,237                hidden=True,238                params=[239                    Option(["-a"]),240                    Option(["-b"], type=Choice(["a", "b"]), hidden=True),241                ],242            )243        ],244    )245    assert "hidden" not in _get_words(cli, [], "")246    assert "hidden" not in _get_words(cli, [], "hidden")247    assert _get_words(cli, ["hidden"], "-") == ["-a"]248    assert _get_words(cli, ["hidden", "-b"], "") == ["a", "b"]249250251def test_add_different_name():252    cli = Group("cli", commands={"renamed": Command("original")})253    words = _get_words(cli, [], "")254    assert "renamed" in words255    assert "original" not in words256257258def test_completion_item_data():259    c = CompletionItem("test", a=1)260    assert c.a == 1261    assert c.b is None262263264@pytest.fixture()265def _patch_for_completion(monkeypatch):266    monkeypatch.setattr(267        "click.shell_completion.BashComplete._check_version", lambda self: True268    )269270271@pytest.mark.parametrize("shell", ["bash", "zsh", "fish"])272@pytest.mark.usefixtures("_patch_for_completion")273def test_full_source(runner, shell):274    cli = Group("cli", commands=[Command("a"), Command("b")])275    result = runner.invoke(cli, env={"_CLI_COMPLETE": f"{shell}_source"})276    assert f"_CLI_COMPLETE={shell}_complete" in result.output277278279@pytest.mark.parametrize(280    ("shell", "env", "expect"),281    [282        ("bash", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain,a\nplain,b\n"),283        ("bash", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain,b\n"),284        ("zsh", {"COMP_WORDS": "", "COMP_CWORD": "0"}, "plain\na\n_\nplain\nb\nbee\n"),285        ("zsh", {"COMP_WORDS": "a b", "COMP_CWORD": "1"}, "plain\nb\nbee\n"),286        ("fish", {"COMP_WORDS": "", "COMP_CWORD": ""}, "plain,a\nplain,b\tbee\n"),287        ("fish", {"COMP_WORDS": "a b", "COMP_CWORD": "b"}, "plain,b\tbee\n"),288    ],289)290@pytest.mark.usefixtures("_patch_for_completion")291def test_full_complete(runner, shell, env, expect):292    cli = Group("cli", commands=[Command("a"), Command("b", help="bee")])293    env["_CLI_COMPLETE"] = f"{shell}_complete"294    result = runner.invoke(cli, env=env)295    assert result.output == expect296297298@pytest.mark.usefixtures("_patch_for_completion")299def test_context_settings(runner):300    def complete(ctx, param, incomplete):301        return ctx.obj["choices"]302303    cli = Command("cli", params=[Argument("x", shell_complete=complete)])304    result = runner.invoke(305        cli,306        obj={"choices": ["a", "b"]},307        env={"COMP_WORDS": "", "COMP_CWORD": "0", "_CLI_COMPLETE": "bash_complete"},308    )309    assert result.output == "plain,a\nplain,b\n"310311312@pytest.mark.parametrize(("value", "expect"), [(False, ["Au", "al"]), (True, ["al"])])313def test_choice_case_sensitive(value, expect):314    cli = Command(315        "cli",316        params=[Option(["-a"], type=Choice(["Au", "al", "Bc"], case_sensitive=value))],317    )318    completions = _get_words(cli, ["-a"], "a")319    assert completions == expect