test_commands.py
This file
Path
tests/test_commands.py
575 lines · 17.6 KiB · Python
Last changed by
Hide `Sentinel.UNSET` values for defaults processed by `Context.invoke` (#3068)Rowlando13before adoption6a1c0d0
History of this fileTake it
The walk stopped after 200 commits: lines older than 7ab7174 point at it.
Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 1–97why, one step back1import 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 )9697Help shown via no_args_is_help results in exit code 2, was 0 (#1489)fdavisbefore adoptiond8763b9
lines 98–100why, one step back98def test_command_no_args_is_help(runner):99 result = runner.invoke(click.Command("test", no_args_is_help=True))100 assert result.exit_code == 2Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 101–125why, one step back101 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"),Help shown via no_args_is_help results in exit code 2, was 0 (#1489)fdavisbefore adoptiond8763b9
line 126why, one step back126 ([], 2, "Show this message and exit."),Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 127–143why, one step back127 ],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.output142143deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 144why, one step back144def test_custom_parser(runner):Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 145–150why, one step back145 import optparse146147 @click.group()148 def cli():149 pass150deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 151why, one step back151 class OptParseCommand(click.Command):Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 152–230why, one step back152 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"229230Hide `Sentinel.UNSET` values for defaults processed by `Context.invoke` (#3068)Rowlando13before adoption6a1c0d0
lines 231–262why, one step back231@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):Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 263–268why, one step back263 @click.command()264 @click.pass_context265 def cli(ctx):266 return ctx.invoke(other_cmd)267268 @click.command()Hide `Sentinel.UNSET` values for defaults processed by `Context.invoke` (#3068)Rowlando13before adoption6a1c0d0
line 269why, one step back269 @click.option("-a", **opt_params)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 270why, one step back270 @click.pass_contextHide `Sentinel.UNSET` values for defaults processed by `Context.invoke` (#3068)Rowlando13before adoption6a1c0d0
lines 271–272why, one step back271 def other_cmd(ctx, a):272 return ctx.info_name, aBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 273–274why, one step back273274 result = runner.invoke(cli, standalone_mode=False)Hide `Sentinel.UNSET` values for defaults processed by `Context.invoke` (#3068)Rowlando13before adoption6a1c0d0
lines 275–276why, one step back275276 assert result.return_value == ("other", expected)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 277–331why, one step back277278279def 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"300301302def test_aliased_command_canonical_name(runner):303 class AliasedGroup(click.Group):304 def get_command(self, ctx, cmd_name):305 return push306307 def resolve_command(self, ctx, args):308 _, command, args = super().resolve_command(ctx, args)309 return command.name, command, args310311 cli = AliasedGroup()312313 @cli.command()314 def push():315 click.echo("push command")316317 result = runner.invoke(cli, ["pu", "--help"])318 assert not result.exception319 assert result.output.startswith("Usage: root push [OPTIONS]")320321322def test_group_add_command_name(runner):323 cli = click.Group("cli")324 cmd = click.Command("a", params=[click.Option(["-x"], required=True)])325 cli.add_command(cmd, "b")326 # Check that the command is accessed through the registered name,327 # not the original name.328 result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})329 assert result.exit_code == 0330331Merge `stable` into `main`; Release 8.2.0 (#2873)Rowlando13before adoptionb7c0ab4
lines 332–463why, one step back332@pytest.mark.parametrize(333 ("invocation_order", "declaration_order", "expected_order"),334 [335 # Non-eager options.336 ([], ["-a"], ["-a"]),337 (["-a"], ["-a"], ["-a"]),338 ([], ["-a", "-c"], ["-a", "-c"]),339 (["-a"], ["-a", "-c"], ["-a", "-c"]),340 (["-c"], ["-a", "-c"], ["-c", "-a"]),341 ([], ["-c", "-a"], ["-c", "-a"]),342 (["-a"], ["-c", "-a"], ["-a", "-c"]),343 (["-c"], ["-c", "-a"], ["-c", "-a"]),344 (["-a", "-c"], ["-a", "-c"], ["-a", "-c"]),345 (["-c", "-a"], ["-a", "-c"], ["-c", "-a"]),346 # Eager options.347 ([], ["-b"], ["-b"]),348 (["-b"], ["-b"], ["-b"]),349 ([], ["-b", "-d"], ["-b", "-d"]),350 (["-b"], ["-b", "-d"], ["-b", "-d"]),351 (["-d"], ["-b", "-d"], ["-d", "-b"]),352 ([], ["-d", "-b"], ["-d", "-b"]),353 (["-b"], ["-d", "-b"], ["-b", "-d"]),354 (["-d"], ["-d", "-b"], ["-d", "-b"]),355 (["-b", "-d"], ["-b", "-d"], ["-b", "-d"]),356 (["-d", "-b"], ["-b", "-d"], ["-d", "-b"]),357 # Mixed options.358 ([], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),359 (["-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),360 (["-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),361 (["-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-c", "-a"]),362 (["-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-a", "-c"]),363 (["-a", "-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),364 (["-b", "-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),365 (["-d", "-c"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),366 (["-c", "-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),367 (["-a", "-b", "-c", "-d"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),368 (["-b", "-d", "-a", "-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),369 ([], ["-b", "-d", "-e", "-a", "-c"], ["-b", "-d", "-e", "-a", "-c"]),370 (["-a", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-a", "-c"]),371 (["-c", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-c", "-a"]),372 ],373)374def test_iter_params_for_processing(375 invocation_order, declaration_order, expected_order376):377 parameters = {378 "-a": click.Option(["-a"]),379 "-b": click.Option(["-b"], is_eager=True),380 "-c": click.Option(["-c"]),381 "-d": click.Option(["-d"], is_eager=True),382 "-e": click.Option(["-e"], is_eager=True),383 }384385 invocation_params = [parameters[opt_id] for opt_id in invocation_order]386 declaration_params = [parameters[opt_id] for opt_id in declaration_order]387 expected_params = [parameters[opt_id] for opt_id in expected_order]388389 assert (390 click.core.iter_params_for_processing(invocation_params, declaration_params)391 == expected_params392 )393394395def test_help_param_priority(runner):396 """Cover the edge-case in which the eagerness of help option was not397 respected, because it was internally generated multiple times.398399 See: https://github.com/pallets/click/pull/2811400 """401402 def print_and_exit(ctx, param, value):403 if value:404 click.echo(f"Value of {param.name} is: {value}")405 ctx.exit()406407 @click.command(context_settings={"help_option_names": ("--my-help",)})408 @click.option("-a", is_flag=True, expose_value=False, callback=print_and_exit)409 @click.option(410 "-b", is_flag=True, expose_value=False, callback=print_and_exit, is_eager=True411 )412 def cli():413 pass414415 # --my-help is properly called and stop execution.416 result = runner.invoke(cli, ["--my-help"])417 assert "Value of a is: True" not in result.stdout418 assert "Value of b is: True" not in result.stdout419 assert "--my-help" in result.stdout420 assert result.exit_code == 0421422 # -a is properly called and stop execution.423 result = runner.invoke(cli, ["-a"])424 assert "Value of a is: True" in result.stdout425 assert "Value of b is: True" not in result.stdout426 assert "--my-help" not in result.stdout427 assert result.exit_code == 0428429 # -a takes precedence over -b and stop execution.430 result = runner.invoke(cli, ["-a", "-b"])431 assert "Value of a is: True" not in result.stdout432 assert "Value of b is: True" in result.stdout433 assert "--my-help" not in result.stdout434 assert result.exit_code == 0435436 # --my-help is eager by default so takes precedence over -a and stop437 # execution, whatever the order.438 for args in [["-a", "--my-help"], ["--my-help", "-a"]]:439 result = runner.invoke(cli, args)440 assert "Value of a is: True" not in result.stdout441 assert "Value of b is: True" not in result.stdout442 assert "--my-help" in result.stdout443 assert result.exit_code == 0444445 # Both -b and --my-help are eager so they're called in the order they're446 # invoked by the user.447 result = runner.invoke(cli, ["-b", "--my-help"])448 assert "Value of a is: True" not in result.stdout449 assert "Value of b is: True" in result.stdout450 assert "--my-help" not in result.stdout451 assert result.exit_code == 0452453 # But there was a bug when --my-help is called before -b, because the454 # --my-help option created by click via help_option_names is internally455 # created twice and is not the same object, breaking the priority order456 # produced by iter_params_for_processing.457 result = runner.invoke(cli, ["--my-help", "-b"])458 assert "Value of a is: True" not in result.stdout459 assert "Value of b is: True" not in result.stdout460 assert "--my-help" in result.stdout461 assert result.exit_code == 0462463Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 464–480why, one step back464def test_unprocessed_options(runner):465 @click.command(context_settings=dict(ignore_unknown_options=True))466 @click.argument("args", nargs=-1, type=click.UNPROCESSED)467 @click.option("--verbose", "-v", count=True)468 def cli(verbose, args):469 click.echo(f"Verbosity: {verbose}")470 click.echo(f"Args: {'|'.join(args)}")471472 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])473 assert not result.exception474 assert result.output.splitlines() == [475 "Verbosity: 4",476 "Args: -foo|-x|--muhaha|x|y|-x",477 ]478479480@pytest.mark.parametrize("doc", ["CLI HELP", None])Introduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31
lines 481–483why, one step back481@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])482def test_deprecated_in_help_messages(runner, doc, deprecated):483 @click.command(deprecated=deprecated, help=doc)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 484–487why, one step back484 def cli():485 pass486487 result = runner.invoke(cli, ["--help"])Introduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31
line 488why, one step back488 assert "(DEPRECATED" in result.outputBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 489why, one step back489Introduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31
lines 490–491why, one step back490 if isinstance(deprecated, str):491 assert deprecated in result.outputBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
line 492why, one step back492Introduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31
lines 493–496why, one step back493494@pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])495def test_deprecated_in_invocation(runner, deprecated):496 @click.command(deprecated=deprecated)Bump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 497–501why, one step back497 def deprecated_cmd():498 pass499500 result = runner.invoke(deprecated_cmd)501 assert "DeprecationWarning:" in result.outputIntroduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31
lines 502–504why, one step back502503 if isinstance(deprecated, str):504 assert deprecated in result.outputBump actions/cache from 3.2.4 to 3.2.6 (#2458)David Lordbefore adoption7ab7174
lines 505–563why, one step back505506507def test_command_parse_args_collects_option_prefixes():508 @click.command()509 @click.option("+p", is_flag=True)510 @click.option("!e", is_flag=True)511 def test(p, e):512 pass513514 ctx = click.Context(test)515 test.parse_args(ctx, [])516517 assert ctx._opt_prefixes == {"-", "--", "+", "!"}518519520def test_group_parse_args_collects_base_option_prefixes():521 @click.group()522 @click.option("~t", is_flag=True)523 def group(t):524 pass525526 @group.command()527 @click.option("+p", is_flag=True)528 def command1(p):529 pass530531 @group.command()532 @click.option("!e", is_flag=True)533 def command2(e):534 pass535536 ctx = click.Context(group)537 group.parse_args(ctx, ["command1", "+p"])538539 assert ctx._opt_prefixes == {"-", "--", "~"}540541542def test_group_invoke_collects_used_option_prefixes(runner):543 opt_prefixes = set()544545 @click.group()546 @click.option("~t", is_flag=True)547 def group(t):548 pass549550 @group.command()551 @click.option("+p", is_flag=True)552 @click.pass_context553 def command1(ctx, p):554 nonlocal opt_prefixes555 opt_prefixes = ctx._opt_prefixes556557 @group.command()558 @click.option("!e", is_flag=True)559 def command2(e):560 pass561562 runner.invoke(group, ["command1"])563 assert opt_prefixes == {"-", "--", "~", "+"}Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 564–575why, one step back564565566@pytest.mark.parametrize("exc", (EOFError, KeyboardInterrupt))567def test_abort_exceptions_with_disabled_standalone_mode(runner, exc):568 @click.command()569 def cli():570 raise exc("catch me!")571572 rv = runner.invoke(cli, standalone_mode=False)573 assert rv.exit_code == 1574 assert isinstance(rv.exception.__cause__, exc)575 assert rv.exception.__cause__.args == ("catch me!",)