Skip to content
Myr

test_commands.py

This file

Path

tests/test_commands.py

700 lines · 21.7 KiB · Python

Last changed by

Sort help args to make them reproducible (#3728)Rowlando13before adoption9c4dfda

History of this file

Take it

1import re23import pytest45import click678def test_other_command_invoke(runner):9    @click.command()10    @click.pass_context11    def cli(ctx):12        return ctx.invoke(other_cmd, arg=42)1314    @click.command()15    @click.argument("arg", type=click.INT)16    def other_cmd(arg):17        click.echo(arg)1819    result = runner.invoke(cli, [])20    assert not result.exception21    assert result.output == "42\n"222324def test_other_command_forward(runner):25    cli = click.Group()2627    @cli.command()28    @click.option("--count", default=1)29    def test(count):30        click.echo(f"Count: {count:d}")3132    @cli.command()33    @click.option("--count", default=1)34    @click.pass_context35    def dist(ctx, count):36        ctx.forward(test)37        ctx.invoke(test, count=42)3839    result = runner.invoke(cli, ["dist"])40    assert not result.exception41    assert result.output == "Count: 1\nCount: 42\n"424344def test_forwarded_params_consistency(runner):45    cli = click.Group()4647    @cli.command()48    @click.option("-a")49    @click.pass_context50    def first(ctx, **kwargs):51        click.echo(f"{ctx.params}")5253    @cli.command()54    @click.option("-a")55    @click.option("-b")56    @click.pass_context57    def second(ctx, **kwargs):58        click.echo(f"{ctx.params}")59        ctx.forward(first)6061    result = runner.invoke(cli, ["second", "-a", "foo", "-b", "bar"])62    assert not result.exception63    assert result.output == "{'a': 'foo', 'b': 'bar'}\n{'a': 'foo', 'b': 'bar'}\n"646566def test_auto_shorthelp(runner):67    @click.group()68    def cli():69        pass7071    @cli.command()72    def short():73        """This is a short text."""7475    @cli.command()76    def special_chars():77        """Login and store the token in ~/.netrc."""7879    @cli.command()80    def long():81        """This is a long text that is too long to show as short help82        and will be truncated instead."""8384    result = runner.invoke(cli, ["--help"])85    assert (86        re.search(87            r"Commands:\n\s+"88            r"long\s+This is a long text that is too long to show as short help"89            r"\.\.\.\n\s+"90            r"short\s+This is a short text\.\n\s+"91            r"special-chars\s+Login and store the token in ~/.netrc\.\s*",92            result.output,93        )94        is not None95    )969798def test_command_no_args_is_help(runner):99    result = runner.invoke(click.Command("test", no_args_is_help=True))100    assert result.exit_code == 2101    assert "Show this message and exit." in result.output102103104def test_default_maps(runner):105    @click.group()106    def cli():107        pass108109    @cli.command()110    @click.option("--name", default="normal")111    def foo(name):112        click.echo(name)113114    result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})115116    assert not result.exception117    assert result.output == "changed\n"118119120@pytest.mark.parametrize(121    ("args", "exit_code", "expect"),122    [123        (["obj1"], 2, "Error: Missing command."),124        (["obj1", "--help"], 0, "Show this message and exit."),125        (["obj1", "move"], 0, "obj=obj1\nmove\n"),126        ([], 2, "Show this message and exit."),127    ],128)129def test_group_with_args(runner, args, exit_code, expect):130    @click.group()131    @click.argument("obj")132    def cli(obj):133        click.echo(f"obj={obj}")134135    @cli.command()136    def move():137        click.echo("move")138139    result = runner.invoke(cli, args)140    assert result.exit_code == exit_code141    assert expect in result.output142143144def test_custom_parser(runner):145    import optparse146147    @click.group()148    def cli():149        pass150151    class OptParseCommand(click.Command):152        def __init__(self, name, parser, callback):153            super().__init__(name)154            self.parser = parser155            self.callback = callback156157        def parse_args(self, ctx, args):158            try:159                opts, args = parser.parse_args(args)160            except Exception as e:161                ctx.fail(str(e))162            ctx.args = args163            ctx.params = vars(opts)164165        def get_usage(self, ctx):166            return self.parser.get_usage()167168        def get_help(self, ctx):169            return self.parser.format_help()170171        def invoke(self, ctx):172            ctx.invoke(self.callback, ctx.args, **ctx.params)173174    parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]")175    parser.add_option(176        "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"177    )178    parser.add_option(179        "-q",180        "--quiet",181        action="store_false",182        dest="verbose",183        default=True,184        help="don't print status messages to stdout",185    )186187    def test_callback(args, filename, verbose):188        click.echo(" ".join(args))189        click.echo(filename)190        click.echo(verbose)191192    cli.add_command(OptParseCommand("test", parser, test_callback))193194    result = runner.invoke(cli, ["test", "-f", "f.txt", "-q", "q1.txt", "q2.txt"])195    assert result.exception is None196    assert result.output.splitlines() == ["q1.txt q2.txt", "f.txt", "False"]197198    result = runner.invoke(cli, ["test", "--help"])199    assert result.exception is None200    assert result.output.splitlines() == [201        "Usage: foo test [OPTIONS]",202        "",203        "Options:",204        "  -h, --help            show this help message and exit",205        "  -f FILE, --file=FILE  write report to FILE",206        "  -q, --quiet           don't print status messages to stdout",207    ]208209210def test_object_propagation(runner):211    for chain in False, True:212213        @click.group(chain=chain)214        @click.option("--debug/--no-debug", default=False)215        @click.pass_context216        def cli(ctx, debug):217            if ctx.obj is None:218                ctx.obj = {}219            ctx.obj["DEBUG"] = debug220221        @cli.command()222        @click.pass_context223        def sync(ctx):224            click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")225226        result = runner.invoke(cli, ["sync"])227        assert result.exception is None228        assert result.output == "Debug is off\n"229230231@pytest.mark.parametrize(232    ("opt_params", "expected"),233    (234        # Original tests.235        ({"type": click.INT, "default": 42}, 42),236        ({"type": click.INT, "default": "15"}, 15),237        ({"multiple": True}, ()),238        # SENTINEL value tests.239        ({"default": None}, None),240        ({"type": click.STRING}, None),  # No default specified, should be None.241        ({"type": click.BOOL, "default": False}, False),242        ({"type": click.BOOL, "default": True}, True),243        ({"type": click.FLOAT, "default": 3.14}, 3.14),244        # Multiple with default.245        ({"multiple": True, "default": [1, 2, 3]}, (1, 2, 3)),246        ({"multiple": True, "default": ()}, ()),247        # Required option without value should use SENTINEL behavior.248        ({"required": False}, None),249        # Choice type with default.250        ({"type": click.Choice(["a", "b", "c"]), "default": "b"}, "b"),251        # Path type with default.252        ({"type": click.Path(), "default": "/tmp"}, "/tmp"),253        # Flag options.254        ({"is_flag": True, "default": False}, False),255        ({"is_flag": True, "default": True}, True),256        # Count option.257        ({"count": True}, 0),258        # Hidden option.259        ({"hidden": True, "default": "secret"}, "secret"),260    ),261)262def test_other_command_invoke_with_defaults(runner, opt_params, expected):263    @click.command()264    @click.pass_context265    def cli(ctx):266        return ctx.invoke(other_cmd)267268    @click.command()269    @click.option("-a", **opt_params)270    @click.pass_context271    def other_cmd(ctx, a):272        return ctx.info_name, a273274    result = runner.invoke(cli, standalone_mode=False)275276    assert result.return_value == ("other", expected)277278279def test_invoked_subcommand(runner):280    @click.group(invoke_without_command=True)281    @click.pass_context282    def cli(ctx):283        if ctx.invoked_subcommand is None:284            click.echo("no subcommand, use default")285            ctx.invoke(sync)286        else:287            click.echo("invoke subcommand")288289    @cli.command()290    def sync():291        click.echo("in subcommand")292293    result = runner.invoke(cli, ["sync"])294    assert not result.exception295    assert result.output == "invoke subcommand\nin subcommand\n"296297    result = runner.invoke(cli)298    assert not result.exception299    assert result.output == "no subcommand, use default\nin subcommand\n"300301302@pytest.mark.parametrize(303    ("chain", "invoke_without_command", "metavar"),304    [305        (False, False, "COMMAND [ARGS]..."),306        (False, True, "[COMMAND] [ARGS]..."),307        (True, False, "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."),308        (True, True, "[COMMAND1] [ARGS]... [COMMAND2 [ARGS]...]..."),309    ],310)311def test_subcommand_metavar_marks_optional(312    runner, chain, invoke_without_command, metavar313):314    """The leading subcommand token is bracketed only when it is optional."""315316    @click.group(chain=chain, invoke_without_command=invoke_without_command)317    def cli():318        pass319320    @cli.command()321    def sub():322        pass323324    result = runner.invoke(cli, ["--help"])325    assert result.exit_code == 0326    assert result.output.splitlines()[0] == f"Usage: cli [OPTIONS] {metavar}"327328329def test_aliased_command_canonical_name(runner):330    class AliasedGroup(click.Group):331        def get_command(self, ctx, cmd_name):332            return push333334        def resolve_command(self, ctx, args):335            _, command, args = super().resolve_command(ctx, args)336            return command.name, command, args337338    cli = AliasedGroup()339340    @cli.command()341    def push():342        click.echo("push command")343344    result = runner.invoke(cli, ["pu", "--help"])345    assert not result.exception346    assert result.output.startswith("Usage: root push [OPTIONS]")347348349def test_group_add_command_name(runner):350    cli = click.Group("cli")351    cmd = click.Command("a", params=[click.Option(["-x"], required=True)])352    cli.add_command(cmd, "b")353    # Check that the command is accessed through the registered name,354    # not the original name.355    result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})356    assert result.exit_code == 0357358359@pytest.mark.parametrize(360    ("invocation_order", "declaration_order", "expected_order"),361    [362        # Non-eager options.363        ([], ["-a"], ["-a"]),364        (["-a"], ["-a"], ["-a"]),365        ([], ["-a", "-c"], ["-a", "-c"]),366        (["-a"], ["-a", "-c"], ["-a", "-c"]),367        (["-c"], ["-a", "-c"], ["-c", "-a"]),368        ([], ["-c", "-a"], ["-c", "-a"]),369        (["-a"], ["-c", "-a"], ["-a", "-c"]),370        (["-c"], ["-c", "-a"], ["-c", "-a"]),371        (["-a", "-c"], ["-a", "-c"], ["-a", "-c"]),372        (["-c", "-a"], ["-a", "-c"], ["-c", "-a"]),373        # Eager options.374        ([], ["-b"], ["-b"]),375        (["-b"], ["-b"], ["-b"]),376        ([], ["-b", "-d"], ["-b", "-d"]),377        (["-b"], ["-b", "-d"], ["-b", "-d"]),378        (["-d"], ["-b", "-d"], ["-d", "-b"]),379        ([], ["-d", "-b"], ["-d", "-b"]),380        (["-b"], ["-d", "-b"], ["-b", "-d"]),381        (["-d"], ["-d", "-b"], ["-d", "-b"]),382        (["-b", "-d"], ["-b", "-d"], ["-b", "-d"]),383        (["-d", "-b"], ["-b", "-d"], ["-d", "-b"]),384        # Mixed options.385        ([], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),386        (["-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),387        (["-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),388        (["-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-c", "-a"]),389        (["-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-a", "-c"]),390        (["-a", "-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),391        (["-b", "-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),392        (["-d", "-c"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),393        (["-c", "-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),394        (["-a", "-b", "-c", "-d"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),395        (["-b", "-d", "-a", "-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),396        ([], ["-b", "-d", "-e", "-a", "-c"], ["-b", "-d", "-e", "-a", "-c"]),397        (["-a", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-a", "-c"]),398        (["-c", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-c", "-a"]),399    ],400)401def test_iter_params_for_processing(402    invocation_order, declaration_order, expected_order403):404    parameters = {405        "-a": click.Option(["-a"]),406        "-b": click.Option(["-b"], is_eager=True),407        "-c": click.Option(["-c"]),408        "-d": click.Option(["-d"], is_eager=True),409        "-e": click.Option(["-e"], is_eager=True),410    }411412    invocation_params = [parameters[opt_id] for opt_id in invocation_order]413    declaration_params = [parameters[opt_id] for opt_id in declaration_order]414    expected_params = [parameters[opt_id] for opt_id in expected_order]415416    assert (417        click.core.iter_params_for_processing(invocation_params, declaration_params)418        == expected_params419    )420421422@pytest.mark.parametrize(423    ("help_option_names", "params", "expected"),424    [425        # A single default name is returned unchanged.426        (["--help"], [], ["--help"]),427        # Declaration order is preserved verbatim, whatever it is.428        (["-h", "--help"], [], ["-h", "--help"]),429        (["--help", "-h"], [], ["--help", "-h"]),430        (["--help", "-h", "-?"], [], ["--help", "-h", "-?"]),431        (["-?", "--help", "-h"], [], ["-?", "--help", "-h"]),432        # Duplicate names collapse to their first occurrence, keeping order.433        (["--help", "--help"], [], ["--help"]),434        (["-h", "--help", "-h"], [], ["-h", "--help"]),435        # A name already claimed by another parameter's option is dropped.436        (["-h", "--help"], [["--help"]], ["-h"]),437        (["-h", "--help"], [["-h", "--verbose"]], ["--help"]),438        # Both options of a feature-switch flag are removed too.439        (["--shout", "--help"], [["--shout/--no-shout"]], ["--help"]),440        (["--no-shout", "--help"], [["--shout/--no-shout"]], ["--help"]),441        # Filtering every name out yields an empty list.442        (["-h", "--help"], [["-h"], ["--help"]], []),443        # Deduplication and conflict removal combine, order still preserved.444        (["-h", "--help", "-h", "--assist"], [["--assist"]], ["-h", "--help"]),445    ],446    ids=[447        "default",448        "order-short-long",449        "order-long-short",450        "order-three",451        "order-three-shuffled",452        "dedupe-adjacent",453        "dedupe-spread",454        "conflict-long",455        "conflict-short",456        "conflict-flag-on",457        "conflict-flag-off",458        "all-removed",459        "dedupe-and-conflict",460    ],461)462def test_get_help_option_names(help_option_names, params, expected):463    """Check help option names are deduplicated but keep stable order.464465    https://github.com/pallets/click/pull/3728466    """467    cli = click.Command("cli", params=[click.Option(decls) for decls in params])468    ctx = click.Context(cli, help_option_names=help_option_names)469    assert cli.get_help_option_names(ctx) == expected470471472def test_help_param_priority(runner):473    """Cover the edge-case in which the eagerness of help option was not474    respected, because it was internally generated multiple times.475476    See: https://github.com/pallets/click/pull/2811477    """478479    def print_and_exit(ctx, param, value):480        if value:481            click.echo(f"Value of {param.name} is: {value}")482            ctx.exit()483484    @click.command(context_settings={"help_option_names": ("--my-help",)})485    @click.option("-a", is_flag=True, expose_value=False, callback=print_and_exit)486    @click.option(487        "-b", is_flag=True, expose_value=False, callback=print_and_exit, is_eager=True488    )489    def cli():490        pass491492    # --my-help is properly called and stop execution.493    result = runner.invoke(cli, ["--my-help"])494    assert "Value of a is: True" not in result.stdout495    assert "Value of b is: True" not in result.stdout496    assert "--my-help" in result.stdout497    assert result.exit_code == 0498499    # -a is properly called and stop execution.500    result = runner.invoke(cli, ["-a"])501    assert "Value of a is: True" in result.stdout502    assert "Value of b is: True" not in result.stdout503    assert "--my-help" not in result.stdout504    assert result.exit_code == 0505506    # -a takes precedence over -b and stop execution.507    result = runner.invoke(cli, ["-a", "-b"])508    assert "Value of a is: True" not in result.stdout509    assert "Value of b is: True" in result.stdout510    assert "--my-help" not in result.stdout511    assert result.exit_code == 0512513    # --my-help is eager by default so takes precedence over -a and stop514    # execution, whatever the order.515    for args in [["-a", "--my-help"], ["--my-help", "-a"]]:516        result = runner.invoke(cli, args)517        assert "Value of a is: True" not in result.stdout518        assert "Value of b is: True" not in result.stdout519        assert "--my-help" in result.stdout520        assert result.exit_code == 0521522    # Both -b and --my-help are eager so they're called in the order they're523    # invoked by the user.524    result = runner.invoke(cli, ["-b", "--my-help"])525    assert "Value of a is: True" not in result.stdout526    assert "Value of b is: True" in result.stdout527    assert "--my-help" not in result.stdout528    assert result.exit_code == 0529530    # But there was a bug when --my-help is called before -b, because the531    # --my-help option created by click via help_option_names is internally532    # created twice and is not the same object, breaking the priority order533    # produced by iter_params_for_processing.534    result = runner.invoke(cli, ["--my-help", "-b"])535    assert "Value of a is: True" not in result.stdout536    assert "Value of b is: True" not in result.stdout537    assert "--my-help" in result.stdout538    assert result.exit_code == 0539540541def test_unprocessed_options(runner):542    @click.command(context_settings=dict(ignore_unknown_options=True))543    @click.argument("args", nargs=-1, type=click.UNPROCESSED)544    @click.option("--verbose", "-v", count=True)545    def cli(verbose, args):546        click.echo(f"Verbosity: {verbose}")547        click.echo(f"Args: {'|'.join(args)}")548549    result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])550    assert not result.exception551    assert result.output.splitlines() == [552        "Verbosity: 4",553        "Args: -foo|-x|--muhaha|x|y|-x",554    ]555556557@pytest.mark.parametrize("doc", ["CLI HELP", None])558@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])559def test_deprecated_in_help_messages(runner, doc, deprecated):560    @click.command(deprecated=deprecated, help=doc)561    def cli():562        pass563564    result = runner.invoke(cli, ["--help"])565    assert "(DEPRECATED" in result.output566567    if isinstance(deprecated, str):568        assert deprecated in result.output569570571@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])572@pytest.mark.parametrize("doc", ["", None])573def test_deprecated_empty_help_no_leading_space(runner, doc, deprecated):574    """A command with empty or missing help text must render the deprecation575    label at the normal indentation, without a stray leading space.576    """577578    @click.command(deprecated=deprecated, help=doc)579    def cli():580        pass581582    out = runner.invoke(cli, ["--help"]).output583    assert "\n  (DEPRECATED" in out584    assert "\n   (DEPRECATED" not in out585586587@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])588def test_deprecated_in_invocation(runner, deprecated):589    @click.command(deprecated=deprecated)590    def deprecated_cmd():591        pass592593    result = runner.invoke(deprecated_cmd)594    assert "DeprecationWarning:" in result.output595596    if isinstance(deprecated, str):597        assert deprecated in result.output598599600def test_command_parse_args_collects_option_prefixes():601    @click.command()602    @click.option("+p", is_flag=True)603    @click.option("!e", is_flag=True)604    def test(p, e):605        pass606607    ctx = click.Context(test)608    test.parse_args(ctx, [])609610    assert ctx._opt_prefixes == {"-", "--", "+", "!"}611612613def test_group_parse_args_collects_base_option_prefixes():614    @click.group()615    @click.option("~t", is_flag=True)616    def group(t):617        pass618619    @group.command()620    @click.option("+p", is_flag=True)621    def command1(p):622        pass623624    @group.command()625    @click.option("!e", is_flag=True)626    def command2(e):627        pass628629    ctx = click.Context(group)630    group.parse_args(ctx, ["command1", "+p"])631632    assert ctx._opt_prefixes == {"-", "--", "~"}633634635def test_group_invoke_collects_used_option_prefixes(runner):636    opt_prefixes = set()637638    @click.group()639    @click.option("~t", is_flag=True)640    def group(t):641        pass642643    @group.command()644    @click.option("+p", is_flag=True)645    @click.pass_context646    def command1(ctx, p):647        nonlocal opt_prefixes648        opt_prefixes = ctx._opt_prefixes649650    @group.command()651    @click.option("!e", is_flag=True)652    def command2(e):653        pass654655    runner.invoke(group, ["command1"])656    assert opt_prefixes == {"-", "--", "~", "+"}657658659@pytest.mark.parametrize("exc", (EOFError, KeyboardInterrupt))660def test_abort_exceptions_with_disabled_standalone_mode(runner, exc):661    @click.command()662    def cli():663        raise exc("catch me!")664665    rv = runner.invoke(cli, standalone_mode=False)666    assert rv.exit_code == 1667    assert isinstance(rv.exception.__cause__, exc)668    assert rv.exception.__cause__.args == ("catch me!",)669670671def test_unknown_command(runner):672    result = runner.invoke(click.Group(), "unknown")673    assert result.exception674    assert "No such command 'unknown'." in result.output675676677@pytest.mark.parametrize(678    ("value", "expect"),679    [680        ("pause", "Did you mean 'push'?"),681        ("decline", "(Did you mean one of: 'declare', 'refine'?)"),682    ],683)684def test_suggest_possible_commands(runner, value, expect):685    cli = click.Group()686687    @cli.command()688    def push():689        pass690691    @cli.command()692    def declare():693        pass694695    @cli.command()696    def refine():697        pass698699    result = runner.invoke(cli, [value])700    assert expect in result.output