Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

1,141 lines · 34.8 KiB · Python

Last changed by

Fix flag value set when is_flag=True and type is provided (#2930)David Lordbefore adoption884af5c

History of this file

Take it

1import os2import re34import pytest56import click7from click import Option8910def test_prefixes(runner):11    @click.command()12    @click.option("++foo", is_flag=True, help="das foo")13    @click.option("--bar", is_flag=True, help="das bar")14    def cli(foo, bar):15        click.echo(f"foo={foo} bar={bar}")1617    result = runner.invoke(cli, ["++foo", "--bar"])18    assert not result.exception19    assert result.output == "foo=True bar=True\n"2021    result = runner.invoke(cli, ["--help"])22    assert re.search(r"\+\+foo\s+das foo", result.output) is not None23    assert re.search(r"--bar\s+das bar", result.output) is not None242526def test_invalid_option(runner):27    with pytest.raises(TypeError, match="name was passed") as exc_info:28        click.Option(["foo"])2930    message = str(exc_info.value)31    assert "name was passed (foo)" in message32    assert "declare an argument" in message33    assert "'--foo'" in message343536@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])37def test_deprecated_usage(runner, deprecated):38    @click.command()39    @click.option("--foo", default="bar", deprecated=deprecated)40    def cmd(foo):41        click.echo(foo)4243    result = runner.invoke(cmd, ["--help"])44    assert "(DEPRECATED" in result.output4546    if isinstance(deprecated, str):47        assert deprecated in result.output484950@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])51def test_deprecated_warning(runner, deprecated):52    @click.command()53    @click.option(54        "--my-option", required=False, deprecated=deprecated, default="default option"55    )56    def cli(my_option: str):57        click.echo(f"{my_option}")5859    # defaults should not give a deprecated warning60    result = runner.invoke(cli, [])61    assert result.exit_code == 0, result.output62    assert "is deprecated" not in result.output6364    result = runner.invoke(cli, ["--my-option", "hello"])65    assert result.exit_code == 0, result.output66    assert "option 'my_option' is deprecated" in result.output6768    if isinstance(deprecated, str):69        assert deprecated in result.output707172def test_deprecated_required(runner):73    with pytest.raises(ValueError, match="is deprecated and still required"):74        click.Option(["--a"], required=True, deprecated=True)757677def test_deprecated_prompt(runner):78    with pytest.raises(ValueError, match="`deprecated` options cannot use `prompt`"):79        click.Option(["--a"], prompt=True, deprecated=True)808182def test_invalid_nargs(runner):83    with pytest.raises(TypeError, match="nargs=-1"):8485        @click.command()86        @click.option("--foo", nargs=-1)87        def cli(foo):88            pass899091def test_nargs_tup_composite_mult(runner):92    @click.command()93    @click.option("--item", type=(str, int), multiple=True)94    def copy(item):95        for name, id in item:96            click.echo(f"name={name} id={id:d}")9798    result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])99    assert not result.exception100    assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]101102103def test_counting(runner):104    @click.command()105    @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))106    def cli(v):107        click.echo(f"verbosity={v:d}")108109    result = runner.invoke(cli, ["-vvv"])110    assert not result.exception111    assert result.output == "verbosity=3\n"112113    result = runner.invoke(cli, ["-vvvv"])114    assert result.exception115    assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output116117    result = runner.invoke(cli, [])118    assert not result.exception119    assert result.output == "verbosity=0\n"120121    result = runner.invoke(cli, ["--help"])122    assert re.search(r"-v\s+Verbosity", result.output) is not None123124125@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])126def test_unknown_options(runner, unknown_flag):127    @click.command()128    def cli():129        pass130131    result = runner.invoke(cli, [unknown_flag])132    assert result.exception133    assert f"No such option: {unknown_flag}" in result.output134135136@pytest.mark.parametrize(137    ("value", "expect"),138    [139        ("--cat", "Did you mean --count?"),140        ("--bounds", "(Possible options: --bound, --count)"),141        ("--bount", "(Possible options: --bound, --count)"),142    ],143)144def test_suggest_possible_options(runner, value, expect):145    cli = click.Command(146        "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]147    )148    result = runner.invoke(cli, [value])149    assert expect in result.output150151152def test_multiple_required(runner):153    @click.command()154    @click.option("-m", "--message", multiple=True, required=True)155    def cli(message):156        click.echo("\n".join(message))157158    result = runner.invoke(cli, ["-m", "foo", "-mbar"])159    assert not result.exception160    assert result.output == "foo\nbar\n"161162    result = runner.invoke(cli, [])163    assert result.exception164    assert "Error: Missing option '-m' / '--message'." in result.output165166167@pytest.mark.parametrize(168    ("multiple", "nargs", "default"),169    [170        (True, 1, []),171        (True, 1, [1]),172        # (False, -1, []),173        # (False, -1, [1]),174        (False, 2, [1, 2]),175        # (True, -1, [[]]),176        # (True, -1, []),177        # (True, -1, [[1]]),178        (True, 2, []),179        (True, 2, [[1, 2]]),180    ],181)182def test_init_good_default_list(runner, multiple, nargs, default):183    click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)184185186@pytest.mark.parametrize(187    ("multiple", "nargs", "default"),188    [189        (True, 1, 1),190        # (False, -1, 1),191        (False, 2, [1]),192        (True, 2, [[1]]),193    ],194)195def test_init_bad_default_list(runner, multiple, nargs, default):196    type = (str, str) if nargs == 2 else None197198    with pytest.raises(ValueError, match="default"):199        click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)200201202@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])203def test_empty_envvar(runner, env_key):204    @click.command()205    @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")206    def cli(mypath):207        click.echo(f"mypath: {mypath}")208209    result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO")210    assert result.exception is None211    assert result.output == "mypath: None\n"212213214def test_multiple_envvar(runner):215    @click.command()216    @click.option("--arg", multiple=True)217    def cmd(arg):218        click.echo("|".join(arg))219220    result = runner.invoke(221        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}222    )223    assert not result.exception224    assert result.output == "foo|bar|baz\n"225226    @click.command()227    @click.option("--arg", multiple=True, envvar="X")228    def cmd(arg):229        click.echo("|".join(arg))230231    result = runner.invoke(cmd, [], env={"X": "foo bar baz"})232    assert not result.exception233    assert result.output == "foo|bar|baz\n"234235    @click.command()236    @click.option("--arg", multiple=True, type=click.Path())237    def cmd(arg):238        click.echo("|".join(arg))239240    result = runner.invoke(241        cmd,242        [],243        auto_envvar_prefix="TEST",244        env={"TEST_ARG": f"foo{os.path.pathsep}bar"},245    )246    assert not result.exception247    assert result.output == "foo|bar\n"248249250def test_trailing_blanks_boolean_envvar(runner):251    @click.command()252    @click.option("--shout/--no-shout", envvar="SHOUT")253    def cli(shout):254        click.echo(f"shout: {shout!r}")255256    result = runner.invoke(cli, [], env={"SHOUT": " true "})257    assert result.exit_code == 0258    assert result.output == "shout: True\n"259260261def test_multiple_default_help(runner):262    @click.command()263    @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)264    @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)265    def cmd(arg, arg2):266        pass267268    result = runner.invoke(cmd, ["--help"])269    assert not result.exception270    assert "foo, bar" in result.output271    assert "1, 2" in result.output272273274def test_show_default_default_map(runner):275    @click.command()276    @click.option("--arg", default="a", show_default=True)277    def cmd(arg):278        click.echo(arg)279280    result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})281282    assert not result.exception283    assert "[default: b]" in result.output284285286def test_multiple_default_type():287    opt = click.Option(["-a"], multiple=True, default=(1, 2))288    assert opt.nargs == 1289    assert opt.multiple290    assert opt.type is click.INT291    ctx = click.Context(click.Command("test"))292    assert opt.get_default(ctx) == (1, 2)293294295def test_multiple_default_composite_type():296    opt = click.Option(["-a"], multiple=True, default=[(1, "a")])297    assert opt.nargs == 2298    assert opt.multiple299    assert isinstance(opt.type, click.Tuple)300    assert opt.type.types == [click.INT, click.STRING]301    ctx = click.Context(click.Command("test"))302    assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)303304305def test_parse_multiple_default_composite_type(runner):306    @click.command()307    @click.option("-a", multiple=True, default=("a", "b"))308    @click.option("-b", multiple=True, default=[(1, "a")])309    def cmd(a, b):310        click.echo(a)311        click.echo(b)312313    # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())314    # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"315    result = runner.invoke(cmd)316    assert result.output == "('a', 'b')\n((1, 'a'),)\n"317318319def test_dynamic_default_help_unset(runner):320    @click.command()321    @click.option(322        "--username",323        prompt=True,324        default=lambda: os.environ.get("USER", ""),325        show_default=True,326    )327    def cmd(username):328        print("Hello,", username)329330    result = runner.invoke(cmd, ["--help"])331    assert result.exit_code == 0332    assert "--username" in result.output333    assert "lambda" not in result.output334    assert "(dynamic)" in result.output335336337def test_dynamic_default_help_text(runner):338    @click.command()339    @click.option(340        "--username",341        prompt=True,342        default=lambda: os.environ.get("USER", ""),343        show_default="current user",344    )345    def cmd(username):346        print("Hello,", username)347348    result = runner.invoke(cmd, ["--help"])349    assert result.exit_code == 0350    assert "--username" in result.output351    assert "lambda" not in result.output352    assert "(current user)" in result.output353354355def test_dynamic_default_help_special_method(runner):356    class Value:357        def __call__(self):358            return 42359360        def __str__(self):361            return "special value"362363    opt = click.Option(["-a"], default=Value(), show_default=True)364    ctx = click.Context(click.Command("cli"))365    assert opt.get_help_extra(ctx) == {"default": "special value"}366    assert "special value" in opt.get_help_record(ctx)[1]367368369@pytest.mark.parametrize(370    ("type", "expect"),371    [372        (click.IntRange(1, 32), "1<=x<=32"),373        (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),374        (click.IntRange(1), "x>=1"),375        (click.IntRange(max=32), "x<=32"),376    ],377)378def test_intrange_default_help_text(type, expect):379    option = click.Option(["--num"], type=type, show_default=True, default=2)380    context = click.Context(click.Command("test"))381    assert option.get_help_extra(context) == {"default": "2", "range": expect}382    result = option.get_help_record(context)[1]383    assert expect in result384385386def test_count_default_type_help():387    """A count option with the default type should not show >=0 in help."""388    option = click.Option(["--count"], count=True, help="some words")389    context = click.Context(click.Command("test"))390    assert option.get_help_extra(context) == {}391    result = option.get_help_record(context)[1]392    assert result == "some words"393394395def test_file_type_help_default():396    """The default for a File type is a filename string. The string397    should be displayed in help, not an open file object.398399    Type casting is only applied to defaults in processing, not when400    getting the default value.401    """402    option = click.Option(403        ["--in"], type=click.File(), default=__file__, show_default=True404    )405    context = click.Context(click.Command("test"))406    assert option.get_help_extra(context) == {"default": __file__}407    result = option.get_help_record(context)[1]408    assert __file__ in result409410411def test_toupper_envvar_prefix(runner):412    @click.command()413    @click.option("--arg")414    def cmd(arg):415        click.echo(arg)416417    result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})418    assert not result.exception419    assert result.output == "foo\n"420421422def test_nargs_envvar(runner):423    @click.command()424    @click.option("--arg", nargs=2)425    def cmd(arg):426        click.echo("|".join(arg))427428    result = runner.invoke(429        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}430    )431    assert not result.exception432    assert result.output == "foo|bar\n"433434    @click.command()435    @click.option("--arg", nargs=2, multiple=True)436    def cmd(arg):437        for item in arg:438            click.echo("|".join(item))439440    result = runner.invoke(441        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}442    )443    assert not result.exception444    assert result.output == "x|1\ny|2\n"445446447def test_show_envvar(runner):448    @click.command()449    @click.option("--arg1", envvar="ARG1", show_envvar=True)450    def cmd(arg):451        pass452453    result = runner.invoke(cmd, ["--help"])454    assert not result.exception455    assert "ARG1" in result.output456457458def test_show_envvar_auto_prefix(runner):459    @click.command()460    @click.option("--arg1", show_envvar=True)461    def cmd(arg):462        pass463464    result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")465    assert not result.exception466    assert "TEST_ARG1" in result.output467468469def test_show_envvar_auto_prefix_dash_in_command(runner):470    @click.group()471    def cli():472        pass473474    @cli.command()475    @click.option("--baz", show_envvar=True)476    def foo_bar(baz):477        pass478479    result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")480    assert not result.exception481    assert "TEST_FOO_BAR_BAZ" in result.output482483484def test_custom_validation(runner):485    def validate_pos_int(ctx, param, value):486        if value < 0:487            raise click.BadParameter("Value needs to be positive")488        return value489490    @click.command()491    @click.option("--foo", callback=validate_pos_int, default=1)492    def cmd(foo):493        click.echo(foo)494495    result = runner.invoke(cmd, ["--foo", "-1"])496    assert "Invalid value for '--foo': Value needs to be positive" in result.output497498    result = runner.invoke(cmd, ["--foo", "42"])499    assert result.output == "42\n"500501502def test_callback_validates_prompt(runner, monkeypatch):503    def validate(ctx, param, value):504        if value < 0:505            raise click.BadParameter("should be positive")506507        return value508509    @click.command()510    @click.option("-a", type=int, callback=validate, prompt=True)511    def cli(a):512        click.echo(a)513514    result = runner.invoke(cli, input="-12\n60\n")515    assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"516517518def test_winstyle_options(runner):519    @click.command()520    @click.option("/debug;/no-debug", help="Enables or disables debug mode.")521    def cmd(debug):522        click.echo(debug)523524    result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])525    assert result.output == "True\n"526    result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])527    assert result.output == "False\n"528    result = runner.invoke(cmd, [], help_option_names=["/?"])529    assert result.output == "False\n"530    result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])531    assert "/debug; /no-debug  Enables or disables debug mode." in result.output532    assert "/?                 Show this message and exit." in result.output533534535def test_legacy_options(runner):536    @click.command()537    @click.option("-whatever")538    def cmd(whatever):539        click.echo(whatever)540541    result = runner.invoke(cmd, ["-whatever", "42"])542    assert result.output == "42\n"543    result = runner.invoke(cmd, ["-whatever=23"])544    assert result.output == "23\n"545546547def test_missing_option_string_cast():548    ctx = click.Context(click.Command(""))549550    with pytest.raises(click.MissingParameter) as excinfo:551        click.Option(["-a"], required=True).process_value(ctx, None)552553    assert str(excinfo.value) == "Missing parameter: a"554555556def test_missing_required_flag(runner):557    cli = click.Command(558        "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]559    )560    result = runner.invoke(cli)561    assert result.exit_code == 2562    assert "Error: Missing option '--on'." in result.output563564565def test_missing_choice(runner):566    @click.command()567    @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)568    def cmd(foo):569        click.echo(foo)570571    result = runner.invoke(cmd)572    assert result.exit_code == 2573    error, separator, choices = result.output.partition("Choose from")574    assert "Error: Missing option '--foo'. " in error575    assert "Choose from" in separator576    assert "foo" in choices577    assert "bar" in choices578579580def test_missing_envvar(runner):581    cli = click.Command(582        "cli", params=[click.Option(["--foo"], envvar="bar", required=True)]583    )584    result = runner.invoke(cli)585    assert result.exit_code == 2586    assert "Error: Missing option '--foo'." in result.output587    cli = click.Command(588        "cli",589        params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)],590    )591    result = runner.invoke(cli)592    assert result.exit_code == 2593    assert "Error: Missing option '--foo' (env var: 'bar')." in result.output594595596def test_case_insensitive_choice(runner):597    @click.command()598    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))599    def cmd(foo):600        click.echo(foo)601602    result = runner.invoke(cmd, ["--foo", "apple"])603    assert result.exit_code == 0604    assert result.output == "Apple\n"605606    result = runner.invoke(cmd, ["--foo", "oRANGe"])607    assert result.exit_code == 0608    assert result.output == "Orange\n"609610    result = runner.invoke(cmd, ["--foo", "Apple"])611    assert result.exit_code == 0612    assert result.output == "Apple\n"613614    @click.command()615    @click.option("--foo", type=click.Choice(["Orange", "Apple"]))616    def cmd2(foo):617        click.echo(foo)618619    result = runner.invoke(cmd2, ["--foo", "apple"])620    assert result.exit_code == 2621622    result = runner.invoke(cmd2, ["--foo", "oRANGe"])623    assert result.exit_code == 2624625    result = runner.invoke(cmd2, ["--foo", "Apple"])626    assert result.exit_code == 0627628629def test_case_insensitive_choice_returned_exactly(runner):630    @click.command()631    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))632    def cmd(foo):633        click.echo(foo)634635    result = runner.invoke(cmd, ["--foo", "apple"])636    assert result.exit_code == 0637    assert result.output == "Apple\n"638639640def test_option_help_preserve_paragraphs(runner):641    @click.command()642    @click.option(643        "-C",644        "--config",645        type=click.Path(),646        help="""Configuration file to use.647648        If not given, the environment variable CONFIG_FILE is consulted649        and used if set. If neither are given, a default configuration650        file is loaded.""",651    )652    def cmd(config):653        pass654655    result = runner.invoke(cmd, ["--help"])656    assert result.exit_code == 0657    i = " " * 21658    assert (659        "  -C, --config PATH  Configuration file to use.\n"660        f"{i}\n"661        f"{i}If not given, the environment variable CONFIG_FILE is\n"662        f"{i}consulted and used if set. If neither are given, a default\n"663        f"{i}configuration file is loaded."664    ) in result.output665666667def test_argument_custom_class(runner):668    class CustomArgument(click.Argument):669        def get_default(self, ctx, call=True):670            """a dumb override of a default value for testing"""671            return "I am a default"672673    @click.command()674    @click.argument("testarg", cls=CustomArgument, default="you wont see me")675    def cmd(testarg):676        click.echo(testarg)677678    result = runner.invoke(cmd)679    assert "I am a default" in result.output680    assert "you wont see me" not in result.output681682683def test_option_custom_class(runner):684    class CustomOption(click.Option):685        def get_help_record(self, ctx):686            """a dumb override of a help text for testing"""687            return ("--help", "I am a help text")688689    @click.command()690    @click.option("--testoption", cls=CustomOption, help="you wont see me")691    def cmd(testoption):692        click.echo(testoption)693694    result = runner.invoke(cmd, ["--help"])695    assert "I am a help text" in result.output696    assert "you wont see me" not in result.output697698699def test_option_custom_class_reusable(runner):700    """Ensure we can reuse a custom class option. See Issue #926"""701702    class CustomOption(click.Option):703        def get_help_record(self, ctx):704            """a dumb override of a help text for testing"""705            return ("--help", "I am a help text")706707    # Assign to a variable to re-use the decorator.708    testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")709710    @click.command()711    @testoption712    def cmd1(testoption):713        click.echo(testoption)714715    @click.command()716    @testoption717    def cmd2(testoption):718        click.echo(testoption)719720    # Both of the commands should have the --help option now.721    for cmd in (cmd1, cmd2):722        result = runner.invoke(cmd, ["--help"])723        assert "I am a help text" in result.output724        assert "you wont see me" not in result.output725726727@pytest.mark.parametrize("custom_class", (True, False))728@pytest.mark.parametrize(729    ("name_specs", "expected"),730    (731        (732            ("-h", "--help"),733            "  -h, --help  Show this message and exit.\n",734        ),735        (736            ("-h",),737            "  -h      Show this message and exit.\n"738            "  --help  Show this message and exit.\n",739        ),740        (741            ("--help",),742            "  --help  Show this message and exit.\n",743        ),744    ),745)746def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):747    class CustomHelpOption(click.Option):748        pass749750    option_attrs = {}751    if custom_class:752        option_attrs["cls"] = CustomHelpOption753754    @click.command()755    @click.help_option(*name_specs, **option_attrs)756    def cmd():757        pass758759    for arg in name_specs:760        result = runner.invoke(cmd, [arg])761        assert not result.exception762        assert result.exit_code == 0763        assert expected in result.output764765766def test_bool_flag_with_type(runner):767    @click.command()768    @click.option("--shout/--no-shout", default=False, type=bool)769    def cmd(shout):770        pass771772    result = runner.invoke(cmd)773    assert not result.exception774775776def test_aliases_for_flags(runner):777    @click.command()778    @click.option("--warnings/--no-warnings", " /-W", default=True)779    def cli(warnings):780        click.echo(warnings)781782    result = runner.invoke(cli, ["--warnings"])783    assert result.output == "True\n"784    result = runner.invoke(cli, ["--no-warnings"])785    assert result.output == "False\n"786    result = runner.invoke(cli, ["-W"])787    assert result.output == "False\n"788789    @click.command()790    @click.option("--warnings/--no-warnings", "-w", default=True)791    def cli_alt(warnings):792        click.echo(warnings)793794    result = runner.invoke(cli_alt, ["--warnings"])795    assert result.output == "True\n"796    result = runner.invoke(cli_alt, ["--no-warnings"])797    assert result.output == "False\n"798    result = runner.invoke(cli_alt, ["-w"])799    assert result.output == "True\n"800801802@pytest.mark.parametrize(803    "option_args,expected",804    [805        (["--aggressive", "--all", "-a"], "aggressive"),806        (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),807        (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),808        (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),809        (["-a", "-b", "-c"], "a"),810        (["-c", "-b", "-a"], "c"),811        (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),812        (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),813        (["--from", "-f", "_from"], "_from"),814        (["--return", "-r", "_ret"], "_ret"),815    ],816)817def test_option_names(runner, option_args, expected):818    @click.command()819    @click.option(*option_args, is_flag=True)820    def cmd(**kwargs):821        click.echo(str(kwargs[expected]))822823    assert cmd.params[0].name == expected824825    for form in option_args:826        if form.startswith("-"):827            result = runner.invoke(cmd, [form])828            assert result.output == "True\n"829830831def test_flag_duplicate_names(runner):832    with pytest.raises(ValueError, match="cannot use the same flag for true/false"):833        click.Option(["--foo/--foo"], default=False)834835836@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])837def test_show_default_boolean_flag_name(runner, default, expect):838    """When a boolean flag has distinct True/False opts, it should show839    the default opt name instead of the default value. It should only840    show one name even if multiple are declared.841    """842    opt = click.Option(843        ("--cache/--no-cache", "--c/--nc"),844        default=default,845        show_default=True,846        help="Enable/Disable the cache.",847    )848    ctx = click.Context(click.Command("test"))849    assert opt.get_help_extra(ctx) == {"default": expect}850    message = opt.get_help_record(ctx)[1]851    assert f"[default: {expect}]" in message852853854def test_show_true_default_boolean_flag_value(runner):855    """When a boolean flag only has one opt and its default is True,856    it will show the default value, not the opt name.857    """858    opt = click.Option(859        ("--cache",),860        is_flag=True,861        show_default=True,862        default=True,863        help="Enable the cache.",864    )865    ctx = click.Context(click.Command("test"))866    assert opt.get_help_extra(ctx) == {"default": "True"}867    message = opt.get_help_record(ctx)[1]868    assert "[default: True]" in message869870871@pytest.mark.parametrize("default", [False, None])872def test_hide_false_default_boolean_flag_value(runner, default):873    """When a boolean flag only has one opt and its default is False or874    None, it will not show the default875    """876    opt = click.Option(877        ("--cache",),878        is_flag=True,879        show_default=True,880        default=default,881        help="Enable the cache.",882    )883    ctx = click.Context(click.Command("test"))884    assert opt.get_help_extra(ctx) == {}885    message = opt.get_help_record(ctx)[1]886    assert "[default: " not in message887888889def test_show_default_string(runner):890    """When show_default is a string show that value as default."""891    opt = click.Option(["--limit"], show_default="unlimited")892    ctx = click.Context(click.Command("cli"))893    assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}894    message = opt.get_help_record(ctx)[1]895    assert "[default: (unlimited)]" in message896897898def test_show_default_with_empty_string(runner):899    """When show_default is True and default is set to an empty string."""900    opt = click.Option(["--limit"], default="", show_default=True)901    ctx = click.Context(click.Command("cli"))902    message = opt.get_help_record(ctx)[1]903    assert '[default: ""]' in message904905906def test_do_not_show_no_default(runner):907    """When show_default is True and no default is set do not show None."""908    opt = click.Option(["--limit"], show_default=True)909    ctx = click.Context(click.Command("cli"))910    assert opt.get_help_extra(ctx) == {}911    message = opt.get_help_record(ctx)[1]912    assert "[default: None]" not in message913914915def test_do_not_show_default_empty_multiple():916    """When show_default is True and multiple=True is set, it should not917    print empty default value in --help output.918    """919    opt = click.Option(["-a"], multiple=True, help="values", show_default=True)920    ctx = click.Context(click.Command("cli"))921    assert opt.get_help_extra(ctx) == {}922    message = opt.get_help_record(ctx)[1]923    assert message == "values"924925926@pytest.mark.parametrize(927    ("ctx_value", "opt_value", "extra_value", "expect"),928    [929        (None, None, {}, False),930        (None, False, {}, False),931        (None, True, {"default": "1"}, True),932        (False, None, {}, False),933        (False, False, {}, False),934        (False, True, {"default": "1"}, True),935        (True, None, {"default": "1"}, True),936        (True, False, {}, False),937        (True, True, {"default": "1"}, True),938        (False, "one", {"default": "(one)"}, True),939    ],940)941def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):942    ctx = click.Context(click.Command("test"), show_default=ctx_value)943    opt = click.Option("-a", default=1, help="value", show_default=opt_value)944    assert opt.get_help_extra(ctx) == extra_value945    help = opt.get_help_record(ctx)[1]946    assert ("default:" in help) is expect947948949@pytest.mark.parametrize(950    ("args", "expect"),951    [952        (None, (None, None, ())),953        (["--opt"], ("flag", None, ())),954        (["--opt", "-a", 42], ("flag", "42", ())),955        (["--opt", "test", "-a", 42], ("test", "42", ())),956        (["--opt=test", "-a", 42], ("test", "42", ())),957        (["-o"], ("flag", None, ())),958        (["-o", "-a", 42], ("flag", "42", ())),959        (["-o", "test", "-a", 42], ("test", "42", ())),960        (["-otest", "-a", 42], ("test", "42", ())),961        (["a", "b", "c"], (None, None, ("a", "b", "c"))),962        (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),963        (["--opt", "test"], ("test", None, ())),964        (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),965        (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),966    ],967)968def test_option_with_optional_value(runner, args, expect):969    @click.command()970    @click.option("-o", "--opt", is_flag=False, flag_value="flag")971    @click.option("-a")972    @click.argument("b", nargs=-1)973    def cli(opt, a, b):974        return opt, a, b975976    result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)977    assert result.return_value == expect978979980def test_multiple_option_with_optional_value(runner):981    cli = click.Command(982        "cli",983        params=[984            click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),985            click.Option(["-a"]),986            click.Argument(["b"], nargs=-1),987        ],988        callback=lambda **kwargs: kwargs,989    )990    result = runner.invoke(991        cli,992        ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],993        standalone_mode=False,994        catch_exceptions=False,995    )996    assert result.return_value == {997        "f": ("flag", "other", "flag"),998        "a": "1",999        "b": ("a", "b"),1000    }100110021003def test_type_from_flag_value():1004    param = click.Option(["-a", "x"], default=True, flag_value=4)1005    assert param.type is click.INT1006    param = click.Option(["-b", "x"], flag_value=8)1007    assert param.type is click.INT100810091010@pytest.mark.parametrize(1011    ("opts", "pass_flag", "expected"),1012    [1013        pytest.param({"type": bool}, False, "False"),1014        pytest.param({"type": bool}, True, "True"),1015        pytest.param({"type": bool, "default": True}, False, "True"),1016        pytest.param({"type": bool, "default": True}, True, "False"),1017        pytest.param({"type": click.BOOL}, False, "False"),1018        pytest.param({"type": click.BOOL}, True, "True"),1019        pytest.param({"type": click.BOOL, "default": True}, False, "True"),1020        pytest.param({"type": click.BOOL, "default": True}, True, "False"),1021        pytest.param({"type": str}, False, ""),1022        pytest.param({"type": str}, True, "True"),1023    ],1024)1025def test_flag_value_is_correctly_set(runner, opts, pass_flag, expected):1026    @click.command()1027    @click.option("--foo", is_flag=True, **opts)1028    def cmd(foo):1029        click.echo(foo)10301031    result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1032    assert result.output == f"{expected}\n"103310341035@pytest.mark.parametrize(1036    ("option", "expected"),1037    [1038        # Not boolean flags1039        pytest.param(Option(["-a"], type=int), False, id="int option"),1040        pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),1041        pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),1042        pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),1043        pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),1044        # Boolean flags1045        pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),1046        pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1047        pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1048    ],1049)1050def test_is_bool_flag_is_correctly_set(option, expected):1051    assert option.is_bool_flag is expected105210531054@pytest.mark.parametrize(1055    ("kwargs", "message"),1056    [1057        ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),1058        ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),1059    ],1060)1061def test_invalid_flag_combinations(runner, kwargs, message):1062    with pytest.raises(TypeError) as e:1063        click.Option(["-a"], **kwargs)10641065    assert message in str(e.value)106610671068def test_non_flag_with_non_negatable_default(runner):1069    class NonNegatable:1070        def __bool__(self):1071            raise ValueError("Cannot negate this object")10721073    @click.command()1074    @click.option("--foo", default=NonNegatable())1075    def cmd(foo):1076        pass10771078    result = runner.invoke(cmd)1079    assert result.exit_code == 0108010811082@pytest.mark.parametrize(1083    ("choices", "metavars"),1084    [1085        pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1086        pytest.param([1, 2], "[INTEGER]", id="int choices"),1087        pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1088        pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1089        pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1090    ],1091)1092def test_usage_show_choices(runner, choices, metavars):1093    """When show_choices=False is set, the --help output1094    should print choice metavars instead of values.1095    """10961097    @click.command()1098    @click.option("-g", type=click.Choice(choices))1099    def cli_with_choices(g):1100        pass11011102    @click.command()1103    @click.option(1104        "-g",1105        type=click.Choice(choices),1106        show_choices=False,1107    )1108    def cli_without_choices(g):1109        pass11101111    result = runner.invoke(cli_with_choices, ["--help"])1112    assert f"[{'|'.join([str(i) for i in choices])}]" in result.output11131114    result = runner.invoke(cli_without_choices, ["--help"])1115    assert metavars in result.output111611171118@pytest.mark.parametrize(1119    "opts_one,opts_two",1120    [1121        # No duplicate shortnames1122        (1123            ("-a", "--aardvark"),1124            ("-a", "--avocado"),1125        ),1126        # No duplicate long names1127        (1128            ("-a", "--aardvark"),1129            ("-b", "--aardvark"),1130        ),1131    ],1132)1133def test_duplicate_names_warning(runner, opts_one, opts_two):1134    @click.command()1135    @click.option(*opts_one)1136    @click.option(*opts_two)1137    def cli(one, two):1138        pass11391140    with pytest.warns(UserWarning):1141        runner.invoke(cli, [])