test_basic.py
This file
Path
tests/test_basic.py
986 lines · 28.0 KiB · Python
Last changed by
Split out types tests. (#3850)Rowlando13before adoption7ecc8d7
History of this fileTake it
1from __future__ import annotations23import enum4import os56import pytest78import click9from click._utils import UNSET101112def 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 == 0293031@pytest.mark.parametrize(32 ("help_names", "params", "args", "expected_output"),33 [34 (["--help"], [], [], "\n"),35 (["--help"], [click.Argument(["help"])], ["value"], "value\n"),36 (37 ["--help"],38 [click.Option(["--assist", "help"])],39 ["--assist", "value"],40 "value\n",41 ),42 (["--man"], [click.Option(["--foo", "man"])], ["--foo", "value"], "value\n"),43 ],44 ids=["no-collision", "argument", "option", "custom-flags"],45)46def test_param_named_help(runner, help_names, params, args, expected_output):47 """User parameters never clash with the automatic help option, which48 stores its value under the reserved ``_click_default_help`` name.4950 https://github.com/pallets/click/issues/281951 """52 cli = click.Command(53 "cli",54 context_settings={"help_option_names": help_names},55 params=params,56 callback=lambda **kwargs: click.echo(next(iter(kwargs.values()), None)),57 )5859 ctx = click.Context(cli, help_option_names=help_names)60 help_option = cli.get_help_option(ctx)61 assert help_option is not None62 assert help_option.name == "_click_default_help"6364 result = runner.invoke(cli, args)65 assert result.output == expected_output66 assert result.exit_code == 06768 result = runner.invoke(cli, [help_names[0]])69 assert "Show this message and exit." in result.output70 assert result.exit_code == 0717273def test_param_squatting_help_option_name(runner):74 """Claiming the reserved storage name of the automatic help option75 triggers a warning.76 """7778 @click.command()79 @click.argument("_click_default_help")80 def cli(_click_default_help):81 click.echo(_click_default_help)8283 with pytest.warns(UserWarning, match="reserved for the automatic help option"):84 result = runner.invoke(cli, ["value"])8586 # The collision still breaks parsing, but no longer silently.87 assert result.exit_code == 2888990def test_option_reusing_help_flag(runner):91 """An option reusing the ``--help`` flag replaces the automatic help92 option entirely.9394 https://github.com/pallets/click/issues/281995 """9697 @click.command()98 @click.option("--help", default="default value")99 def cli(help):100 click.echo(help)101102 assert cli.get_help_option(click.Context(cli)) is None103104 result = runner.invoke(cli, [])105 assert result.output == "default value\n"106 assert result.exit_code == 0107108 result = runner.invoke(cli, ["--help", "custom"])109 assert result.output == "custom\n"110 assert result.exit_code == 0111112113def test_repr():114 @click.command()115 def command():116 pass117118 @click.group()119 def group():120 pass121122 @group.command()123 def subcommand():124 pass125126 assert repr(command) == "<Command command>"127 assert repr(group) == "<Group group>"128 assert repr(subcommand) == "<Command subcommand>"129130131def test_return_values():132 @click.command()133 def cli():134 return 42135136 with cli.make_context("foo", []) as ctx:137 rv = cli.invoke(ctx)138 assert rv == 42139140141def test_basic_group(runner):142 @click.group()143 def cli():144 """This is the root."""145 click.echo("ROOT EXECUTED")146147 @cli.command()148 def subcommand():149 """This is a subcommand."""150 click.echo("SUBCOMMAND EXECUTED")151152 result = runner.invoke(cli, ["--help"])153 assert not result.exception154 assert "COMMAND [ARGS]..." in result.output155 assert "This is the root" in result.output156 assert "This is a subcommand." in result.output157 assert result.exit_code == 0158 assert "ROOT EXECUTED" not in result.output159160 result = runner.invoke(cli, ["subcommand"])161 assert not result.exception162 assert result.exit_code == 0163 assert "ROOT EXECUTED" in result.output164 assert "SUBCOMMAND EXECUTED" in result.output165166167def test_group_commands_dict(runner):168 """A Group can be built with a dict of commands."""169170 @click.command()171 def sub():172 click.echo("sub", nl=False)173174 cli = click.Group(commands={"other": sub})175 result = runner.invoke(cli, ["other"])176 assert result.output == "sub"177178179def test_group_from_list(runner):180 """A Group can be built with a list of commands."""181182 @click.command()183 def sub():184 click.echo("sub", nl=False)185186 cli = click.Group(commands=[sub])187 result = runner.invoke(cli, ["sub"])188 assert result.output == "sub"189190191@pytest.mark.parametrize(192 ("args", "expect"),193 [194 ([], "S:[no value]"),195 (["--s=42"], "S:[42]"),196 (["--s"], "Error: Option '--s' requires an argument."),197 (["--s="], "S:[]"),198 (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"),199 ],200)201def test_string_option(runner, args, expect):202 @click.command()203 @click.option("--s", default="no value")204 def cli(s):205 click.echo(f"S:[{s}]")206207 result = runner.invoke(cli, args)208 assert expect in result.output209210 if expect.startswith("Error:"):211 assert result.exception is not None212 else:213 assert result.exception is None214215216@pytest.mark.parametrize(217 ("args", "expect"),218 [219 ([], "I:[84]"),220 (["--i=23"], "I:[46]"),221 (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."),222 ],223)224def test_int_option(runner, args, expect):225 @click.command()226 @click.option("--i", default=42)227 def cli(i):228 click.echo(f"I:[{i * 2}]")229230 result = runner.invoke(cli, args)231 assert expect in result.output232233 if expect.startswith("Error:"):234 assert result.exception is not None235 else:236 assert result.exception is None237238239@pytest.mark.parametrize(240 ("args", "expect"),241 [242 ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"),243 (244 ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"],245 "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]",246 ),247 (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."),248 ],249)250def test_uuid_option(runner, args, expect):251 @click.command()252 @click.option(253 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID254 )255 def cli(u):256 click.echo(f"U:[{u}]")257258 result = runner.invoke(cli, args)259 assert expect in result.output260261 if expect.startswith("Error:"):262 assert result.exception is not None263 else:264 assert result.exception is None265266267@pytest.mark.parametrize(268 ("args", "expect"),269 [270 ([], "F:[42.0]"),271 ("--f=23.5", "F:[23.5]"),272 ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."),273 ],274)275def test_float_option(runner, args, expect):276 @click.command()277 @click.option("--f", default=42.0)278 def cli(f):279 click.echo(f"F:[{f}]")280281 result = runner.invoke(cli, args)282 assert expect in result.output283284 if expect.startswith("Error:"):285 assert result.exception is not None286 else:287 assert result.exception is None288289290@pytest.mark.parametrize(291 ("args", "default", "expect"),292 [293 (["--on"], True, True),294 (["--on"], False, True),295 (["--on"], None, True),296 (["--on"], UNSET, True),297 (["--off"], True, False),298 (["--off"], False, False),299 (["--off"], None, False),300 (["--off"], UNSET, False),301 ([], True, True),302 ([], False, False),303 ([], None, None),304 ([], UNSET, False),305 ],306)307def test_boolean_switch(runner, args, default, expect):308 @click.command()309 @click.option("--on/--off", default=default)310 def cli(on):311 return on312313 result = runner.invoke(cli, args, standalone_mode=False)314 assert result.return_value is expect315316317@pytest.mark.parametrize(318 ("default", "args", "expect"),319 (320 (True, ["--f"], True),321 (True, [], True),322 (False, ["--f"], True),323 (False, [], False),324 # Boolean flags have a 3-states logic.325 # See: https://github.com/pallets/click/issues/3024#issue-3285556668326 (None, ["--f"], True),327 (None, [], None),328 ),329)330def test_boolean_flag(runner, default, args, expect):331 @click.command()332 @click.option("--f", is_flag=True, default=default)333 def cli(f):334 return f335336 result = runner.invoke(cli, args, standalone_mode=False)337 assert result.return_value is expect338339340@pytest.mark.parametrize(341 ("value", "expect"),342 [343 *((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),344 *((x, "False") for x in ("0", "false", "f", "no", "n", "off")),345 ],346)347def test_boolean_conversion(runner, value, expect):348 @click.command()349 @click.option("--flag", type=bool)350 def cli(flag):351 click.echo(flag, nl=False)352353 result = runner.invoke(cli, ["--flag", value])354 assert result.output == expect355356 result = runner.invoke(cli, ["--flag", value.title()])357 assert result.output == expect358359360@pytest.mark.parametrize(361 ("default", "args", "expected"),362 # These test cases are similar to the ones in363 # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.364 (365 # Each option is returning its own flag_value, whatever the default is.366 (True, ["--upper"], "upper"),367 (True, ["--lower"], "lower"),368 (False, ["--upper"], "upper"),369 (False, ["--lower"], "lower"),370 (None, ["--upper"], "upper"),371 (None, ["--lower"], "lower"),372 (UNSET, ["--upper"], "upper"),373 (UNSET, ["--lower"], "lower"),374 # Check that the last option wins when both are specified.375 (True, ["--upper", "--lower"], "lower"),376 (True, ["--lower", "--upper"], "upper"),377 # Check that the default is returned as-is when no option is specified.378 ("upper", [], "upper"),379 ("lower", [], "lower"),380 ("uPPer", [], "uPPer"),381 ("lOwEr", [], "lOwEr"),382 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),383 (None, [], None),384 # Default is normalized to None if it is UNSET.385 (UNSET, [], None),386 # Special case: if default=True and flag_value is set, the value returned is the387 # flag_value, not the True Python value itself.388 (True, [], "upper"),389 # Non-string defaults are process as strings by the default Parameter's type.390 (False, [], "False"),391 (42, [], "42"),392 (12.3, [], "12.3"),393 ),394)395def test_flag_value_dual_options(runner, default, args, expected):396 """Check how default is processed when options compete for the same variable name.397398 Covers the regression reported in399 https://github.com/pallets/click/issues/3024#issuecomment-3146199461400401 .. hint::402 Similar to ``test_options.py::test_default_dual_option_callback``.403404 ``test_defaults.py::test_shared_param_prefers_first_default``405 is a smoke-test complement that exercises both default placements.406 """407408 @click.command()409 @click.option("--upper", "case", flag_value="upper", default=default)410 @click.option("--lower", "case", flag_value="lower")411 def cli(case):412 click.echo(repr(case), nl=False)413414 result = runner.invoke(cli, args)415 assert result.output == repr(expected)416417418def test_file_option(runner, tmp_path):419 @click.command()420 @click.option("--file", type=click.File("w"))421 def input(file):422 file.write("Hello World!\n")423424 @click.command()425 @click.option("--file", type=click.File("r"))426 def output(file):427 click.echo(file.read())428429 example = tmp_path / "example.txt"430 result_in = runner.invoke(input, [f"--file={example}"])431 result_out = runner.invoke(output, [f"--file={example}"])432433 assert not result_in.exception434 assert result_in.output == ""435 assert not result_out.exception436 assert result_out.output == "Hello World!\n\n"437438439def test_file_lazy_mode(runner, tmp_path):440 do_io = False441442 @click.command()443 @click.option("--file", type=click.File("w"))444 def input(file):445 if do_io:446 file.write("Hello World!\n")447448 @click.command()449 @click.option("--file", type=click.File("r"))450 def output(file):451 pass452453 example = tmp_path / "example.txt"454 example.mkdir()455456 do_io = True457 result_in = runner.invoke(input, [f"--file={example}"])458 assert result_in.exit_code == 1459460 do_io = False461 result_in = runner.invoke(input, [f"--file={example}"])462 assert result_in.exit_code == 0463464 result_out = runner.invoke(output, [f"--file={example}"])465 assert result_out.exception466467 @click.command()468 @click.option("--file", type=click.File("w", lazy=False))469 def input_non_lazy(file):470 file.write("Hello World!\n")471472 non_lazy = tmp_path / "non_lazy.txt"473 non_lazy.mkdir()474 result_in = runner.invoke(input_non_lazy, [f"--file={non_lazy}"])475 assert result_in.exit_code == 2476 assert f"Invalid value for '--file': '{non_lazy}'" in result_in.output477478479def test_path_option(runner, tmp_path):480 @click.command()481 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))482 def write_to_dir(o):483 with open(os.path.join(o, "foo.txt"), "wb") as f:484 f.write(b"meh\n")485486 test_dir = tmp_path / "test"487 test_dir.mkdir()488489 result = runner.invoke(write_to_dir, ["-O", str(test_dir)])490 assert not result.exception491492 with open(test_dir / "foo.txt", "rb") as f:493 assert f.read() == b"meh\n"494495 result = runner.invoke(write_to_dir, ["-O", str(test_dir / "foo.txt")])496 assert "is a file" in result.output497498 @click.command()499 @click.option("-f", type=click.Path(exists=True))500 def showtype(f):501 click.echo(f"is_file={os.path.isfile(f)}")502 click.echo(f"is_dir={os.path.isdir(f)}")503504 result = runner.invoke(showtype, ["-f", str(tmp_path / "xxx")])505 assert "does not exist" in result.output506507 result = runner.invoke(showtype, ["-f", str(tmp_path)])508 assert "is_file=False" in result.output509 assert "is_dir=True" in result.output510511 @click.command()512 @click.option("-f", type=click.Path())513 def exists(f):514 click.echo(f"exists={os.path.exists(f)}")515516 result = runner.invoke(exists, ["-f", str(tmp_path / "xxx")])517 assert "exists=False" in result.output518519 result = runner.invoke(exists, ["-f", str(tmp_path)])520 assert "exists=True" in result.output521522523def test_choice_option(runner):524 @click.command()525 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))526 def cli(method):527 click.echo(method)528529 result = runner.invoke(cli, ["--method=foo"])530 assert not result.exception531 assert result.output == "foo\n"532533 result = runner.invoke(cli, ["--method=meh"])534 assert result.exit_code == 2535 assert (536 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."537 in result.output538 )539540 result = runner.invoke(cli, ["--help"])541 assert "--method [foo|bar|baz]" in result.output542543544def test_choice_argument(runner):545 @click.command()546 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))547 def cli(method):548 click.echo(method)549550 result = runner.invoke(cli, ["foo"])551 assert not result.exception552 assert result.output == "foo\n"553554 result = runner.invoke(cli, ["meh"])555 assert result.exit_code == 2556 assert (557 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"558 " 'bar', 'baz'." in result.output559 )560561 result = runner.invoke(cli, ["--help"])562 assert "{foo|bar|baz}" in result.output563564565def test_choice_argument_enum(runner):566 class MyEnum(str, enum.Enum):567 FOO = "foo-value"568 BAR = "bar-value"569 BAZ = "baz-value"570571 @click.command()572 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))573 def cli(method: MyEnum):574 assert isinstance(method, MyEnum)575 click.echo(method)576577 result = runner.invoke(cli, ["foo"])578 assert result.output == "foo-value\n"579 assert not result.exception580581 result = runner.invoke(cli, ["meh"])582 assert result.exit_code == 2583 assert (584 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"585 " 'bar', 'baz'." in result.output586 )587588 result = runner.invoke(cli, ["--help"])589 assert "{foo|bar|baz}" in result.output590591592def test_choice_argument_custom_type(runner):593 class MyClass:594 def __init__(self, value: str) -> None:595 self.value = value596597 def __str__(self) -> str:598 return self.value599600 @click.command()601 @click.argument(602 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])603 )604 def cli(method: MyClass):605 assert isinstance(method, MyClass)606 click.echo(method)607608 result = runner.invoke(cli, ["foo"])609 assert not result.exception610 assert result.output == "foo\n"611612 result = runner.invoke(cli, ["meh"])613 assert result.exit_code == 2614 assert (615 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"616 " 'bar', 'baz'." in result.output617 )618619 result = runner.invoke(cli, ["--help"])620 assert "{foo|bar|baz}" in result.output621622623def test_choice_argument_none(runner):624 @click.command()625 @click.argument(626 "method", type=click.Choice(["not-none", None], case_sensitive=False)627 )628 def cli(method: str | None):629 assert isinstance(method, str) or method is None630 click.echo(repr(method), nl=False)631632 result = runner.invoke(cli, ["not-none"])633 assert not result.exception634 assert result.output == repr("not-none")635636 result = runner.invoke(cli, ["none"])637 assert not result.exception638 assert result.output == repr(None)639640 result = runner.invoke(cli, [])641 assert result.exception642 assert (643 "Error: Missing argument '{not-none|none}'. "644 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr645 )646647 result = runner.invoke(cli, ["--help"])648 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")649650651def test_choice_argument_optional_metavar(runner):652 """Optional Choice arguments reuse the type's brackets instead of doubling.653654 Without this the usage line for a ``Choice`` argument with ``nargs=-1`` or655 ``required=False`` rendered as ``[[a|b|c]]``: one pair from ``Choice`` to656 enumerate values, a second pair from ``Argument`` to mark it optional.657 """658659 @click.command()660 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), nargs=-1)661 def cli_variadic(method):662 pass663664 @click.command()665 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), required=False)666 def cli_optional(method):667 pass668669 variadic = runner.invoke(cli_variadic, ["--help"]).output670 assert "Usage: cli-variadic [OPTIONS] [foo|bar|baz]...\n" in variadic671 assert "[[foo|bar|baz]]" not in variadic672673 optional = runner.invoke(cli_optional, ["--help"]).output674 assert "Usage: cli-optional [OPTIONS] [foo|bar|baz]\n" in optional675 assert "[[foo|bar|baz]]" not in optional676677678def test_datetime_argument_optional_metavar(runner):679 """``DateTime`` arguments behave the same way as ``Choice``."""680681 @click.command()682 @click.argument("when", type=click.DateTime(formats=["%Y-%m-%d"]), required=False)683 def cli(when):684 pass685686 result = runner.invoke(cli, ["--help"])687 assert "Usage: cli [OPTIONS] [%Y-%m-%d]\n" in result.output688 assert "[[%Y-%m-%d]]" not in result.output689690691def test_datetime_option_default(runner):692 @click.command()693 @click.option("--start_date", type=click.DateTime())694 def cli(start_date):695 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))696697 result = runner.invoke(cli, ["--start_date=2015-09-29"])698 assert not result.exception699 assert result.output == "2015-09-29T00:00:00\n"700701 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])702 assert not result.exception703 assert result.output == "2015-09-29T09:11:22\n"704705 result = runner.invoke(cli, ["--start_date=2015-09"])706 assert result.exit_code == 2707 assert (708 "Invalid value for '--start_date': '2015-09' does not match the formats"709 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."710 ) in result.output711712 result = runner.invoke(cli, ["--help"])713 assert (714 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output715 )716717718def test_datetime_option_custom(runner):719 @click.command()720 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))721 def cli(start_date):722 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))723724 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])725 assert not result.exception726 assert result.output == "2010-06-05T00:00:00\n"727728729def test_required_option(runner):730 @click.command()731 @click.option("--foo", required=True)732 def cli(foo):733 click.echo(foo)734735 result = runner.invoke(cli, [])736 assert result.exit_code == 2737 assert "Missing option '--foo'" in result.output738739740def test_evaluation_order(runner):741 called = []742743 def memo(ctx, param, value):744 called.append(value)745 return value746747 @click.command()748 @click.option("--missing", default="missing", is_eager=False, callback=memo)749 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)750 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)751 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)752 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)753 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)754 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)755 def cli(**x):756 pass757758 result = runner.invoke(759 cli,760 [761 "--eager-flag2",762 "--eager-flag1",763 "--normal-flag2",764 "--eager-flag3",765 "--normal-flag3",766 "--normal-flag3",767 "--normal-flag1",768 "--normal-flag1",769 ],770 )771 assert not result.exception772 assert called == [773 "eager2",774 "eager1",775 "eager3",776 "normal2",777 "normal3",778 "normal1",779 "missing",780 ]781782783def test_hidden_option(runner):784 @click.command()785 @click.option("--nope", hidden=True)786 def cli(nope):787 click.echo(nope)788789 result = runner.invoke(cli, ["--help"])790 assert result.exit_code == 0791 assert "--nope" not in result.output792793794def test_hidden_command(runner):795 @click.group()796 def cli():797 pass798799 @cli.command(hidden=True)800 def nope():801 pass802803 result = runner.invoke(cli, ["--help"])804 assert result.exit_code == 0805 assert "nope" not in result.output806807808def test_hidden_group(runner):809 @click.group()810 def cli():811 pass812813 @cli.group(hidden=True)814 def subgroup():815 pass816817 @subgroup.command()818 def nope():819 pass820821 result = runner.invoke(cli, ["--help"])822 assert result.exit_code == 0823 assert "subgroup" not in result.output824 assert "nope" not in result.output825826827def test_summary_line(runner):828 @click.group()829 def cli():830 pass831832 @cli.command()833 def cmd():834 """835 Summary line without period836837 Here is a sentence. And here too.838 """839 pass840841 result = runner.invoke(cli, ["--help"])842 assert "Summary line without period" in result.output843 assert "Here is a sentence." not in result.output844845846def test_help_invalid_default(runner):847 cli = click.Command(848 "cli",849 params=[850 click.Option(851 ["-a"],852 type=click.Path(exists=True),853 default="not found",854 show_default=True,855 ),856 ],857 )858 result = runner.invoke(cli, ["--help"])859 assert result.exit_code == 0860 assert "default: not found" in result.output861862863def test_version_option_resolves_import_name_to_distribution(runner, monkeypatch):864 """When ``package_name`` (detected or passed) is an import name that865 differs from its installed distribution name (``PIL`` vs ``Pillow``),866 ``version_option`` resolves it via ``packages_distributions()`` instead867 of raising ``RuntimeError``.868 """869 import importlib.metadata870871 def fake_version(name):872 if name == "pillow":873 return "10.4.0"874 raise importlib.metadata.PackageNotFoundError(name)875876 monkeypatch.setattr(importlib.metadata, "version", fake_version)877 monkeypatch.setattr(878 importlib.metadata,879 "packages_distributions",880 lambda: {"PIL": ["pillow"]},881 )882883 @click.command()884 @click.version_option(package_name="PIL")885 def cli():886 pass887888 result = runner.invoke(cli, ["--version"], prog_name="imageapp")889 assert result.exit_code == 0890 assert "10.4.0" in result.output891892893def test_version_option_ambiguous_import_name_errors(runner, monkeypatch):894 """When an import name maps to multiple installed distributions, the895 user must disambiguate. The error names the candidates.896 """897 import importlib.metadata898899 def fake_version(name):900 raise importlib.metadata.PackageNotFoundError(name)901902 monkeypatch.setattr(importlib.metadata, "version", fake_version)903 monkeypatch.setattr(904 importlib.metadata,905 "packages_distributions",906 lambda: {"plug": ["foo-plug", "bar-plug"]},907 )908909 @click.command()910 @click.version_option(package_name="plug")911 def cli():912 pass913914 result = runner.invoke(cli, ["--version"])915 assert result.exit_code != 0916 msg = str(result.exception)917 assert "multiple installed distributions" in msg918 assert "foo-plug" in msg919 assert "bar-plug" in msg920921922def test_version_option_unknown_package_errors(runner, monkeypatch):923 """When the name resolves to no distribution, keep the existing error."""924 import importlib.metadata925926 def fake_version(name):927 raise importlib.metadata.PackageNotFoundError(name)928929 monkeypatch.setattr(importlib.metadata, "version", fake_version)930 monkeypatch.setattr(importlib.metadata, "packages_distributions", lambda: {})931932 @click.command()933 @click.version_option(package_name="nonexistent")934 def cli():935 pass936937 result = runner.invoke(cli, ["--version"])938 assert result.exit_code != 0939 assert "not installed" in str(result.exception)940941942@pytest.mark.parametrize("args", [["--version"], ["-V"]])943def test_custom_version_option(runner, args):944 @click.command()945 @click.custom_version_option(lambda ctx: "custom 9.9.9", "-V", "--version")946 def cli():947 pass948949 result = runner.invoke(cli, args)950 assert result.exit_code == 0951 assert result.output == "custom 9.9.9\n"952953954def test_custom_version_option_receives_context(runner):955 @click.command()956 @click.custom_version_option(lambda ctx: f"{ctx.info_name} 1.0")957 def cli():958 pass959960 result = runner.invoke(cli, ["--version"], prog_name="mytool")961 assert result.exit_code == 0962 assert result.output == "mytool 1.0\n"963964965@pytest.mark.parametrize(966 ("nargs", "multiple", "default", "expect"),967 [968 (2, False, None, None),969 (2, False, (None, None), (None, None)),970 (None, True, None, ()),971 (None, True, (None, None), (None, None)),972 (2, True, None, ()),973 (2, True, [(None, None)], ((None, None),)),974 (-1, None, None, ()),975 ],976)977def test_cast_multi_default(runner, nargs, multiple, default, expect):978 if nargs == -1:979 param = click.Argument(["a"], nargs=nargs, default=default)980 else:981 param = click.Option(["-a"], nargs=nargs, multiple=multiple, default=default)982983 cli = click.Command("cli", params=[param], callback=lambda a: a)984 result = runner.invoke(cli, standalone_mode=False)985 assert result.exception is None986 assert result.return_value == expect