Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

882 lines · 24.7 KiB · Python

Last changed by

Add `@custom_version_option`, freeze `@version_option` (#3581)Rowlando13before adoption94c191c

History of this file

Take it

The walk stopped after 200 commits: lines older than 0ef55fd point at it.

Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a

lines 1–3why, one step back
1from __future__ import annotations
23import enum

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 4–8why, one step back
4import os
56import pytest78import click

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 9why, one step back
9from click._utils import UNSET

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 10–208why, one step back
10
1112def test_basic_functionality(runner):13 @click.command()14 def cli():15 """Hello World!"""16 click.echo("I EXECUTED")1718 result = runner.invoke(cli, ["--help"])19 assert not result.exception20 assert "Hello World!" in result.output21 assert "Show this message and exit." in result.output22 assert result.exit_code == 023 assert "I EXECUTED" not in result.output2425 result = runner.invoke(cli, [])26 assert not result.exception27 assert "I EXECUTED" in result.output28 assert result.exit_code == 0293031def test_repr():32 @click.command()33 def command():34 pass3536 @click.group()37 def group():38 pass3940 @group.command()41 def subcommand():42 pass4344 assert repr(command) == "<Command command>"45 assert repr(group) == "<Group group>"46 assert repr(subcommand) == "<Command subcommand>"474849def test_return_values():50 @click.command()51 def cli():52 return 425354 with cli.make_context("foo", []) as ctx:55 rv = cli.invoke(ctx)56 assert rv == 42575859def test_basic_group(runner):60 @click.group()61 def cli():62 """This is the root."""63 click.echo("ROOT EXECUTED")6465 @cli.command()66 def subcommand():67 """This is a subcommand."""68 click.echo("SUBCOMMAND EXECUTED")6970 result = runner.invoke(cli, ["--help"])71 assert not result.exception72 assert "COMMAND [ARGS]..." in result.output73 assert "This is the root" in result.output74 assert "This is a subcommand." in result.output75 assert result.exit_code == 076 assert "ROOT EXECUTED" not in result.output7778 result = runner.invoke(cli, ["subcommand"])79 assert not result.exception80 assert result.exit_code == 081 assert "ROOT EXECUTED" in result.output82 assert "SUBCOMMAND EXECUTED" in result.output838485def test_group_commands_dict(runner):86 """A Group can be built with a dict of commands."""8788 @click.command()89 def sub():90 click.echo("sub", nl=False)9192 cli = click.Group(commands={"other": sub})93 result = runner.invoke(cli, ["other"])94 assert result.output == "sub"959697def test_group_from_list(runner):98 """A Group can be built with a list of commands."""99100 @click.command()101 def sub():102 click.echo("sub", nl=False)103104 cli = click.Group(commands=[sub])105 result = runner.invoke(cli, ["sub"])106 assert result.output == "sub"107108109@pytest.mark.parametrize(110 ("args", "expect"),111 [112 ([], "S:[no value]"),113 (["--s=42"], "S:[42]"),114 (["--s"], "Error: Option '--s' requires an argument."),115 (["--s="], "S:[]"),116 (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"),117 ],118)119def test_string_option(runner, args, expect):120 @click.command()121 @click.option("--s", default="no value")122 def cli(s):123 click.echo(f"S:[{s}]")124125 result = runner.invoke(cli, args)126 assert expect in result.output127128 if expect.startswith("Error:"):129 assert result.exception is not None130 else:131 assert result.exception is None132133134@pytest.mark.parametrize(135 ("args", "expect"),136 [137 ([], "I:[84]"),138 (["--i=23"], "I:[46]"),139 (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."),140 ],141)142def test_int_option(runner, args, expect):143 @click.command()144 @click.option("--i", default=42)145 def cli(i):146 click.echo(f"I:[{i * 2}]")147148 result = runner.invoke(cli, args)149 assert expect in result.output150151 if expect.startswith("Error:"):152 assert result.exception is not None153 else:154 assert result.exception is None155156157@pytest.mark.parametrize(158 ("args", "expect"),159 [160 ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"),161 (162 ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"],163 "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]",164 ),165 (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."),166 ],167)168def test_uuid_option(runner, args, expect):169 @click.command()170 @click.option(171 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID172 )173 def cli(u):174 click.echo(f"U:[{u}]")175176 result = runner.invoke(cli, args)177 assert expect in result.output178179 if expect.startswith("Error:"):180 assert result.exception is not None181 else:182 assert result.exception is None183184185@pytest.mark.parametrize(186 ("args", "expect"),187 [188 ([], "F:[42.0]"),189 ("--f=23.5", "F:[23.5]"),190 ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."),191 ],192)193def test_float_option(runner, args, expect):194 @click.command()195 @click.option("--f", default=42.0)196 def cli(f):197 click.echo(f"F:[{f}]")198199 result = runner.invoke(cli, args)200 assert expect in result.output201202 if expect.startswith("Error:"):203 assert result.exception is not None204 else:205 assert result.exception is None206207208@pytest.mark.parametrize(

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 209–223why, one step back
209 ("args", "default", "expect"),
210 [211 (["--on"], True, True),212 (["--on"], False, True),213 (["--on"], None, True),214 (["--on"], UNSET, True),215 (["--off"], True, False),216 (["--off"], False, False),217 (["--off"], None, False),218 (["--off"], UNSET, False),219 ([], True, True),220 ([], False, False),221 ([], None, None),222 ([], UNSET, False),223 ],

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

line 224why, one step back
224)

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 225why, one step back
225def test_boolean_switch(runner, args, default, expect):

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 226–234why, one step back
226 @click.command()
227 @click.option("--on/--off", default=default)228 def cli(on):229 return on230231 result = runner.invoke(cli, args, standalone_mode=False)232 assert result.return_value is expect233234

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 235–241why, one step back
235@pytest.mark.parametrize(
236 ("default", "args", "expect"),237 (238 (True, ["--f"], True),239 (True, [], True),240 (False, ["--f"], True),241 (False, [], False),

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 242–245why, one step back
242 # Boolean flags have a 3-states logic.
243 # See: https://github.com/pallets/click/issues/3024#issue-3285556668244 (None, ["--f"], True),245 (None, [], None),

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 246–247why, one step back
246 ),
247)

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 248–259why, one step back
248def test_boolean_flag(runner, default, args, expect):
249 @click.command()250 @click.option("--f", is_flag=True, default=default)251 def cli(f):252 return f253254 result = runner.invoke(cli, args, standalone_mode=False)255 assert result.return_value is expect256257258@pytest.mark.parametrize(259 ("value", "expect"),

Don't parameterize tests using non-Collection iterables (#3656)Kevin Deldyckebefore adoption6ec99f8

lines 260–263why, one step back
260 [
261 *((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),262 *((x, "False") for x in ("0", "false", "f", "no", "n", "off")),263 ],

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 264–277why, one step back
264)
265def test_boolean_conversion(runner, value, expect):266 @click.command()267 @click.option("--flag", type=bool)268 def cli(flag):269 click.echo(flag, nl=False)270271 result = runner.invoke(cli, ["--flag", value])272 assert result.output == expect273274 result = runner.invoke(cli, ["--flag", value.title()])275 assert result.output == expect276277

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 278–317why, one step back
278@pytest.mark.parametrize(
279 ("default", "args", "expected"),280 # These test cases are similar to the ones in281 # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.282 (283 # Each option is returning its own flag_value, whatever the default is.284 (True, ["--upper"], "upper"),285 (True, ["--lower"], "lower"),286 (False, ["--upper"], "upper"),287 (False, ["--lower"], "lower"),288 (None, ["--upper"], "upper"),289 (None, ["--lower"], "lower"),290 (UNSET, ["--upper"], "upper"),291 (UNSET, ["--lower"], "lower"),292 # Check that the last option wins when both are specified.293 (True, ["--upper", "--lower"], "lower"),294 (True, ["--lower", "--upper"], "upper"),295 # Check that the default is returned as-is when no option is specified.296 ("upper", [], "upper"),297 ("lower", [], "lower"),298 ("uPPer", [], "uPPer"),299 ("lOwEr", [], "lOwEr"),300 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),301 (None, [], None),302 # Default is normalized to None if it is UNSET.303 (UNSET, [], None),304 # Special case: if default=True and flag_value is set, the value returned is the305 # flag_value, not the True Python value itself.306 (True, [], "upper"),307 # Non-string defaults are process as strings by the default Parameter's type.308 (False, [], "False"),309 (42, [], "42"),310 (12.3, [], "12.3"),311 ),312)313def test_flag_value_dual_options(runner, default, args, expected):314 """Check how default is processed when options compete for the same variable name.315316 Covers the regression reported in317 https://github.com/pallets/click/issues/3024#issuecomment-3146199461

Add cross-reference to tests from `test_defaults.py` (#3223)Rowlando13before adoptionfa7f035

lines 318–323why, one step back
318
319 .. hint::320 Similar to ``test_options.py::test_default_dual_option_callback``.321322 ``test_defaults.py::test_shared_param_prefers_first_default``323 is a smoke-test complement that exercises both default placements.

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 324–335why, one step back
324 """
325326 @click.command()327 @click.option("--upper", "case", flag_value="upper", default=default)328 @click.option("--lower", "case", flag_value="lower")329 def cli(case):330 click.echo(repr(case), nl=False)331332 result = runner.invoke(cli, args)333 assert result.output == repr(expected)334335

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 336–482why, one step back
336def test_file_option(runner):
337 @click.command()338 @click.option("--file", type=click.File("w"))339 def input(file):340 file.write("Hello World!\n")341342 @click.command()343 @click.option("--file", type=click.File("r"))344 def output(file):345 click.echo(file.read())346347 with runner.isolated_filesystem():348 result_in = runner.invoke(input, ["--file=example.txt"])349 result_out = runner.invoke(output, ["--file=example.txt"])350351 assert not result_in.exception352 assert result_in.output == ""353 assert not result_out.exception354 assert result_out.output == "Hello World!\n\n"355356357def test_file_lazy_mode(runner):358 do_io = False359360 @click.command()361 @click.option("--file", type=click.File("w"))362 def input(file):363 if do_io:364 file.write("Hello World!\n")365366 @click.command()367 @click.option("--file", type=click.File("r"))368 def output(file):369 pass370371 with runner.isolated_filesystem():372 os.mkdir("example.txt")373374 do_io = True375 result_in = runner.invoke(input, ["--file=example.txt"])376 assert result_in.exit_code == 1377378 do_io = False379 result_in = runner.invoke(input, ["--file=example.txt"])380 assert result_in.exit_code == 0381382 result_out = runner.invoke(output, ["--file=example.txt"])383 assert result_out.exception384385 @click.command()386 @click.option("--file", type=click.File("w", lazy=False))387 def input_non_lazy(file):388 file.write("Hello World!\n")389390 with runner.isolated_filesystem():391 os.mkdir("example.txt")392 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])393 assert result_in.exit_code == 2394 assert "Invalid value for '--file': 'example.txt'" in result_in.output395396397def test_path_option(runner):398 @click.command()399 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))400 def write_to_dir(o):401 with open(os.path.join(o, "foo.txt"), "wb") as f:402 f.write(b"meh\n")403404 with runner.isolated_filesystem():405 os.mkdir("test")406407 result = runner.invoke(write_to_dir, ["-O", "test"])408 assert not result.exception409410 with open("test/foo.txt", "rb") as f:411 assert f.read() == b"meh\n"412413 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])414 assert "is a file" in result.output415416 @click.command()417 @click.option("-f", type=click.Path(exists=True))418 def showtype(f):419 click.echo(f"is_file={os.path.isfile(f)}")420 click.echo(f"is_dir={os.path.isdir(f)}")421422 with runner.isolated_filesystem():423 result = runner.invoke(showtype, ["-f", "xxx"])424 assert "does not exist" in result.output425426 result = runner.invoke(showtype, ["-f", "."])427 assert "is_file=False" in result.output428 assert "is_dir=True" in result.output429430 @click.command()431 @click.option("-f", type=click.Path())432 def exists(f):433 click.echo(f"exists={os.path.exists(f)}")434435 with runner.isolated_filesystem():436 result = runner.invoke(exists, ["-f", "xxx"])437 assert "exists=False" in result.output438439 result = runner.invoke(exists, ["-f", "."])440 assert "exists=True" in result.output441442443def test_choice_option(runner):444 @click.command()445 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))446 def cli(method):447 click.echo(method)448449 result = runner.invoke(cli, ["--method=foo"])450 assert not result.exception451 assert result.output == "foo\n"452453 result = runner.invoke(cli, ["--method=meh"])454 assert result.exit_code == 2455 assert (456 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."457 in result.output458 )459460 result = runner.invoke(cli, ["--help"])461 assert "--method [foo|bar|baz]" in result.output462463464def test_choice_argument(runner):465 @click.command()466 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))467 def cli(method):468 click.echo(method)469470 result = runner.invoke(cli, ["foo"])471 assert not result.exception472 assert result.output == "foo\n"473474 result = runner.invoke(cli, ["meh"])475 assert result.exit_code == 2476 assert (477 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"478 " 'bar', 'baz'." in result.output479 )480481 result = runner.invoke(cli, ["--help"])482 assert "{foo|bar|baz}" in result.output

Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a

lines 483–549why, one step back
483
484485def test_choice_argument_enum(runner):486 class MyEnum(str, enum.Enum):487 FOO = "foo-value"488 BAR = "bar-value"489 BAZ = "baz-value"490491 @click.command()492 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))493 def cli(method: MyEnum):494 assert isinstance(method, MyEnum)495 click.echo(method)496497 result = runner.invoke(cli, ["foo"])498 assert result.output == "foo-value\n"499 assert not result.exception500501 result = runner.invoke(cli, ["meh"])502 assert result.exit_code == 2503 assert (504 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"505 " 'bar', 'baz'." in result.output506 )507508 result = runner.invoke(cli, ["--help"])509 assert "{foo|bar|baz}" in result.output510511512def test_choice_argument_custom_type(runner):513 class MyClass:514 def __init__(self, value: str) -> None:515 self.value = value516517 def __str__(self) -> str:518 return self.value519520 @click.command()521 @click.argument(522 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])523 )524 def cli(method: MyClass):525 assert isinstance(method, MyClass)526 click.echo(method)527528 result = runner.invoke(cli, ["foo"])529 assert not result.exception530 assert result.output == "foo\n"531532 result = runner.invoke(cli, ["meh"])533 assert result.exit_code == 2534 assert (535 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"536 " 'bar', 'baz'." in result.output537 )538539 result = runner.invoke(cli, ["--help"])540 assert "{foo|bar|baz}" in result.output541542543def test_choice_argument_none(runner):544 @click.command()545 @click.argument(546 "method", type=click.Choice(["not-none", None], case_sensitive=False)547 )548 def cli(method: str | None):549 assert isinstance(method, str) or method is None

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 550why, one step back
550 click.echo(repr(method), nl=False)

Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a

lines 551–553why, one step back
551
552 result = runner.invoke(cli, ["not-none"])553 assert not result.exception

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

line 554why, one step back
554 assert result.output == repr("not-none")

Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a

lines 555–556why, one step back
555
556 result = runner.invoke(cli, ["none"])

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 557–560why, one step back
557 assert not result.exception
558 assert result.output == repr(None)559560 result = runner.invoke(cli, [])

Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a

line 561why, one step back
561 assert result.exception

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 562–568why, one step back
562 assert (
563 "Error: Missing argument '{not-none|none}'. "564 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr565 )566567 result = runner.invoke(cli, ["--help"])568 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 569–570why, one step back
569
570

Merge remote-tracking branch 'upstream/stable' into merge-stable-into-mainKevin Deldyckebefore adoption240603f

lines 571–610why, one step back
571def test_choice_argument_optional_metavar(runner):
572 """Optional Choice arguments reuse the type's brackets instead of doubling.573574 Without this the usage line for a ``Choice`` argument with ``nargs=-1`` or575 ``required=False`` rendered as ``[[a|b|c]]``: one pair from ``Choice`` to576 enumerate values, a second pair from ``Argument`` to mark it optional.577 """578579 @click.command()580 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), nargs=-1)581 def cli_variadic(method):582 pass583584 @click.command()585 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), required=False)586 def cli_optional(method):587 pass588589 variadic = runner.invoke(cli_variadic, ["--help"]).output590 assert "Usage: cli-variadic [OPTIONS] [foo|bar|baz]...\n" in variadic591 assert "[[foo|bar|baz]]" not in variadic592593 optional = runner.invoke(cli_optional, ["--help"]).output594 assert "Usage: cli-optional [OPTIONS] [foo|bar|baz]\n" in optional595 assert "[[foo|bar|baz]]" not in optional596597598def test_datetime_argument_optional_metavar(runner):599 """``DateTime`` arguments behave the same way as ``Choice``."""600601 @click.command()602 @click.argument("when", type=click.DateTime(formats=["%Y-%m-%d"]), required=False)603 def cli(when):604 pass605606 result = runner.invoke(cli, ["--help"])607 assert "Usage: cli [OPTIONS] [%Y-%m-%d]\n" in result.output608 assert "[[%Y-%m-%d]]" not in result.output609610

Close contexts created during shell completion #2644. (#2800)Andreas Backxbefore adoption0ef55fd

lines 611–780why, one step back
611def test_datetime_option_default(runner):
612 @click.command()613 @click.option("--start_date", type=click.DateTime())614 def cli(start_date):615 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))616617 result = runner.invoke(cli, ["--start_date=2015-09-29"])618 assert not result.exception619 assert result.output == "2015-09-29T00:00:00\n"620621 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])622 assert not result.exception623 assert result.output == "2015-09-29T09:11:22\n"624625 result = runner.invoke(cli, ["--start_date=2015-09"])626 assert result.exit_code == 2627 assert (628 "Invalid value for '--start_date': '2015-09' does not match the formats"629 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."630 ) in result.output631632 result = runner.invoke(cli, ["--help"])633 assert (634 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output635 )636637638def test_datetime_option_custom(runner):639 @click.command()640 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))641 def cli(start_date):642 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))643644 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])645 assert not result.exception646 assert result.output == "2010-06-05T00:00:00\n"647648649def test_required_option(runner):650 @click.command()651 @click.option("--foo", required=True)652 def cli(foo):653 click.echo(foo)654655 result = runner.invoke(cli, [])656 assert result.exit_code == 2657 assert "Missing option '--foo'" in result.output658659660def test_evaluation_order(runner):661 called = []662663 def memo(ctx, param, value):664 called.append(value)665 return value666667 @click.command()668 @click.option("--missing", default="missing", is_eager=False, callback=memo)669 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)670 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)671 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)672 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)673 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)674 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)675 def cli(**x):676 pass677678 result = runner.invoke(679 cli,680 [681 "--eager-flag2",682 "--eager-flag1",683 "--normal-flag2",684 "--eager-flag3",685 "--normal-flag3",686 "--normal-flag3",687 "--normal-flag1",688 "--normal-flag1",689 ],690 )691 assert not result.exception692 assert called == [693 "eager2",694 "eager1",695 "eager3",696 "normal2",697 "normal3",698 "normal1",699 "missing",700 ]701702703def test_hidden_option(runner):704 @click.command()705 @click.option("--nope", hidden=True)706 def cli(nope):707 click.echo(nope)708709 result = runner.invoke(cli, ["--help"])710 assert result.exit_code == 0711 assert "--nope" not in result.output712713714def test_hidden_command(runner):715 @click.group()716 def cli():717 pass718719 @cli.command(hidden=True)720 def nope():721 pass722723 result = runner.invoke(cli, ["--help"])724 assert result.exit_code == 0725 assert "nope" not in result.output726727728def test_hidden_group(runner):729 @click.group()730 def cli():731 pass732733 @cli.group(hidden=True)734 def subgroup():735 pass736737 @subgroup.command()738 def nope():739 pass740741 result = runner.invoke(cli, ["--help"])742 assert result.exit_code == 0743 assert "subgroup" not in result.output744 assert "nope" not in result.output745746747def test_summary_line(runner):748 @click.group()749 def cli():750 pass751752 @cli.command()753 def cmd():754 """755 Summary line without period756757 Here is a sentence. And here too.758 """759 pass760761 result = runner.invoke(cli, ["--help"])762 assert "Summary line without period" in result.output763 assert "Here is a sentence." not in result.output764765766def test_help_invalid_default(runner):767 cli = click.Command(768 "cli",769 params=[770 click.Option(771 ["-a"],772 type=click.Path(exists=True),773 default="not found",774 show_default=True,775 ),776 ],777 )778 result = runner.invoke(cli, ["--help"])779 assert result.exit_code == 0780 assert "default: not found" in result.output

Merge remote-tracking branch 'upstream/stable' into merge-stable-into-mainKevin Deldyckebefore adoption240603f

lines 781–859why, one step back
781
782783def test_version_option_resolves_import_name_to_distribution(runner, monkeypatch):784 """When ``package_name`` (detected or passed) is an import name that785 differs from its installed distribution name (``PIL`` vs ``Pillow``),786 ``version_option`` resolves it via ``packages_distributions()`` instead787 of raising ``RuntimeError``.788 """789 import importlib.metadata790791 def fake_version(name):792 if name == "pillow":793 return "10.4.0"794 raise importlib.metadata.PackageNotFoundError(name)795796 monkeypatch.setattr(importlib.metadata, "version", fake_version)797 monkeypatch.setattr(798 importlib.metadata,799 "packages_distributions",800 lambda: {"PIL": ["pillow"]},801 )802803 @click.command()804 @click.version_option(package_name="PIL")805 def cli():806 pass807808 result = runner.invoke(cli, ["--version"], prog_name="imageapp")809 assert result.exit_code == 0810 assert "10.4.0" in result.output811812813def test_version_option_ambiguous_import_name_errors(runner, monkeypatch):814 """When an import name maps to multiple installed distributions, the815 user must disambiguate. The error names the candidates.816 """817 import importlib.metadata818819 def fake_version(name):820 raise importlib.metadata.PackageNotFoundError(name)821822 monkeypatch.setattr(importlib.metadata, "version", fake_version)823 monkeypatch.setattr(824 importlib.metadata,825 "packages_distributions",826 lambda: {"plug": ["foo-plug", "bar-plug"]},827 )828829 @click.command()830 @click.version_option(package_name="plug")831 def cli():832 pass833834 result = runner.invoke(cli, ["--version"])835 assert result.exit_code != 0836 msg = str(result.exception)837 assert "multiple installed distributions" in msg838 assert "foo-plug" in msg839 assert "bar-plug" in msg840841842def test_version_option_unknown_package_errors(runner, monkeypatch):843 """When the name resolves to no distribution, keep the existing error."""844 import importlib.metadata845846 def fake_version(name):847 raise importlib.metadata.PackageNotFoundError(name)848849 monkeypatch.setattr(importlib.metadata, "version", fake_version)850 monkeypatch.setattr(importlib.metadata, "packages_distributions", lambda: {})851852 @click.command()853 @click.version_option(package_name="nonexistent")854 def cli():855 pass856857 result = runner.invoke(cli, ["--version"])858 assert result.exit_code != 0859 assert "not installed" in str(result.exception)

Add `@custom_version_option`, freeze `@version_option` (#3581)Rowlando13before adoption94c191c

lines 860–882why, one step back
860
861862@pytest.mark.parametrize("args", [["--version"], ["-V"]])863def test_custom_version_option(runner, args):864 @click.command()865 @click.custom_version_option(lambda ctx: "custom 9.9.9", "-V", "--version")866 def cli():867 pass868869 result = runner.invoke(cli, args)870 assert result.exit_code == 0871 assert result.output == "custom 9.9.9\n"872873874def test_custom_version_option_receives_context(runner):875 @click.command()876 @click.custom_version_option(lambda ctx: f"{ctx.info_name} 1.0")877 def cli():878 pass879880 result = runner.invoke(cli, ["--version"], prog_name="mytool")881 assert result.exit_code == 0882 assert result.output == "mytool 1.0\n"