test_basic.py
This file
Path
tests/test_basic.py
860 lines · 24.1 KiB · Python
Last changed by
Fix `package_name` resolution when module differs from distribution name (#3582)Rowlando13before adoption7a16b20
History of this fileTake it
The walk stopped after 200 commits: lines older than 0d69b6c point at it.
Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 1–3why, one step back1from __future__ import annotations23import enumAdds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 4–9why, one step back4import os5from itertools import chain67import pytest89import clickMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 10why, one step back10from click._utils import UNSETAdds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 11–209why, one step back111213def test_basic_functionality(runner):14 @click.command()15 def cli():16 """Hello World!"""17 click.echo("I EXECUTED")1819 result = runner.invoke(cli, ["--help"])20 assert not result.exception21 assert "Hello World!" in result.output22 assert "Show this message and exit." in result.output23 assert result.exit_code == 024 assert "I EXECUTED" not in result.output2526 result = runner.invoke(cli, [])27 assert not result.exception28 assert "I EXECUTED" in result.output29 assert result.exit_code == 0303132def test_repr():33 @click.command()34 def command():35 pass3637 @click.group()38 def group():39 pass4041 @group.command()42 def subcommand():43 pass4445 assert repr(command) == "<Command command>"46 assert repr(group) == "<Group group>"47 assert repr(subcommand) == "<Command subcommand>"484950def test_return_values():51 @click.command()52 def cli():53 return 425455 with cli.make_context("foo", []) as ctx:56 rv = cli.invoke(ctx)57 assert rv == 42585960def test_basic_group(runner):61 @click.group()62 def cli():63 """This is the root."""64 click.echo("ROOT EXECUTED")6566 @cli.command()67 def subcommand():68 """This is a subcommand."""69 click.echo("SUBCOMMAND EXECUTED")7071 result = runner.invoke(cli, ["--help"])72 assert not result.exception73 assert "COMMAND [ARGS]..." in result.output74 assert "This is the root" in result.output75 assert "This is a subcommand." in result.output76 assert result.exit_code == 077 assert "ROOT EXECUTED" not in result.output7879 result = runner.invoke(cli, ["subcommand"])80 assert not result.exception81 assert result.exit_code == 082 assert "ROOT EXECUTED" in result.output83 assert "SUBCOMMAND EXECUTED" in result.output848586def test_group_commands_dict(runner):87 """A Group can be built with a dict of commands."""8889 @click.command()90 def sub():91 click.echo("sub", nl=False)9293 cli = click.Group(commands={"other": sub})94 result = runner.invoke(cli, ["other"])95 assert result.output == "sub"969798def test_group_from_list(runner):99 """A Group can be built with a list of commands."""100101 @click.command()102 def sub():103 click.echo("sub", nl=False)104105 cli = click.Group(commands=[sub])106 result = runner.invoke(cli, ["sub"])107 assert result.output == "sub"108109110@pytest.mark.parametrize(111 ("args", "expect"),112 [113 ([], "S:[no value]"),114 (["--s=42"], "S:[42]"),115 (["--s"], "Error: Option '--s' requires an argument."),116 (["--s="], "S:[]"),117 (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"),118 ],119)120def test_string_option(runner, args, expect):121 @click.command()122 @click.option("--s", default="no value")123 def cli(s):124 click.echo(f"S:[{s}]")125126 result = runner.invoke(cli, args)127 assert expect in result.output128129 if expect.startswith("Error:"):130 assert result.exception is not None131 else:132 assert result.exception is None133134135@pytest.mark.parametrize(136 ("args", "expect"),137 [138 ([], "I:[84]"),139 (["--i=23"], "I:[46]"),140 (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."),141 ],142)143def test_int_option(runner, args, expect):144 @click.command()145 @click.option("--i", default=42)146 def cli(i):147 click.echo(f"I:[{i * 2}]")148149 result = runner.invoke(cli, args)150 assert expect in result.output151152 if expect.startswith("Error:"):153 assert result.exception is not None154 else:155 assert result.exception is None156157158@pytest.mark.parametrize(159 ("args", "expect"),160 [161 ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"),162 (163 ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"],164 "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]",165 ),166 (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."),167 ],168)169def test_uuid_option(runner, args, expect):170 @click.command()171 @click.option(172 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID173 )174 def cli(u):175 click.echo(f"U:[{u}]")176177 result = runner.invoke(cli, args)178 assert expect in result.output179180 if expect.startswith("Error:"):181 assert result.exception is not None182 else:183 assert result.exception is None184185186@pytest.mark.parametrize(187 ("args", "expect"),188 [189 ([], "F:[42.0]"),190 ("--f=23.5", "F:[23.5]"),191 ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."),192 ],193)194def test_float_option(runner, args, expect):195 @click.command()196 @click.option("--f", default=42.0)197 def cli(f):198 click.echo(f"F:[{f}]")199200 result = runner.invoke(cli, args)201 assert expect in result.output202203 if expect.startswith("Error:"):204 assert result.exception is not None205 else:206 assert result.exception is None207208209@pytest.mark.parametrize(Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 210–224why, one step back210 ("args", "default", "expect"),211 [212 (["--on"], True, True),213 (["--on"], False, True),214 (["--on"], None, True),215 (["--on"], UNSET, True),216 (["--off"], True, False),217 (["--off"], False, False),218 (["--off"], None, False),219 (["--off"], UNSET, False),220 ([], True, True),221 ([], False, False),222 ([], None, None),223 ([], UNSET, False),224 ],Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
line 225why, one step back225)Merge branch 'main' into stableDavid Lordbefore adoption81a482f
line 226why, one step back226def test_boolean_switch(runner, args, default, expect):Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 227–235why, one step back227 @click.command()228 @click.option("--on/--off", default=default)229 def cli(on):230 return on231232 result = runner.invoke(cli, args, standalone_mode=False)233 assert result.return_value is expect234235Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 236–242why, one step back236@pytest.mark.parametrize(237 ("default", "args", "expect"),238 (239 (True, ["--f"], True),240 (True, [], True),241 (False, ["--f"], True),242 (False, [], False),Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 243–246why, one step back243 # Boolean flags have a 3-states logic.244 # See: https://github.com/pallets/click/issues/3024#issue-3285556668245 (None, ["--f"], True),246 (None, [], None),Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d
lines 247–248why, one step back247 ),248)Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 249–278why, one step back249def test_boolean_flag(runner, default, args, expect):250 @click.command()251 @click.option("--f", is_flag=True, default=default)252 def cli(f):253 return f254255 result = runner.invoke(cli, args, standalone_mode=False)256 assert result.return_value is expect257258259@pytest.mark.parametrize(260 ("value", "expect"),261 chain(262 ((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),263 ((x, "False") for x in ("0", "false", "f", "no", "n", "off")),264 ),265)266def test_boolean_conversion(runner, value, expect):267 @click.command()268 @click.option("--flag", type=bool)269 def cli(flag):270 click.echo(flag, nl=False)271272 result = runner.invoke(cli, ["--flag", value])273 assert result.output == expect274275 result = runner.invoke(cli, ["--flag", value.title()])276 assert result.output == expect277278Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 279–318why, one step back279@pytest.mark.parametrize(280 ("default", "args", "expected"),281 # These test cases are similar to the ones in282 # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.283 (284 # Each option is returning its own flag_value, whatever the default is.285 (True, ["--upper"], "upper"),286 (True, ["--lower"], "lower"),287 (False, ["--upper"], "upper"),288 (False, ["--lower"], "lower"),289 (None, ["--upper"], "upper"),290 (None, ["--lower"], "lower"),291 (UNSET, ["--upper"], "upper"),292 (UNSET, ["--lower"], "lower"),293 # Check that the last option wins when both are specified.294 (True, ["--upper", "--lower"], "lower"),295 (True, ["--lower", "--upper"], "upper"),296 # Check that the default is returned as-is when no option is specified.297 ("upper", [], "upper"),298 ("lower", [], "lower"),299 ("uPPer", [], "uPPer"),300 ("lOwEr", [], "lOwEr"),301 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),302 (None, [], None),303 # Default is normalized to None if it is UNSET.304 (UNSET, [], None),305 # Special case: if default=True and flag_value is set, the value returned is the306 # flag_value, not the True Python value itself.307 (True, [], "upper"),308 # Non-string defaults are process as strings by the default Parameter's type.309 (False, [], "False"),310 (42, [], "42"),311 (12.3, [], "12.3"),312 ),313)314def test_flag_value_dual_options(runner, default, args, expected):315 """Check how default is processed when options compete for the same variable name.316317 Covers the regression reported in318 https://github.com/pallets/click/issues/3024#issuecomment-3146199461Add cross-reference to tests from `test_defaults.py` (#3223)Rowlando13before adoptionfa7f035
lines 319–324why, one step back319320 .. hint::321 Similar to ``test_options.py::test_default_dual_option_callback``.322323 ``test_defaults.py::test_shared_param_prefers_first_default``324 is a smoke-test complement that exercises both default placements.Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 325–336why, one step back325 """326327 @click.command()328 @click.option("--upper", "case", flag_value="upper", default=default)329 @click.option("--lower", "case", flag_value="lower")330 def cli(case):331 click.echo(repr(case), nl=False)332333 result = runner.invoke(cli, args)334 assert result.output == repr(expected)335336Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 337–483why, one step back337def test_file_option(runner):338 @click.command()339 @click.option("--file", type=click.File("w"))340 def input(file):341 file.write("Hello World!\n")342343 @click.command()344 @click.option("--file", type=click.File("r"))345 def output(file):346 click.echo(file.read())347348 with runner.isolated_filesystem():349 result_in = runner.invoke(input, ["--file=example.txt"])350 result_out = runner.invoke(output, ["--file=example.txt"])351352 assert not result_in.exception353 assert result_in.output == ""354 assert not result_out.exception355 assert result_out.output == "Hello World!\n\n"356357358def test_file_lazy_mode(runner):359 do_io = False360361 @click.command()362 @click.option("--file", type=click.File("w"))363 def input(file):364 if do_io:365 file.write("Hello World!\n")366367 @click.command()368 @click.option("--file", type=click.File("r"))369 def output(file):370 pass371372 with runner.isolated_filesystem():373 os.mkdir("example.txt")374375 do_io = True376 result_in = runner.invoke(input, ["--file=example.txt"])377 assert result_in.exit_code == 1378379 do_io = False380 result_in = runner.invoke(input, ["--file=example.txt"])381 assert result_in.exit_code == 0382383 result_out = runner.invoke(output, ["--file=example.txt"])384 assert result_out.exception385386 @click.command()387 @click.option("--file", type=click.File("w", lazy=False))388 def input_non_lazy(file):389 file.write("Hello World!\n")390391 with runner.isolated_filesystem():392 os.mkdir("example.txt")393 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])394 assert result_in.exit_code == 2395 assert "Invalid value for '--file': 'example.txt'" in result_in.output396397398def test_path_option(runner):399 @click.command()400 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))401 def write_to_dir(o):402 with open(os.path.join(o, "foo.txt"), "wb") as f:403 f.write(b"meh\n")404405 with runner.isolated_filesystem():406 os.mkdir("test")407408 result = runner.invoke(write_to_dir, ["-O", "test"])409 assert not result.exception410411 with open("test/foo.txt", "rb") as f:412 assert f.read() == b"meh\n"413414 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])415 assert "is a file" in result.output416417 @click.command()418 @click.option("-f", type=click.Path(exists=True))419 def showtype(f):420 click.echo(f"is_file={os.path.isfile(f)}")421 click.echo(f"is_dir={os.path.isdir(f)}")422423 with runner.isolated_filesystem():424 result = runner.invoke(showtype, ["-f", "xxx"])425 assert "does not exist" in result.output426427 result = runner.invoke(showtype, ["-f", "."])428 assert "is_file=False" in result.output429 assert "is_dir=True" in result.output430431 @click.command()432 @click.option("-f", type=click.Path())433 def exists(f):434 click.echo(f"exists={os.path.exists(f)}")435436 with runner.isolated_filesystem():437 result = runner.invoke(exists, ["-f", "xxx"])438 assert "exists=False" in result.output439440 result = runner.invoke(exists, ["-f", "."])441 assert "exists=True" in result.output442443444def test_choice_option(runner):445 @click.command()446 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))447 def cli(method):448 click.echo(method)449450 result = runner.invoke(cli, ["--method=foo"])451 assert not result.exception452 assert result.output == "foo\n"453454 result = runner.invoke(cli, ["--method=meh"])455 assert result.exit_code == 2456 assert (457 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."458 in result.output459 )460461 result = runner.invoke(cli, ["--help"])462 assert "--method [foo|bar|baz]" in result.output463464465def test_choice_argument(runner):466 @click.command()467 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))468 def cli(method):469 click.echo(method)470471 result = runner.invoke(cli, ["foo"])472 assert not result.exception473 assert result.output == "foo\n"474475 result = runner.invoke(cli, ["meh"])476 assert result.exit_code == 2477 assert (478 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"479 " 'bar', 'baz'." in result.output480 )481482 result = runner.invoke(cli, ["--help"])483 assert "{foo|bar|baz}" in result.outputExpand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 484–550why, one step back484485486def test_choice_argument_enum(runner):487 class MyEnum(str, enum.Enum):488 FOO = "foo-value"489 BAR = "bar-value"490 BAZ = "baz-value"491492 @click.command()493 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))494 def cli(method: MyEnum):495 assert isinstance(method, MyEnum)496 click.echo(method)497498 result = runner.invoke(cli, ["foo"])499 assert result.output == "foo-value\n"500 assert not result.exception501502 result = runner.invoke(cli, ["meh"])503 assert result.exit_code == 2504 assert (505 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"506 " 'bar', 'baz'." in result.output507 )508509 result = runner.invoke(cli, ["--help"])510 assert "{foo|bar|baz}" in result.output511512513def test_choice_argument_custom_type(runner):514 class MyClass:515 def __init__(self, value: str) -> None:516 self.value = value517518 def __str__(self) -> str:519 return self.value520521 @click.command()522 @click.argument(523 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])524 )525 def cli(method: MyClass):526 assert isinstance(method, MyClass)527 click.echo(method)528529 result = runner.invoke(cli, ["foo"])530 assert not result.exception531 assert result.output == "foo\n"532533 result = runner.invoke(cli, ["meh"])534 assert result.exit_code == 2535 assert (536 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"537 " 'bar', 'baz'." in result.output538 )539540 result = runner.invoke(cli, ["--help"])541 assert "{foo|bar|baz}" in result.output542543544def test_choice_argument_none(runner):545 @click.command()546 @click.argument(547 "method", type=click.Choice(["not-none", None], case_sensitive=False)548 )549 def cli(method: str | None):550 assert isinstance(method, str) or method is NoneMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 551why, one step back551 click.echo(repr(method), nl=False)Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 552–554why, one step back552553 result = runner.invoke(cli, ["not-none"])554 assert not result.exceptionMerge branch 'main' into stableDavid Lordbefore adoption81a482f
line 555why, one step back555 assert result.output == repr("not-none")Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
lines 556–557why, one step back556557 result = runner.invoke(cli, ["none"])Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 558–561why, one step back558 assert not result.exception559 assert result.output == repr(None)560561 result = runner.invoke(cli, [])Expand `Choice` token normalization + make generic (#2796)Andreas Backxbefore adoption4ece17a
line 562why, one step back562 assert result.exceptionMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 563–569why, one step back563 assert (564 "Error: Missing argument '{not-none|none}'. "565 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr566 )567568 result = runner.invoke(cli, ["--help"])569 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 570–571why, one step back570571Fix double-bracketing of choices in synopsis (#3578)Rowlando13before adoption09195f6
lines 572–611why, one step back572def test_choice_argument_optional_metavar(runner):573 """Optional Choice arguments reuse the type's brackets instead of doubling.574575 Without this the usage line for a ``Choice`` argument with ``nargs=-1`` or576 ``required=False`` rendered as ``[[a|b|c]]``: one pair from ``Choice`` to577 enumerate values, a second pair from ``Argument`` to mark it optional.578 """579580 @click.command()581 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), nargs=-1)582 def cli_variadic(method):583 pass584585 @click.command()586 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), required=False)587 def cli_optional(method):588 pass589590 variadic = runner.invoke(cli_variadic, ["--help"]).output591 assert "Usage: cli-variadic [OPTIONS] [foo|bar|baz]...\n" in variadic592 assert "[[foo|bar|baz]]" not in variadic593594 optional = runner.invoke(cli_optional, ["--help"]).output595 assert "Usage: cli-optional [OPTIONS] [foo|bar|baz]\n" in optional596 assert "[[foo|bar|baz]]" not in optional597598599def test_datetime_argument_optional_metavar(runner):600 """``DateTime`` arguments behave the same way as ``Choice``."""601602 @click.command()603 @click.argument("when", type=click.DateTime(formats=["%Y-%m-%d"]), required=False)604 def cli(when):605 pass606607 result = runner.invoke(cli, ["--help"])608 assert "Usage: cli [OPTIONS] [%Y-%m-%d]\n" in result.output609 assert "[[%Y-%m-%d]]" not in result.output610611Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 612–781why, one step back612def test_datetime_option_default(runner):613 @click.command()614 @click.option("--start_date", type=click.DateTime())615 def cli(start_date):616 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))617618 result = runner.invoke(cli, ["--start_date=2015-09-29"])619 assert not result.exception620 assert result.output == "2015-09-29T00:00:00\n"621622 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])623 assert not result.exception624 assert result.output == "2015-09-29T09:11:22\n"625626 result = runner.invoke(cli, ["--start_date=2015-09"])627 assert result.exit_code == 2628 assert (629 "Invalid value for '--start_date': '2015-09' does not match the formats"630 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."631 ) in result.output632633 result = runner.invoke(cli, ["--help"])634 assert (635 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output636 )637638639def test_datetime_option_custom(runner):640 @click.command()641 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))642 def cli(start_date):643 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))644645 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])646 assert not result.exception647 assert result.output == "2010-06-05T00:00:00\n"648649650def test_required_option(runner):651 @click.command()652 @click.option("--foo", required=True)653 def cli(foo):654 click.echo(foo)655656 result = runner.invoke(cli, [])657 assert result.exit_code == 2658 assert "Missing option '--foo'" in result.output659660661def test_evaluation_order(runner):662 called = []663664 def memo(ctx, param, value):665 called.append(value)666 return value667668 @click.command()669 @click.option("--missing", default="missing", is_eager=False, callback=memo)670 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)671 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)672 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)673 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)674 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)675 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)676 def cli(**x):677 pass678679 result = runner.invoke(680 cli,681 [682 "--eager-flag2",683 "--eager-flag1",684 "--normal-flag2",685 "--eager-flag3",686 "--normal-flag3",687 "--normal-flag3",688 "--normal-flag1",689 "--normal-flag1",690 ],691 )692 assert not result.exception693 assert called == [694 "eager2",695 "eager1",696 "eager3",697 "normal2",698 "normal3",699 "normal1",700 "missing",701 ]702703704def test_hidden_option(runner):705 @click.command()706 @click.option("--nope", hidden=True)707 def cli(nope):708 click.echo(nope)709710 result = runner.invoke(cli, ["--help"])711 assert result.exit_code == 0712 assert "--nope" not in result.output713714715def test_hidden_command(runner):716 @click.group()717 def cli():718 pass719720 @cli.command(hidden=True)721 def nope():722 pass723724 result = runner.invoke(cli, ["--help"])725 assert result.exit_code == 0726 assert "nope" not in result.output727728729def test_hidden_group(runner):730 @click.group()731 def cli():732 pass733734 @cli.group(hidden=True)735 def subgroup():736 pass737738 @subgroup.command()739 def nope():740 pass741742 result = runner.invoke(cli, ["--help"])743 assert result.exit_code == 0744 assert "subgroup" not in result.output745 assert "nope" not in result.output746747748def test_summary_line(runner):749 @click.group()750 def cli():751 pass752753 @cli.command()754 def cmd():755 """756 Summary line without period757758 Here is a sentence. And here too.759 """760 pass761762 result = runner.invoke(cli, ["--help"])763 assert "Summary line without period" in result.output764 assert "Here is a sentence." not in result.output765766767def test_help_invalid_default(runner):768 cli = click.Command(769 "cli",770 params=[771 click.Option(772 ["-a"],773 type=click.Path(exists=True),774 default="not found",775 show_default=True,776 ),777 ],778 )779 result = runner.invoke(cli, ["--help"])780 assert result.exit_code == 0781 assert "default: not found" in result.outputFix `package_name` resolution when module differs from distribution name (#3582)Rowlando13before adoption7a16b20
lines 782–860why, one step back782783784def test_version_option_resolves_import_name_to_distribution(runner, monkeypatch):785 """When ``package_name`` (detected or passed) is an import name that786 differs from its installed distribution name (``PIL`` vs ``Pillow``),787 ``version_option`` resolves it via ``packages_distributions()`` instead788 of raising ``RuntimeError``.789 """790 import importlib.metadata791792 def fake_version(name):793 if name == "pillow":794 return "10.4.0"795 raise importlib.metadata.PackageNotFoundError(name)796797 monkeypatch.setattr(importlib.metadata, "version", fake_version)798 monkeypatch.setattr(799 importlib.metadata,800 "packages_distributions",801 lambda: {"PIL": ["pillow"]},802 )803804 @click.command()805 @click.version_option(package_name="PIL")806 def cli():807 pass808809 result = runner.invoke(cli, ["--version"], prog_name="imageapp")810 assert result.exit_code == 0811 assert "10.4.0" in result.output812813814def test_version_option_ambiguous_import_name_errors(runner, monkeypatch):815 """When an import name maps to multiple installed distributions, the816 user must disambiguate. The error names the candidates.817 """818 import importlib.metadata819820 def fake_version(name):821 raise importlib.metadata.PackageNotFoundError(name)822823 monkeypatch.setattr(importlib.metadata, "version", fake_version)824 monkeypatch.setattr(825 importlib.metadata,826 "packages_distributions",827 lambda: {"plug": ["foo-plug", "bar-plug"]},828 )829830 @click.command()831 @click.version_option(package_name="plug")832 def cli():833 pass834835 result = runner.invoke(cli, ["--version"])836 assert result.exit_code != 0837 msg = str(result.exception)838 assert "multiple installed distributions" in msg839 assert "foo-plug" in msg840 assert "bar-plug" in msg841842843def test_version_option_unknown_package_errors(runner, monkeypatch):844 """When the name resolves to no distribution, keep the existing error."""845 import importlib.metadata846847 def fake_version(name):848 raise importlib.metadata.PackageNotFoundError(name)849850 monkeypatch.setattr(importlib.metadata, "version", fake_version)851 monkeypatch.setattr(importlib.metadata, "packages_distributions", lambda: {})852853 @click.command()854 @click.version_option(package_name="nonexistent")855 def cli():856 pass857858 result = runner.invoke(cli, ["--version"])859 assert result.exit_code != 0860 assert "not installed" in str(result.exception)