Skip to content
Myr

test_basic.py

This file

Path

tests/test_basic.py

964 lines · 27.3 KiB · Python

Last changed by

Revert "Deprecate `isolated_filesystem` and document its limits"Kevin Deldyckebefore adoption8ee83dd

History of this file

Take 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):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    with runner.isolated_filesystem():430        result_in = runner.invoke(input, ["--file=example.txt"])431        result_out = runner.invoke(output, ["--file=example.txt"])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):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    with runner.isolated_filesystem():454        os.mkdir("example.txt")455456        do_io = True457        result_in = runner.invoke(input, ["--file=example.txt"])458        assert result_in.exit_code == 1459460        do_io = False461        result_in = runner.invoke(input, ["--file=example.txt"])462        assert result_in.exit_code == 0463464        result_out = runner.invoke(output, ["--file=example.txt"])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    with runner.isolated_filesystem():473        os.mkdir("example.txt")474        result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])475        assert result_in.exit_code == 2476        assert "Invalid value for '--file': 'example.txt'" in result_in.output477478479def test_path_option(runner):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    with runner.isolated_filesystem():487        os.mkdir("test")488489        result = runner.invoke(write_to_dir, ["-O", "test"])490        assert not result.exception491492        with open("test/foo.txt", "rb") as f:493            assert f.read() == b"meh\n"494495        result = runner.invoke(write_to_dir, ["-O", "test/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    with runner.isolated_filesystem():505        result = runner.invoke(showtype, ["-f", "xxx"])506        assert "does not exist" in result.output507508        result = runner.invoke(showtype, ["-f", "."])509        assert "is_file=False" in result.output510        assert "is_dir=True" in result.output511512    @click.command()513    @click.option("-f", type=click.Path())514    def exists(f):515        click.echo(f"exists={os.path.exists(f)}")516517    with runner.isolated_filesystem():518        result = runner.invoke(exists, ["-f", "xxx"])519        assert "exists=False" in result.output520521        result = runner.invoke(exists, ["-f", "."])522        assert "exists=True" in result.output523524525def test_choice_option(runner):526    @click.command()527    @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))528    def cli(method):529        click.echo(method)530531    result = runner.invoke(cli, ["--method=foo"])532    assert not result.exception533    assert result.output == "foo\n"534535    result = runner.invoke(cli, ["--method=meh"])536    assert result.exit_code == 2537    assert (538        "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."539        in result.output540    )541542    result = runner.invoke(cli, ["--help"])543    assert "--method [foo|bar|baz]" in result.output544545546def test_choice_argument(runner):547    @click.command()548    @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))549    def cli(method):550        click.echo(method)551552    result = runner.invoke(cli, ["foo"])553    assert not result.exception554    assert result.output == "foo\n"555556    result = runner.invoke(cli, ["meh"])557    assert result.exit_code == 2558    assert (559        "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"560        " 'bar', 'baz'." in result.output561    )562563    result = runner.invoke(cli, ["--help"])564    assert "{foo|bar|baz}" in result.output565566567def test_choice_argument_enum(runner):568    class MyEnum(str, enum.Enum):569        FOO = "foo-value"570        BAR = "bar-value"571        BAZ = "baz-value"572573    @click.command()574    @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))575    def cli(method: MyEnum):576        assert isinstance(method, MyEnum)577        click.echo(method)578579    result = runner.invoke(cli, ["foo"])580    assert result.output == "foo-value\n"581    assert not result.exception582583    result = runner.invoke(cli, ["meh"])584    assert result.exit_code == 2585    assert (586        "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"587        " 'bar', 'baz'." in result.output588    )589590    result = runner.invoke(cli, ["--help"])591    assert "{foo|bar|baz}" in result.output592593594def test_choice_argument_custom_type(runner):595    class MyClass:596        def __init__(self, value: str) -> None:597            self.value = value598599        def __str__(self) -> str:600            return self.value601602    @click.command()603    @click.argument(604        "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])605    )606    def cli(method: MyClass):607        assert isinstance(method, MyClass)608        click.echo(method)609610    result = runner.invoke(cli, ["foo"])611    assert not result.exception612    assert result.output == "foo\n"613614    result = runner.invoke(cli, ["meh"])615    assert result.exit_code == 2616    assert (617        "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"618        " 'bar', 'baz'." in result.output619    )620621    result = runner.invoke(cli, ["--help"])622    assert "{foo|bar|baz}" in result.output623624625def test_choice_argument_none(runner):626    @click.command()627    @click.argument(628        "method", type=click.Choice(["not-none", None], case_sensitive=False)629    )630    def cli(method: str | None):631        assert isinstance(method, str) or method is None632        click.echo(repr(method), nl=False)633634    result = runner.invoke(cli, ["not-none"])635    assert not result.exception636    assert result.output == repr("not-none")637638    result = runner.invoke(cli, ["none"])639    assert not result.exception640    assert result.output == repr(None)641642    result = runner.invoke(cli, [])643    assert result.exception644    assert (645        "Error: Missing argument '{not-none|none}'. "646        "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr647    )648649    result = runner.invoke(cli, ["--help"])650    assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")651652653def test_choice_argument_optional_metavar(runner):654    """Optional Choice arguments reuse the type's brackets instead of doubling.655656    Without this the usage line for a ``Choice`` argument with ``nargs=-1`` or657    ``required=False`` rendered as ``[[a|b|c]]``: one pair from ``Choice`` to658    enumerate values, a second pair from ``Argument`` to mark it optional.659    """660661    @click.command()662    @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), nargs=-1)663    def cli_variadic(method):664        pass665666    @click.command()667    @click.argument("method", type=click.Choice(["foo", "bar", "baz"]), required=False)668    def cli_optional(method):669        pass670671    variadic = runner.invoke(cli_variadic, ["--help"]).output672    assert "Usage: cli-variadic [OPTIONS] [foo|bar|baz]...\n" in variadic673    assert "[[foo|bar|baz]]" not in variadic674675    optional = runner.invoke(cli_optional, ["--help"]).output676    assert "Usage: cli-optional [OPTIONS] [foo|bar|baz]\n" in optional677    assert "[[foo|bar|baz]]" not in optional678679680def test_datetime_argument_optional_metavar(runner):681    """``DateTime`` arguments behave the same way as ``Choice``."""682683    @click.command()684    @click.argument("when", type=click.DateTime(formats=["%Y-%m-%d"]), required=False)685    def cli(when):686        pass687688    result = runner.invoke(cli, ["--help"])689    assert "Usage: cli [OPTIONS] [%Y-%m-%d]\n" in result.output690    assert "[[%Y-%m-%d]]" not in result.output691692693def test_datetime_option_default(runner):694    @click.command()695    @click.option("--start_date", type=click.DateTime())696    def cli(start_date):697        click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))698699    result = runner.invoke(cli, ["--start_date=2015-09-29"])700    assert not result.exception701    assert result.output == "2015-09-29T00:00:00\n"702703    result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])704    assert not result.exception705    assert result.output == "2015-09-29T09:11:22\n"706707    result = runner.invoke(cli, ["--start_date=2015-09"])708    assert result.exit_code == 2709    assert (710        "Invalid value for '--start_date': '2015-09' does not match the formats"711        " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."712    ) in result.output713714    result = runner.invoke(cli, ["--help"])715    assert (716        "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output717    )718719720def test_datetime_option_custom(runner):721    @click.command()722    @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))723    def cli(start_date):724        click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))725726    result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])727    assert not result.exception728    assert result.output == "2010-06-05T00:00:00\n"729730731def test_required_option(runner):732    @click.command()733    @click.option("--foo", required=True)734    def cli(foo):735        click.echo(foo)736737    result = runner.invoke(cli, [])738    assert result.exit_code == 2739    assert "Missing option '--foo'" in result.output740741742def test_evaluation_order(runner):743    called = []744745    def memo(ctx, param, value):746        called.append(value)747        return value748749    @click.command()750    @click.option("--missing", default="missing", is_eager=False, callback=memo)751    @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)752    @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)753    @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)754    @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)755    @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)756    @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)757    def cli(**x):758        pass759760    result = runner.invoke(761        cli,762        [763            "--eager-flag2",764            "--eager-flag1",765            "--normal-flag2",766            "--eager-flag3",767            "--normal-flag3",768            "--normal-flag3",769            "--normal-flag1",770            "--normal-flag1",771        ],772    )773    assert not result.exception774    assert called == [775        "eager2",776        "eager1",777        "eager3",778        "normal2",779        "normal3",780        "normal1",781        "missing",782    ]783784785def test_hidden_option(runner):786    @click.command()787    @click.option("--nope", hidden=True)788    def cli(nope):789        click.echo(nope)790791    result = runner.invoke(cli, ["--help"])792    assert result.exit_code == 0793    assert "--nope" not in result.output794795796def test_hidden_command(runner):797    @click.group()798    def cli():799        pass800801    @cli.command(hidden=True)802    def nope():803        pass804805    result = runner.invoke(cli, ["--help"])806    assert result.exit_code == 0807    assert "nope" not in result.output808809810def test_hidden_group(runner):811    @click.group()812    def cli():813        pass814815    @cli.group(hidden=True)816    def subgroup():817        pass818819    @subgroup.command()820    def nope():821        pass822823    result = runner.invoke(cli, ["--help"])824    assert result.exit_code == 0825    assert "subgroup" not in result.output826    assert "nope" not in result.output827828829def test_summary_line(runner):830    @click.group()831    def cli():832        pass833834    @cli.command()835    def cmd():836        """837        Summary line without period838839        Here is a sentence. And here too.840        """841        pass842843    result = runner.invoke(cli, ["--help"])844    assert "Summary line without period" in result.output845    assert "Here is a sentence." not in result.output846847848def test_help_invalid_default(runner):849    cli = click.Command(850        "cli",851        params=[852            click.Option(853                ["-a"],854                type=click.Path(exists=True),855                default="not found",856                show_default=True,857            ),858        ],859    )860    result = runner.invoke(cli, ["--help"])861    assert result.exit_code == 0862    assert "default: not found" in result.output863864865def test_version_option_resolves_import_name_to_distribution(runner, monkeypatch):866    """When ``package_name`` (detected or passed) is an import name that867    differs from its installed distribution name (``PIL`` vs ``Pillow``),868    ``version_option`` resolves it via ``packages_distributions()`` instead869    of raising ``RuntimeError``.870    """871    import importlib.metadata872873    def fake_version(name):874        if name == "pillow":875            return "10.4.0"876        raise importlib.metadata.PackageNotFoundError(name)877878    monkeypatch.setattr(importlib.metadata, "version", fake_version)879    monkeypatch.setattr(880        importlib.metadata,881        "packages_distributions",882        lambda: {"PIL": ["pillow"]},883    )884885    @click.command()886    @click.version_option(package_name="PIL")887    def cli():888        pass889890    result = runner.invoke(cli, ["--version"], prog_name="imageapp")891    assert result.exit_code == 0892    assert "10.4.0" in result.output893894895def test_version_option_ambiguous_import_name_errors(runner, monkeypatch):896    """When an import name maps to multiple installed distributions, the897    user must disambiguate. The error names the candidates.898    """899    import importlib.metadata900901    def fake_version(name):902        raise importlib.metadata.PackageNotFoundError(name)903904    monkeypatch.setattr(importlib.metadata, "version", fake_version)905    monkeypatch.setattr(906        importlib.metadata,907        "packages_distributions",908        lambda: {"plug": ["foo-plug", "bar-plug"]},909    )910911    @click.command()912    @click.version_option(package_name="plug")913    def cli():914        pass915916    result = runner.invoke(cli, ["--version"])917    assert result.exit_code != 0918    msg = str(result.exception)919    assert "multiple installed distributions" in msg920    assert "foo-plug" in msg921    assert "bar-plug" in msg922923924def test_version_option_unknown_package_errors(runner, monkeypatch):925    """When the name resolves to no distribution, keep the existing error."""926    import importlib.metadata927928    def fake_version(name):929        raise importlib.metadata.PackageNotFoundError(name)930931    monkeypatch.setattr(importlib.metadata, "version", fake_version)932    monkeypatch.setattr(importlib.metadata, "packages_distributions", lambda: {})933934    @click.command()935    @click.version_option(package_name="nonexistent")936    def cli():937        pass938939    result = runner.invoke(cli, ["--version"])940    assert result.exit_code != 0941    assert "not installed" in str(result.exception)942943944@pytest.mark.parametrize("args", [["--version"], ["-V"]])945def test_custom_version_option(runner, args):946    @click.command()947    @click.custom_version_option(lambda ctx: "custom 9.9.9", "-V", "--version")948    def cli():949        pass950951    result = runner.invoke(cli, args)952    assert result.exit_code == 0953    assert result.output == "custom 9.9.9\n"954955956def test_custom_version_option_receives_context(runner):957    @click.command()958    @click.custom_version_option(lambda ctx: f"{ctx.info_name} 1.0")959    def cli():960        pass961962    result = runner.invoke(cli, ["--version"], prog_name="mytool")963    assert result.exit_code == 0964    assert result.output == "mytool 1.0\n"