Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

3,945 lines · 131.1 KiB · Python

Last changed by

landed by oscabriel2247b35

History of this file

Take it

1import enum2import os3import re4import sys5import tempfile6import unicodedata7import warnings8from contextlib import nullcontext9from typing import Literal1011if sys.version_info < (3, 11):12    enum.StrEnum = enum.Enum  # type: ignore[assignment]1314import pytest1516import click17from click import Option18from click import UNPROCESSED19from click._utils import UNSET20from click.parser import _split_opt21from click.testing import CliRunner222324def test_prefixes(runner):25    @click.command()26    @click.option("++foo", is_flag=True, help="das foo")27    @click.option("--bar", is_flag=True, help="das bar")28    def cli(foo, bar):29        click.echo(f"foo={foo} bar={bar}")3031    result = runner.invoke(cli, ["++foo", "--bar"])32    assert not result.exception33    assert result.output == "foo=True bar=True\n"3435    result = runner.invoke(cli, ["--help"])36    assert re.search(r"\+\+foo\s+das foo", result.output) is not None37    assert re.search(r"--bar\s+das bar", result.output) is not None383940def test_invalid_option(runner):41    with pytest.raises(TypeError, match="name was passed") as exc_info:42        click.Option(["foo"])4344    message = str(exc_info.value)45    assert "name was passed (foo)" in message46    assert "declare an argument" in message47    assert "'--foo'" in message484950@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])51def test_deprecated_usage(runner, deprecated):52    @click.command()53    @click.option("--foo", default="bar", deprecated=deprecated)54    def cmd(foo):55        click.echo(foo)5657    result = runner.invoke(cmd, ["--help"])58    assert "(DEPRECATED" in result.output5960    if isinstance(deprecated, str):61        assert deprecated in result.output626364@pytest.mark.parametrize(65    ("deprecated", "expected"),66    [(True, "(DEPRECATED)"), ("USE B INSTEAD", "(DEPRECATED: USE B INSTEAD)")],67)68@pytest.mark.parametrize("help_text", ["", None])69def test_deprecated_empty_help_no_leading_space(help_text, deprecated, expected):70    """An option with empty or missing help text must not gain a stray leading71    space before the deprecation label.72    """73    opt = click.Option(["--foo"], help=help_text, deprecated=deprecated)74    ctx = click.Context(click.Command("cli"))75    assert opt.get_help_record(ctx)[1] == expected767778@pytest.mark.parametrize(79    ("param_decls", "kwargs", "expected"),80    [81        (["-v", "--verbose"], {"is_flag": True}, "-v, --verbose"),82        (["--config"], {}, "--config TEXT"),83        (["--color/--no-color"], {}, "--color / --no-color"),84        (["/debug;/no-debug"], {}, "/debug; /no-debug"),85    ],86)87@pytest.mark.parametrize("hidden", [False, True])88def test_help_spec(param_decls, kwargs, hidden, expected):89    """A hidden option still produces its spec via ``get_help_spec()``, unlike90    ``get_help_record()``.91    """92    opt = click.Option(param_decls, hidden=hidden, **kwargs)93    ctx = click.Context(click.Command("cli"))94    assert opt.get_help_spec(ctx) == expected9596    if hidden:97        assert opt.get_help_record(ctx) is None98    else:99        assert opt.get_help_record(ctx)[0] == expected100101102@pytest.mark.parametrize(103    ("param_decls", "expected_spec", "expected_name"),104    [105        (["-t", "--times"], "--times", "times"),106        (["--times", "-t"], "--times", "times"),107        (["-t"], "-t", "t"),108        (["-t", "--times", "--repeat"], "--times", "times"),109        (["--color/--no-color"], "--color", "color"),110        (["/debug;/no-debug"], "/debug", "debug"),111    ],112)113def test_spec(param_decls, expected_spec, expected_name):114    """The spec is the declaration the name was derived from, so the longest115    prefix wins over declaration order.116    """117    opt = click.Option(param_decls)118    assert opt.spec == expected_spec119    assert opt.name == expected_name120    assert _split_opt(opt.spec)[1].replace("-", "_").lower() == opt.name121122123def test_spec_with_explicit_name():124    """An explicit name declaration leaves the spec to the remaining flags."""125    opt = click.Option(["--times", "repeat_count"])126    assert opt.spec == "--times"127    assert opt.name == "repeat_count"128129130@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])131def test_deprecated_warning(runner, deprecated):132    @click.command()133    @click.option(134        "--my-option", required=False, deprecated=deprecated, default="default option"135    )136    def cli(my_option: str):137        click.echo(f"{my_option}")138139    # defaults should not give a deprecated warning140    result = runner.invoke(cli, [])141    assert result.exit_code == 0, result.output142    assert "is deprecated" not in result.output143144    result = runner.invoke(cli, ["--my-option", "hello"])145    assert result.exit_code == 0, result.output146    assert "option '--my-option' is deprecated" in result.output147148    if isinstance(deprecated, str):149        assert deprecated in result.output150151152def test_deprecated_required(runner):153    with pytest.raises(ValueError, match="is deprecated and still required"):154        click.Option(["--a"], required=True, deprecated=True)155156157def test_deprecated_prompt(runner):158    with pytest.raises(ValueError, match="`deprecated` options cannot use `prompt`"):159        click.Option(["--a"], prompt=True, deprecated=True)160161162def test_invalid_nargs(runner):163    with pytest.raises(TypeError, match="nargs=-1 is not supported for options."):164165        @click.command()166        @click.option("--foo", nargs=-1)167        def cli(foo):168            pass169170171def test_nargs_tup_composite_mult(runner):172    @click.command()173    @click.option("--item", type=(str, int), multiple=True)174    def copy(item):175        for name, id in item:176            click.echo(f"name={name} id={id:d}")177178    result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])179    assert not result.exception180    assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]181182183def test_counting(runner):184    @click.command()185    @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))186    def cli(v):187        click.echo(f"verbosity={v:d}")188189    result = runner.invoke(cli, ["-vvv"])190    assert not result.exception191    assert result.output == "verbosity=3\n"192193    result = runner.invoke(cli, ["-vvvv"])194    assert result.exception195    assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output196197    result = runner.invoke(cli, [])198    assert not result.exception199    assert result.output == "verbosity=0\n"200201    result = runner.invoke(cli, ["--help"])202    assert re.search(r"-v\s+Verbosity", result.output) is not None203204205@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])206def test_unknown_options(runner, unknown_flag):207    @click.command()208    def cli():209        pass210211    result = runner.invoke(cli, [unknown_flag])212    assert result.exception213    assert f"No such option '{unknown_flag}'." in result.output214215216@pytest.mark.parametrize(217    ("value", "expect"),218    [219        ("--cat", "Did you mean '--count'?"),220        ("--bounds", "(Did you mean one of: '--bound', '--count'?)"),221        ("--bount", "(Did you mean one of: '--bound', '--count'?)"),222    ],223)224def test_suggest_possible_options(runner, value, expect):225    cli = click.Command(226        "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]227    )228    result = runner.invoke(cli, [value])229    assert expect in result.output230231232def test_multiple_required(runner):233    @click.command()234    @click.option("-m", "--message", multiple=True, required=True)235    def cli(message):236        click.echo("\n".join(message))237238    result = runner.invoke(cli, ["-m", "foo", "-mbar"])239    assert not result.exception240    assert result.output == "foo\nbar\n"241242    result = runner.invoke(cli, [])243    assert result.exception244    assert "Error: Missing option '-m' / '--message'." in result.output245246247@pytest.mark.parametrize(248    ("multiple", "nargs", "default", "expected"),249    [250        # If multiple values are allowed, defaults should be iterable.251        (True, 1, [], ()),252        (True, 1, (), ()),253        (True, 1, tuple(), ()),254        (True, 1, set(), ()),255        (True, 1, frozenset(), ()),256        (True, 1, {}, ()),257        # Special values.258        (True, 1, None, ()),259        (True, 1, UNSET, ()),260        # Number of values are kept as-is in the default.261        (True, 1, [1], (1,)),262        (True, 1, [1, 2], (1, 2)),263        (True, 1, [1, 2, 3], (1, 2, 3)),264        (True, 1, [1.1, 2.2], (1.1, 2.2)),265        (True, 1, ["1", "2"], ("1", "2")),266        (True, 1, [None, None], (None, None)),267        # Contrary to list or tuples, native Python types not supported by Click are268        # not recognized and are converted to the default format: tuple of strings.269        # Refs: https://github.com/pallets/click/issues/3036270        (True, 1, {1, 2}, ("1", "2")),271        (True, 1, frozenset([1, 2]), ("1", "2")),272        (True, 1, {1: "a", 2: "b"}, ("1", "2")),273        # Multiple values with nargs > 1.274        (True, 2, [], ()),275        (True, 2, (), ()),276        (True, 2, tuple(), ()),277        (True, 2, set(), ()),278        (True, 2, frozenset(), ()),279        (True, 2, {}, ()),280        (True, 2, None, ()),281        (True, 2, UNSET, ()),282        (True, 2, [[1, 2]], ((1, 2),)),283        (True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))),284        (True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))),285        (True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))),286        (True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))),287        (True, 2, [[None, None], [None, None]], ((None, None), (None, None))),288        (True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))),289        (True, 2, [[1, 2.2], None], ((1, 2.2), None)),290        # Default of the right length works for non-multiples.291        (False, 2, [1, 2], (1, 2)),292    ],293)294def test_good_defaults_for_multiple(runner, multiple, nargs, default, expected):295    """Comprehensive check of default-value processing for options with296    ``multiple=True`` and/or ``nargs > 1``.297298    .. hint::299        An argument-specific equivalent is in300        ``test_arguments.py::test_good_defaults_for_nargs``.301302        Smoke tests are in ``test_defaults.py``:303        ``test_multiple_defaults`` (explicit ``type=FLOAT``)304        and ``test_nargs_plus_multiple`` (``nargs=2``).305    """306307    @click.command()308    @click.option("-a", multiple=multiple, nargs=nargs, default=default)309    def cmd(a):310        click.echo(repr(a), nl=False)311312    result = runner.invoke(cmd)313    assert result.output == repr(expected)314315316@pytest.mark.parametrize(317    ("multiple", "nargs", "default", "exception", "message"),318    [319        # Non-iterables defaults.320        (321            True,322            1,323            "Yo",324            None,325            "Error: Invalid value for '-a': Value must be an iterable.",326        ),327        (328            True,329            1,330            "",331            None,332            "Error: Invalid value for '-a': Value must be an iterable.",333        ),334        (335            True,336            1,337            True,338            None,339            "Error: Invalid value for '-a': Value must be an iterable.",340        ),341        (342            True,343            1,344            False,345            None,346            "Error: Invalid value for '-a': Value must be an iterable.",347        ),348        (349            True,350            1,351            12,352            None,353            "Error: Invalid value for '-a': Value must be an iterable.",354        ),355        (356            True,357            1,358            7.9,359            None,360            "Error: Invalid value for '-a': Value must be an iterable.",361        ),362        (363            False,364            2,365            42,366            None,367            "Error: Invalid value for '-a': Value must be an iterable.",368        ),369        (370            True,371            2,372            ["test string which is not a list in the list"],373            None,374            "Error: Invalid value for '-a': Value must be an iterable.",375        ),376        # Multiple options, each with 2 args, but with wrong length.377        (378            True,379            2,380            (1,),381            None,382            "Error: Invalid value for '-a': Value must be an iterable.",383        ),384        (385            True,386            2,387            (1, 2, 3),388            None,389            "Error: Invalid value for '-a': Value must be an iterable.",390        ),391        (392            True,393            2,394            [tuple()],395            ValueError,396            r"'nargs' must be 0 \(or None\) for type <click\.types\.Tuple object at "397            r"0x[0-9A-Fa-f]+>, but it was 2\.",398        ),399        (400            True,401            2,402            [(1,)],403            ValueError,404            r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "405            r"0x[0-9A-Fa-f]+>, but it was 2\.",406        ),407        (408            True,409            2,410            [(1, 2, 3)],411            ValueError,412            r"'nargs' must be 3 \(or None\) for type <click\.types\.Tuple object at "413            r"0x[0-9A-Fa-f]+>, but it was 2\.",414        ),415        # A mix of valid and invalid defaults.416        (417            True,418            2,419            [[1, 2.2], []],420            None,421            "Error: Invalid value for '-a': 2 values are required, but 0 were given.",422        ),423        # Default values that are iterable but not of the right length.424        (425            False,426            2,427            [1],428            None,429            "Error: Invalid value for '-a': Takes 2 values but 1 was given.",430        ),431        (432            True,433            2,434            [[1]],435            ValueError,436            r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "437            r"0x[0-9A-Fa-f]+>, but it was 2\.",438        ),439    ],440)441def test_bad_defaults_for_multiple(442    runner, multiple, nargs, default, exception, message443):444    if exception:445        assert issubclass(exception, Exception)446    else:447        assert exception is None448449    with (450        pytest.raises(exception, match=re.compile(message))451        if exception452        else nullcontext()453    ):454455        @click.command()456        @click.option("-a", multiple=multiple, nargs=nargs, default=default)457        def cmd(a):458            click.echo(repr(a))459460        result = runner.invoke(cmd)461        assert message in result.stderr462463464@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])465def test_empty_envvar(runner, env_key):466    @click.command()467    @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")468    def cli(mypath):469        click.echo(f"mypath: {mypath}")470471    result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO")472    assert result.exception is None473    assert result.output == "mypath: None\n"474475476def test_multiple_envvar(runner):477    @click.command()478    @click.option("--arg", multiple=True)479    def cmd(arg):480        click.echo("|".join(arg))481482    result = runner.invoke(483        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}484    )485    assert not result.exception486    assert result.output == "foo|bar|baz\n"487488489def test_envvar_container_type(runner):490    """Env vars are plain strings, so a container type splits them character-wise.491492    Refs: https://github.com/pallets/click/issues/3036493    """494495    @click.command()496    @click.option("--x", envvar="X", type=frozenset)497    def cli(x):498        assert isinstance(x, frozenset)499        click.echo("".join(sorted(x)))500501    result = runner.invoke(cli, [], env={"X": "git"})502    assert not result.exception503    assert result.output == "git\n"504505    @click.command()506    @click.option("--arg", multiple=True, envvar="X")507    def cmd(arg):508        click.echo("|".join(arg))509510    result = runner.invoke(cmd, [], env={"X": "foo bar baz"})511    assert not result.exception512    assert result.output == "foo|bar|baz\n"513514    @click.command()515    @click.option("--arg", multiple=True, type=click.Path())516    def cmd(arg):517        click.echo("|".join(arg))518519    result = runner.invoke(520        cmd,521        [],522        auto_envvar_prefix="TEST",523        env={"TEST_ARG": f"foo{os.path.pathsep}bar"},524    )525    assert not result.exception526    assert result.output == "foo|bar\n"527528529@pytest.mark.parametrize(530    ("envvar_name", "envvar_value", "expected"),531    (532        # Lower-cased variations of value.533        ("SHOUT", "true", True),534        ("SHOUT", "false", False),535        # Title-cased variations of value.536        ("SHOUT", "True", True),537        ("SHOUT", "False", False),538        # Upper-cased variations of value.539        ("SHOUT", "TRUE", True),540        ("SHOUT", "FALSE", False),541        # Random-cased variations of value.542        ("SHOUT", "TruE", True),543        ("SHOUT", "truE", True),544        ("SHOUT", "FaLsE", False),545        ("SHOUT", "falsE", False),546        # Extra spaces around the value.547        ("SHOUT", "true    ", True),548        ("SHOUT", "  true  ", True),549        ("SHOUT", "    true", True),550        ("SHOUT", "false   ", False),551        ("SHOUT", "  false ", False),552        ("SHOUT", "   false", False),553        # Integer variations.554        ("SHOUT", "1", True),555        ("SHOUT", "0", False),556        # Alternative states.557        ("SHOUT", "t", True),558        ("SHOUT", "T", True),559        ("SHOUT", "  T  ", True),560        ("SHOUT", "f", False),561        ("SHOUT", "y", True),562        ("SHOUT", "n", False),563        ("SHOUT", "yes", True),564        ("SHOUT", "no", False),565        ("SHOUT", "on", True),566        ("SHOUT", "off", False),567        # Blank value variations.568        ("SHOUT", None, False),569        ("SHOUT", "", False),570        ("SHOUT", " ", False),571        ("SHOUT", "       ", False),572        # Variable names are not stripped of spaces and so don't match the573        # flag, which then naturraly takes its default value.574        ("SHOUT    ", "True", False),575        ("SHOUT    ", "False", False),576        ("  SHOUT  ", "True", False),577        ("  SHOUT  ", "False", False),578        ("    SHOUT", "True", False),579        ("    SHOUT", "False", False),580        ("SH    OUT", "True", False),581        ("SH    OUT", "False", False),582        # Same for random and reverse environment variable names: they are not583        # recognized by the option.584        ("RANDOM", "True", False),585        ("NO_SHOUT", "True", False),586        ("NO_SHOUT", "False", False),587        ("NOSHOUT", "True", False),588        ("NOSHOUT", "False", False),589    ),590)591def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):592    assert isinstance(envvar_name, str)593    assert isinstance(envvar_value, str) or envvar_value is None594595    @click.command()596    @click.option("--shout/--no-shout", envvar="SHOUT")597    def cli(shout):598        click.echo(repr(shout), nl=False)599600    result = runner.invoke(cli, [], env={envvar_name: envvar_value})601    assert result.exit_code == 0602    assert result.output == repr(expected)603604605@pytest.mark.parametrize(606    "value",607    (608        # Extra spaces inside the value.609        "tr ue",  # codespell:ignore ue610        "fa lse",611        # Numbers.612        "10",613        "01",614        "00",615        "11",616        "0.0",617        "1.1",618        # Random strings.619        "randomstring",620        "None",621        "'None'",622        "A B",623        " 1 2 ",624        "9.3",625        "a;n",626        "x:y",627        "i/o",628    ),629)630def test_boolean_envvar_bad_values(runner, value):631    @click.command()632    @click.option("--shout/--no-shout", envvar="SHOUT")633    def cli(shout):634        click.echo(shout)635636    result = runner.invoke(cli, [], env={"SHOUT": value})637    assert result.exit_code == 2638    assert (639        f"Invalid value for '--shout': {value!r} is not a valid boolean."640        in result.output641    )642643644def test_multiple_default_help(runner):645    @click.command()646    @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)647    @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)648    def cmd(arg, arg2):649        pass650651    result = runner.invoke(cmd, ["--help"])652    assert not result.exception653    assert "foo, bar" in result.output654    assert "1, 2" in result.output655656657def test_show_default_default_map(runner):658    @click.command()659    @click.option("--arg", default="a", show_default=True)660    def cmd(arg):661        click.echo(arg)662663    result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})664665    assert not result.exception666    assert "[default: b]" in result.output667668669def test_show_default_container_defaults(runner):670    """Container defaults are rendered through ``str()`` in the help output.671672    Refs: https://github.com/pallets/click/issues/3036673    """674675    @click.command()676    @click.option("--a", default=frozenset(["git"]), type=frozenset, show_default=True)677    @click.option("--b", default={"a": 1}, type=dict, show_default=True)678    @click.option("--c", default={"git"}, type=set, show_default=True)679    def cli(a, b, c):680        pass681682    result = runner.invoke(cli, ["--help"])683    assert "[default: frozenset({'git'})]" in result.output684    assert "[default: {'a': 1}]" in result.output685    assert "[default: {'git'}]" in result.output686687688def test_multiple_default_type():689    opt = click.Option(["-a"], multiple=True, default=(1, 2))690    assert opt.nargs == 1691    assert opt.multiple692    assert opt.type is click.INT693    ctx = click.Context(click.Command("test"))694    assert opt.get_default(ctx) == (1, 2)695696697def test_multiple_default_composite_type():698    opt = click.Option(["-a"], multiple=True, default=[(1, "a")])699    assert opt.nargs == 2700    assert opt.multiple701    assert isinstance(opt.type, click.Tuple)702    assert opt.type.types == [click.INT, click.STRING]703    ctx = click.Context(click.Command("test"))704    assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)705706707@pytest.mark.parametrize(708    "default",709    [710        set(),711        {1, 2},712        frozenset(),713        frozenset(["git"]),714        {},715        {"a": 1},716    ],717)718def test_type_from_default_container(default):719    """Container defaults have no native Click type and fall back to STRING.720721    The documented "if no type is provided, the type of the default value is722    used" rule does not apply to ``set``, ``frozenset`` or ``dict`` defaults.723724    Refs: https://github.com/pallets/click/issues/3036725    """726    opt = click.Option(["-a"], default=default)727    assert opt.type is click.STRING728729730def test_parse_multiple_default_composite_type(runner):731    @click.command()732    @click.option("-a", multiple=True, default=("a", "b"))733    @click.option("-b", multiple=True, default=[(1, "a")])734    def cmd(a, b):735        click.echo(a)736        click.echo(b)737738    # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())739    # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"740    result = runner.invoke(cmd)741    assert result.output == "('a', 'b')\n((1, 'a'),)\n"742743744def test_dynamic_default_help_unset(runner):745    @click.command()746    @click.option(747        "--username",748        prompt=True,749        default=lambda: os.environ.get("USER", ""),750        show_default=True,751    )752    def cmd(username):753        print("Hello,", username)754755    result = runner.invoke(cmd, ["--help"])756    assert result.exit_code == 0757    assert "--username" in result.output758    assert "lambda" not in result.output759    assert "(dynamic)" in result.output760761762def test_dynamic_default_help_text(runner):763    @click.command()764    @click.option(765        "--username",766        prompt=True,767        default=lambda: os.environ.get("USER", ""),768        show_default="current user",769    )770    def cmd(username):771        print("Hello,", username)772773    result = runner.invoke(cmd, ["--help"])774    assert result.exit_code == 0775    assert "--username" in result.output776    assert "lambda" not in result.output777    assert "(current user)" in result.output778779780def test_dynamic_default_help_special_method(runner):781    class Value:782        def __call__(self):783            return 42784785        def __str__(self):786            return "special value"787788    opt = click.Option(["-a"], default=Value(), show_default=True)789    ctx = click.Context(click.Command("cli"))790    assert opt.get_help_extra(ctx) == {"default": "special value"}791    assert "special value" in opt.get_help_record(ctx)[1]792793794@pytest.mark.parametrize(795    ("type", "expect"),796    [797        (click.IntRange(1, 32), "1<=x<=32"),798        (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),799        (click.IntRange(1), "x>=1"),800        (click.IntRange(max=32), "x<=32"),801    ],802)803def test_intrange_default_help_text(type, expect):804    option = click.Option(["--num"], type=type, show_default=True, default=2)805    context = click.Context(click.Command("test"))806    assert option.get_help_extra(context) == {"default": "2", "range": expect}807    result = option.get_help_record(context)[1]808    assert expect in result809810811def test_count_default_type_help():812    """A count option with the default type should not show >=0 in help."""813    option = click.Option(["--count"], count=True, help="some words")814    context = click.Context(click.Command("test"))815    assert option.get_help_extra(context) == {}816    result = option.get_help_record(context)[1]817    assert result == "some words"818819820def test_file_type_help_default():821    """The default for a File type is a filename string. The string822    should be displayed in help, not an open file object.823824    Type casting is only applied to defaults in processing, not when825    getting the default value.826    """827    option = click.Option(828        ["--infile"], type=click.File(), default=__file__, show_default=True829    )830    context = click.Context(click.Command("test"))831    assert option.get_help_extra(context) == {"default": __file__}832    result = option.get_help_record(context)[1]833    assert __file__ in result834835836def test_toupper_envvar_prefix(runner):837    @click.command()838    @click.option("--arg")839    def cmd(arg):840        click.echo(arg)841842    result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})843    assert not result.exception844    assert result.output == "foo\n"845846847# CPython upper-cases every key of ``os.environ`` when ``os.name == "nt"``,848# see ``os._createenviron``. ``CliRunner`` writes the ``env`` mapping through849# ``os.environ`` and ``Parameter.resolve_envvar_value`` reads it back the same850# way, so on Windows a variable answers to every spelling of its name and851# elsewhere to exactly one. Both halves are asserted rather than skipped: the852# difference is the behaviour being pinned. See pallets/click#2483.853ENV_NAMES_ARE_CASE_INSENSITIVE = sys.platform == "win32"854855856def test_auto_envvar_uses_the_transformed_name(runner):857    """The auto envvar is built from the name, which the transform lower-cased."""858859    @click.command()860    @click.option("--Foo-Bar")861    def cmd(foo_bar):862        click.echo(foo_bar)863864    result = runner.invoke(865        cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}866    )867    assert not result.exception868    assert result.output == "foo\n"869870871def test_auto_envvar_ignores_decl_case(runner):872    """The case written in the declaration never reaches the auto envvar."""873874    @click.command()875    @click.option("--Foo-Bar")876    def cmd(foo_bar):877        click.echo(repr(foo_bar))878879    result = runner.invoke(880        cmd, [], auto_envvar_prefix="TEST", env={"TEST_Foo_Bar": "foo"}881    )882    assert not result.exception883    expect = "'foo'" if ENV_NAMES_ARE_CASE_INSENSITIVE else "None"884    assert result.output == f"{expect}\n"885886887def test_auto_envvar_prefix_is_upper_cased(runner):888    """A lower-case prefix reaches an upper-case variable, and only that one."""889890    @click.command()891    @click.option("--flag/--no-flag")892    def cmd(flag):893        click.echo(repr(flag))894895    result = runner.invoke(cmd, [], auto_envvar_prefix="yo", env={"YO_FLAG": "1"})896    assert not result.exception897    assert result.output == "True\n"898899    result = runner.invoke(cmd, [], auto_envvar_prefix="yo", env={"yo_FLAG": "1"})900    assert not result.exception901    assert result.output == f"{ENV_NAMES_ARE_CASE_INSENSITIVE}\n"902903904def test_auto_envvar_flattens_name_case(runner):905    """Two names differing only by case share one auto envvar."""906    with pytest.warns(DeprecationWarning, match="lower cases an explicit name"):907908        @click.command()909        @click.option("--foo-bar")910        @click.option("--other", "Foo_Bar")911        def cmd(**kwargs):912            click.echo(repr(sorted(kwargs.items())))913914    assert [p.name for p in cmd.params if p.name] == ["foo_bar", "Foo_Bar"]915916    result = runner.invoke(917        cmd, [], auto_envvar_prefix="TEST", env={"TEST_FOO_BAR": "foo"}918    )919    assert not result.exception920    assert result.output == "[('Foo_Bar', 'foo'), ('foo_bar', 'foo')]\n"921922923def test_auto_envvar_upper_can_change_length(runner):924    """Deriving the envvar is not the inverse of deriving the name."""925926    @click.command()927    @click.option("--ẞ")928    def cmd(**kwargs):929        click.echo(repr(kwargs))930931    result = runner.invoke(cmd, [], auto_envvar_prefix="TEST", env={"TEST_SS": "foo"})932    assert not result.exception933    assert result.output == "{'ß': 'foo'}\n"934935936@pytest.mark.parametrize(937    ("env", "expect"),938    [939        pytest.param({"ArG": "foo"}, "'foo'", id="exact"),940        pytest.param({"ARG": "foo"}, "None", id="upper"),941        pytest.param({"arg": "foo"}, "None", id="lower"),942    ],943)944def test_explicit_envvar_case_sensitivity(runner, env, expect):945    """An explicitly named envvar keeps the case it was registered with."""946947    @click.command()948    @click.option("--arg", envvar="ArG")949    def cmd(arg):950        click.echo(repr(arg))951952    result = runner.invoke(cmd, [], env=env)953    assert not result.exception954    if ENV_NAMES_ARE_CASE_INSENSITIVE:955        expect = "'foo'"956    assert result.output == f"{expect}\n"957958959@pytest.mark.parametrize("name", ("FlAg", "sUper"))960def test_explicit_envvar_list_keeps_each_spelling(runner, name):961    """Every name of an envvar list is matched with its own case."""962963    @click.command()964    @click.option("--flag/--no-flag", envvar=["FlAg", "sUper"])965    def cmd(flag):966        click.echo(repr(flag))967968    result = runner.invoke(cmd, [], env={name: "1"})969    assert not result.exception970    assert result.output == "True\n"971972973def test_nargs_envvar(runner):974    @click.command()975    @click.option("--arg", nargs=2)976    def cmd(arg):977        click.echo("|".join(arg))978979    result = runner.invoke(980        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}981    )982    assert not result.exception983    assert result.output == "foo|bar\n"984985    @click.command()986    @click.option("--arg", nargs=2, multiple=True)987    def cmd(arg):988        for item in arg:989            click.echo("|".join(item))990991    result = runner.invoke(992        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}993    )994    assert not result.exception995    assert result.output == "x|1\ny|2\n"996997998def test_show_envvar(runner):999    @click.command()1000    @click.option("--arg1", envvar="ARG1", show_envvar=True)1001    def cmd(arg):1002        pass10031004    result = runner.invoke(cmd, ["--help"])1005    assert not result.exception1006    assert "ARG1" in result.output100710081009def test_show_envvar_auto_prefix(runner):1010    @click.command()1011    @click.option("--arg1", show_envvar=True)1012    def cmd(arg):1013        pass10141015    result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")1016    assert not result.exception1017    assert "TEST_ARG1" in result.output101810191020def test_show_envvar_auto_prefix_dash_in_command(runner):1021    @click.group()1022    def cli():1023        pass10241025    @cli.command()1026    @click.option("--baz", show_envvar=True)1027    def foo_bar(baz):1028        pass10291030    result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")1031    assert not result.exception1032    assert "TEST_FOO_BAR_BAZ" in result.output103310341035def test_custom_validation(runner):1036    def validate_pos_int(ctx, param, value):1037        if value < 0:1038            raise click.BadParameter("Value needs to be positive")1039        return value10401041    @click.command()1042    @click.option("--foo", callback=validate_pos_int, default=1)1043    def cmd(foo):1044        click.echo(foo)10451046    result = runner.invoke(cmd, ["--foo", "-1"])1047    assert "Invalid value for '--foo': Value needs to be positive" in result.output10481049    result = runner.invoke(cmd, ["--foo", "42"])1050    assert result.output == "42\n"105110521053def test_callback_validates_prompt(runner, monkeypatch):1054    def validate(ctx, param, value):1055        if value < 0:1056            raise click.BadParameter("should be positive")10571058        return value10591060    @click.command()1061    @click.option("-a", type=int, callback=validate, prompt=True)1062    def cli(a):1063        click.echo(a)10641065    result = runner.invoke(cli, input="-12\n60\n")1066    assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"106710681069def test_winstyle_options(runner):1070    @click.command()1071    @click.option("/debug;/no-debug", help="Enables or disables debug mode.")1072    def cmd(debug):1073        click.echo(debug)10741075    result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])1076    assert result.output == "True\n"1077    result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])1078    assert result.output == "False\n"1079    result = runner.invoke(cmd, [], help_option_names=["/?"])1080    assert result.output == "False\n"1081    result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])1082    assert "/debug; /no-debug  Enables or disables debug mode." in result.output1083    assert "/?                 Show this message and exit." in result.output108410851086def test_legacy_options(runner):1087    @click.command()1088    @click.option("-whatever")1089    def cmd(whatever):1090        click.echo(whatever)10911092    result = runner.invoke(cmd, ["-whatever", "42"])1093    assert result.output == "42\n"1094    result = runner.invoke(cmd, ["-whatever=23"])1095    assert result.output == "23\n"109610971098@pytest.mark.parametrize(1099    ("value", "expect_missing", "processed_value"),1100    [1101        (UNSET, True, None),1102        (None, False, None),1103        # Default type of the argument is str, so everything is processed as strings.1104        ("", False, ""),1105        ("  ", False, "  "),1106        ("foo", False, "foo"),1107        ("12", False, "12"),1108        (12, False, "12"),1109        (12.1, False, "12.1"),1110        (list(), False, "[]"),1111        (tuple(), False, "()"),1112        (set(), False, "set()"),1113        (frozenset(), False, "frozenset()"),1114        (dict(), False, "{}"),1115    ],1116)1117def test_required_option(value, expect_missing, processed_value):1118    ctx = click.Context(click.Command(""))1119    argument = click.Option(["-a"], required=True)11201121    if expect_missing:1122        with pytest.raises(click.MissingParameter) as excinfo:1123            argument.process_value(ctx, value)1124        assert str(excinfo.value) == "Missing parameter: a"11251126    else:1127        value = argument.process_value(ctx, value)1128        assert value == processed_value112911301131def test_missing_required_flag(runner):1132    cli = click.Command(1133        "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]1134    )1135    result = runner.invoke(cli)1136    assert result.exit_code == 21137    assert "Error: Missing option '--on'." in result.output113811391140def test_missing_choice(runner):1141    @click.command()1142    @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)1143    def cmd(foo):1144        click.echo(foo)11451146    result = runner.invoke(cmd)1147    assert result.exit_code == 21148    error, separator, choices = result.output.partition("Choose from")1149    assert "Error: Missing option '--foo'. " in error1150    assert "Choose from" in separator1151    assert "foo" in choices1152    assert "bar" in choices115311541155def test_missing_envvar(runner):1156    cli = click.Command(1157        "cli", params=[click.Option(["--foo"], envvar="bar", required=True)]1158    )1159    result = runner.invoke(cli)1160    assert result.exit_code == 21161    assert "Error: Missing option '--foo'." in result.output1162    cli = click.Command(1163        "cli",1164        params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)],1165    )1166    result = runner.invoke(cli)1167    assert result.exit_code == 21168    assert "Error: Missing option '--foo' (env var: 'bar')." in result.output11691170    cli = click.Command(1171        "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]1172    )1173    result = runner.invoke(cli)1174    assert result.exit_code == 21175    assert "Error: Missing option '--foo'." in result.output117611771178def test_case_insensitive_choice(runner):1179    @click.command()1180    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))1181    def cmd(foo):1182        click.echo(foo)11831184    result = runner.invoke(cmd, ["--foo", "apple"])1185    assert result.exit_code == 01186    assert result.output == "Apple\n"11871188    result = runner.invoke(cmd, ["--foo", "oRANGe"])1189    assert result.exit_code == 01190    assert result.output == "Orange\n"11911192    result = runner.invoke(cmd, ["--foo", "Apple"])1193    assert result.exit_code == 01194    assert result.output == "Apple\n"11951196    @click.command()1197    @click.option("--foo", type=click.Choice(["Orange", "Apple"]))1198    def cmd2(foo):1199        click.echo(foo)12001201    result = runner.invoke(cmd2, ["--foo", "apple"])1202    assert result.exit_code == 212031204    result = runner.invoke(cmd2, ["--foo", "oRANGe"])1205    assert result.exit_code == 212061207    result = runner.invoke(cmd2, ["--foo", "Apple"])1208    assert result.exit_code == 0120912101211def test_case_insensitive_choice_returned_exactly(runner):1212    @click.command()1213    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))1214    def cmd(foo):1215        click.echo(foo)12161217    result = runner.invoke(cmd, ["--foo", "apple"])1218    assert result.exit_code == 01219    assert result.output == "Apple\n"122012211222def test_option_help_preserve_paragraphs(runner):1223    @click.command()1224    @click.option(1225        "-C",1226        "--config",1227        type=click.Path(),1228        help="""Configuration file to use.12291230        If not given, the environment variable CONFIG_FILE is consulted1231        and used if set. If neither are given, a default configuration1232        file is loaded.""",1233    )1234    def cmd(config):1235        pass12361237    result = runner.invoke(cmd, ["--help"])1238    assert result.exit_code == 01239    i = " " * 211240    assert (1241        "  -C, --config PATH  Configuration file to use.\n"1242        f"{i}\n"1243        f"{i}If not given, the environment variable CONFIG_FILE is\n"1244        f"{i}consulted and used if set. If neither are given, a default\n"1245        f"{i}configuration file is loaded."1246    ) in result.output124712481249def test_argument_custom_class(runner):1250    class CustomArgument(click.Argument):1251        def get_default(self, ctx, call=True):1252            """a dumb override of a default value for testing"""1253            return "I am a default"12541255    @click.command()1256    @click.argument("testarg", cls=CustomArgument, default="you won't see me")1257    def cmd(testarg):1258        click.echo(testarg)12591260    result = runner.invoke(cmd)1261    assert "I am a default" in result.output1262    assert "you won't see me" not in result.output126312641265def test_option_custom_class(runner):1266    class CustomOption(click.Option):1267        def get_help_record(self, ctx):1268            """a dumb override of a help text for testing"""1269            return ("--help", "I am a help text")12701271    @click.command()1272    @click.option("--testoption", cls=CustomOption, help="you won't see me")1273    def cmd(testoption):1274        click.echo(testoption)12751276    result = runner.invoke(cmd, ["--help"])1277    assert "I am a help text" in result.output1278    assert "you won't see me" not in result.output127912801281@pytest.mark.parametrize(1282    ("param_decl", "option_kwargs", "pass_argv"),1283    (1284        # there is a large potential parameter space to explore here1285        # this is just a very small sample of it1286        ("--opt", {}, []),1287        ("--opt", {"multiple": True}, []),1288        ("--opt", {"is_flag": True}, []),1289        ("--opt/--no-opt", {"is_flag": True, "default": None}, []),1290        ("--req", {"is_flag": True, "required": True}, ["--req"]),1291    ),1292)1293def test_option_custom_class_can_override_type_cast_value_and_never_sees_unset(1294    runner, param_decl, option_kwargs, pass_argv1295):1296    """1297    Test that overriding type_cast_value is supported12981299    In particular, the option is never passed an UNSET sentinel value.1300    """13011302    class CustomOption(click.Option):1303        def type_cast_value(self, ctx, value):1304            assert value is not UNSET1305            return value13061307    @click.command()1308    @click.option("myparam", param_decl, **option_kwargs, cls=CustomOption)1309    def cmd(myparam):1310        click.echo("ok")13111312    result = runner.invoke(cmd, pass_argv)1313    assert not result.exception1314    assert result.exit_code == 0131513161317def test_option_custom_class_reusable(runner):1318    """Ensure we can reuse a custom class option. See Issue #926"""13191320    class CustomOption(click.Option):1321        def get_help_record(self, ctx):1322            """a dumb override of a help text for testing"""1323            return ("--help", "I am a help text")13241325    # Assign to a variable to reuse the decorator.1326    testoption = click.option("--testoption", cls=CustomOption, help="you won't see me")13271328    @click.command()1329    @testoption1330    def cmd1(testoption):1331        click.echo(testoption)13321333    @click.command()1334    @testoption1335    def cmd2(testoption):1336        click.echo(testoption)13371338    # Both of the commands should have the --help option now.1339    for cmd in (cmd1, cmd2):1340        result = runner.invoke(cmd, ["--help"])1341        assert "I am a help text" in result.output1342        assert "you won't see me" not in result.output134313441345@pytest.mark.parametrize("custom_class", (True, False))1346@pytest.mark.parametrize(1347    ("name_specs", "expected"),1348    (1349        (1350            ("-h", "--help"),1351            "  -h, --help  Show this message and exit.\n",1352        ),1353        (1354            ("-h",),1355            "  -h      Show this message and exit.\n"1356            "  --help  Show this message and exit.\n",1357        ),1358        (1359            ("--help",),1360            "  --help  Show this message and exit.\n",1361        ),1362    ),1363)1364def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):1365    class CustomHelpOption(click.Option):1366        pass13671368    option_attrs = {}1369    if custom_class:1370        option_attrs["cls"] = CustomHelpOption13711372    @click.command()1373    @click.help_option(*name_specs, **option_attrs)1374    def cmd():1375        pass13761377    for arg in name_specs:1378        result = runner.invoke(cmd, [arg])1379        assert not result.exception1380        assert result.exit_code == 01381        assert expected in result.output138213831384def test_bool_flag_with_type(runner):1385    @click.command()1386    @click.option("--shout/--no-shout", default=False, type=bool)1387    def cmd(shout):1388        pass13891390    result = runner.invoke(cmd)1391    assert not result.exception139213931394def test_aliases_for_flags(runner):1395    @click.command()1396    @click.option("--warnings/--no-warnings", " /-W", default=True)1397    def cli(warnings):1398        click.echo(warnings)13991400    result = runner.invoke(cli, ["--warnings"])1401    assert result.output == "True\n"1402    result = runner.invoke(cli, ["--no-warnings"])1403    assert result.output == "False\n"1404    result = runner.invoke(cli, ["-W"])1405    assert result.output == "False\n"14061407    @click.command()1408    @click.option("--warnings/--no-warnings", "-w", default=True)1409    def cli_alt(warnings):1410        click.echo(warnings)14111412    result = runner.invoke(cli_alt, ["--warnings"])1413    assert result.output == "True\n"1414    result = runner.invoke(cli_alt, ["--no-warnings"])1415    assert result.output == "False\n"1416    result = runner.invoke(cli_alt, ["-w"])1417    assert result.output == "True\n"141814191420@pytest.mark.parametrize(1421    "option_args,expected",1422    [1423        (["--aggressive", "--all", "-a"], "aggressive"),1424        (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),1425        (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),1426        (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),1427        (["-a", "-b", "-c"], "a"),1428        (["-c", "-b", "-a"], "c"),1429        (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),1430        (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),1431        (["--from", "-f", "_from"], "_from"),1432        (["--return", "-r", "_ret"], "_ret"),1433        # A name derived from an option string is lower-cased.1434        (["--Foo-Bar"], "foo_bar"),1435        (["--FOO-BAR", "-F"], "foo_bar"),1436        # An identifier declaration goes through the same transform.1437        (["--foo-bar", "-f", "explicit_name"], "explicit_name"),1438        # Underscores survive, and every dash past the prefix becomes one.1439        (["--foo__bar"], "foo__bar"),1440        (["--foo--bar"], "foo__bar"),1441        (["--_foo"], "_foo"),1442        (["--__foo"], "__foo"),1443        (["---foo"], "_foo"),1444        (["-_"], "_"),1445        # A digit is only refused in the leading position.1446        (["--foo-0"], "foo_0"),1447    ],1448)1449def test_option_names(runner, option_args, expected):1450    @click.command()1451    @click.option(*option_args, is_flag=True)1452    def cmd(**kwargs):1453        click.echo(str(kwargs[expected]))14541455    assert cmd.params[0].name == expected14561457    for form in option_args:1458        if form.startswith("-"):1459            result = runner.invoke(cmd, [form])1460            assert result.output == "True\n"146114621463def test_option_name_case_transform_can_collide(runner):1464    """Two declarations that differ can transform to one name, with no warning."""14651466    @click.command()1467    @click.option("--\N{KELVIN SIGN}")1468    @click.option("--k")1469    def cmd(**kwargs):1470        click.echo(repr(kwargs))14711472    assert [p.name for p in cmd.params] == ["k", "k"]14731474    result = runner.invoke(cmd, ["--\N{KELVIN SIGN}", "kelvin", "--k", "ascii"])1475    assert not result.exception1476    assert result.output == "{'k': 'ascii'}\n"147714781479def test_option_name_case_variants_share_one_parameter(runner):1480    """Case variants of one option collapse onto a single parameter."""14811482    @click.command()1483    @click.option("--foo-bar")1484    @click.option("--Foo-Bar")1485    @click.option("--FOO-BAR")1486    def cmd(**kwargs):1487        click.echo(repr(kwargs))14881489    assert [p.name for p in cmd.params] == ["foo_bar"] * 314901491    with warnings.catch_warnings(record=True) as caught:1492        warnings.simplefilter("always")1493        result = runner.invoke(cmd, ["--help"], catch_exceptions=False)14941495    assert not [w for w in caught if issubclass(w.category, UserWarning)]1496    for spelling in ("--foo-bar", "--Foo-Bar", "--FOO-BAR"):1497        assert spelling in result.output14981499    for spelling, value in (("--foo-bar", "a"), ("--Foo-Bar", "b"), ("--FOO-BAR", "c")):1500        result = runner.invoke(cmd, [spelling, value])1501        assert not result.exception1502        assert result.output == f"{{'foo_bar': {value!r}}}\n"15031504    # Sharing one slot, the last spelling on the command line wins.1505    result = runner.invoke(cmd, ["--foo-bar", "a", "--FOO-BAR", "c"])1506    assert result.output == "{'foo_bar': 'c'}\n"150715081509def test_option_name_keeps_its_normalization_form(runner):1510    """A composed and a decomposed declaration are two distinct parameters."""1511    decomposed = "cafe\N{COMBINING ACUTE ACCENT}"1512    composed = unicodedata.normalize("NFC", decomposed)15131514    @click.command()1515    @click.option(f"--{composed}")1516    @click.option(f"--{decomposed}")1517    def cmd(**kwargs):1518        click.echo(repr(sorted(kwargs)))15191520    assert [p.name for p in cmd.params] == [composed, decomposed]15211522    result = runner.invoke(cmd, [])1523    assert not result.exception1524    assert result.output == f"['{decomposed}', '{composed}']\n"152515261527def test_option_name_must_be_an_identifier():1528    """A short option is the one refused shape an argument cannot be written as."""1529    with pytest.raises(TypeError, match="Could not determine name"):1530        click.Option(["-0"])153115321533def test_option_prompt_still_guards_against_a_nameless_option():1534    """An unexposed option can still be named ``""``, which ``prompt=True`` refuses."""1535    with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):1536        with pytest.raises(TypeError, match="'name' is required with 'prompt=True'"):1537            click.Option(["--0-file"], expose_value=False, prompt=True)153815391540def test_option_name_check_applies_when_not_exposed():1541    """An unexposed option is named ``""``, and says Click 9.0 will refuse it."""1542    with pytest.warns(DeprecationWarning, match="not a valid Python identifier"):1543        assert click.Option(["--0foo"], expose_value=False).name == ""154415451546def test_option_explicit_name_carries_a_refused_declaration(runner):1547    """An explicit name reaches a declaration the transform cannot name."""1548    seen = []15491550    def record(ctx, param, value):1551        seen.append(value)15521553    @click.command()1554    @click.option("--0foo", "zero_foo", expose_value=False, callback=record)1555    def cmd(**kwargs):1556        click.echo(repr(kwargs))15571558    assert cmd.params[0].name == "zero_foo"15591560    result = runner.invoke(cmd, ["--0foo", "value"])1561    assert not result.exception1562    assert result.output == "{}\n"1563    assert seen == ["value"]156415651566def test_option_name_may_be_a_python_keyword(runner):1567    """``str.isidentifier()`` accepts a keyword, so the check lets one through."""1568    with pytest.warns(DeprecationWarning, match="is a Python keyword"):15691570        @click.command()1571        @click.option("--from")1572        def cmd(**kwargs):1573            click.echo(repr(kwargs))15741575    assert cmd.params[0].name == "from"15761577    result = runner.invoke(cmd, ["--from", "here"])1578    assert not result.exception1579    assert result.output == "{'from': 'here'}\n"158015811582def test_flag_duplicate_names(runner):1583    with pytest.raises(ValueError, match="cannot use the same flag for true/false"):1584        click.Option(["--foo/--foo"], default=False)158515861587@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])1588def test_show_default_boolean_flag_name(runner, default, expect):1589    """When a boolean flag has distinct True/False opts, it should show1590    the default opt name instead of the default value. It should only1591    show one name even if multiple are declared.1592    """1593    opt = click.Option(1594        ("--cache/--no-cache", "--c/--nc"),1595        default=default,1596        show_default=True,1597        help="Enable/Disable the cache.",1598    )1599    ctx = click.Context(click.Command("test"))1600    assert opt.get_help_extra(ctx) == {"default": expect}1601    message = opt.get_help_record(ctx)[1]1602    assert f"[default: {expect}]" in message160316041605def test_show_true_default_boolean_flag_value(runner):1606    """When a boolean flag only has one opt and its default is True,1607    it will show the default value, not the opt name.1608    """1609    opt = click.Option(1610        ("--cache",),1611        is_flag=True,1612        show_default=True,1613        default=True,1614        help="Enable the cache.",1615    )1616    ctx = click.Context(click.Command("test"))1617    assert opt.get_help_extra(ctx) == {"default": "True"}1618    message = opt.get_help_record(ctx)[1]1619    assert "[default: True]" in message162016211622@pytest.mark.parametrize("default", [False, None])1623def test_hide_false_default_boolean_flag_value(runner, default):1624    """When a boolean flag only has one opt and its default is False or1625    None, it will not show the default1626    """1627    opt = click.Option(1628        ("--cache",),1629        is_flag=True,1630        show_default=True,1631        default=default,1632        help="Enable the cache.",1633    )1634    ctx = click.Context(click.Command("test"))1635    assert opt.get_help_extra(ctx) == {}1636    message = opt.get_help_record(ctx)[1]1637    assert "[default: " not in message163816391640def test_show_default_string(runner):1641    """When show_default is a string show that value as default."""1642    opt = click.Option(["--limit"], show_default="unlimited")1643    ctx = click.Context(click.Command("cli"))1644    assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}1645    message = opt.get_help_record(ctx)[1]1646    assert "[default: (unlimited)]" in message164716481649def test_string_show_default_shows_custom_string_in_prompt(runner):1650    @click.command()1651    @click.option(1652        "--arg1", show_default="custom", prompt=True, default="my-default-value"1653    )1654    def cmd(arg1):1655        pass16561657    result = runner.invoke(cmd, input="my-input", standalone_mode=False)1658    assert "(custom)" in result.output1659    assert "my-default-value" not in result.output166016611662class _StrictEq:1663    """Object whose ``__eq__`` raises on string comparison (like semver.Version)."""16641665    def __eq__(self, other):1666        if isinstance(other, str):1667            raise ValueError("cannot compare to string")1668        return NotImplemented16691670    def __str__(self):1671        return "strict"167216731674@pytest.mark.parametrize(1675    ("default", "expected"),1676    [1677        ("", '[default: ""]'),1678        (_StrictEq(), "[default: strict]"),1679    ],1680    ids=["empty-string", "non-string-comparable-object"],1681)1682def test_show_default_with_empty_string(runner, default, expected):1683    """The empty-string check in help rendering must not break on objects1684    whose ``__eq__`` raises for string operands.16851686    Regression test for https://github.com/pallets/click/issues/3298.1687    """1688    opt = click.Option(["--limit"], default=default, show_default=True)1689    ctx = click.Context(click.Command("cli"))1690    message = opt.get_help_record(ctx)[1]1691    assert expected in message169216931694def test_do_not_show_no_default(runner):1695    """When show_default is True and no default is set do not show None."""1696    opt = click.Option(["--limit"], show_default=True)1697    ctx = click.Context(click.Command("cli"))1698    assert opt.get_help_extra(ctx) == {}1699    message = opt.get_help_record(ctx)[1]1700    assert "[default: None]" not in message170117021703def test_do_not_show_default_empty_multiple():1704    """When show_default is True and multiple=True is set, it should not1705    print empty default value in --help output.1706    """1707    opt = click.Option(["-a"], multiple=True, help="values", show_default=True)1708    ctx = click.Context(click.Command("cli"))1709    assert opt.get_help_extra(ctx) == {}1710    message = opt.get_help_record(ctx)[1]1711    assert message == "values"171217131714@pytest.mark.parametrize(1715    ("ctx_value", "opt_value", "extra_value", "expect"),1716    [1717        (None, None, {}, False),1718        (None, False, {}, False),1719        (None, True, {"default": "1"}, True),1720        (False, None, {}, False),1721        (False, False, {}, False),1722        (False, True, {"default": "1"}, True),1723        (True, None, {"default": "1"}, True),1724        (True, False, {}, False),1725        (True, True, {"default": "1"}, True),1726        (False, "one", {"default": "(one)"}, True),1727    ],1728)1729def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):1730    ctx = click.Context(click.Command("test"), show_default=ctx_value)1731    opt = click.Option("-a", default=1, help="value", show_default=opt_value)1732    assert opt.get_help_extra(ctx) == extra_value1733    help = opt.get_help_record(ctx)[1]1734    assert ("default:" in help) is expect173517361737@pytest.mark.parametrize(1738    ("args", "expect"),1739    [1740        (None, (None, None, ())),1741        (["--opt"], ("flag", None, ())),1742        (["--opt", "-a", 42], ("flag", "42", ())),1743        (["--opt", "test", "-a", 42], ("test", "42", ())),1744        (["--opt=test", "-a", 42], ("test", "42", ())),1745        (["-o"], ("flag", None, ())),1746        (["-o", "-a", 42], ("flag", "42", ())),1747        (["-o", "test", "-a", 42], ("test", "42", ())),1748        (["-otest", "-a", 42], ("test", "42", ())),1749        (["a", "b", "c"], (None, None, ("a", "b", "c"))),1750        (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),1751        (["--opt", "test"], ("test", None, ())),1752        (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1753        (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1754    ],1755)1756def test_option_with_optional_value(runner, args, expect):1757    @click.command()1758    @click.option("-o", "--opt", is_flag=False, flag_value="flag")1759    @click.option("-a")1760    @click.argument("b", nargs=-1)1761    def cli(opt, a, b):1762        return opt, a, b17631764    result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)1765    assert result.return_value == expect176617671768def test_multiple_option_with_optional_value(runner):1769    cli = click.Command(1770        "cli",1771        params=[1772            click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),1773            click.Option(["-a"]),1774            click.Argument(["b"], nargs=-1),1775        ],1776        callback=lambda **kwargs: kwargs,1777    )1778    result = runner.invoke(1779        cli,1780        ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],1781        standalone_mode=False,1782        catch_exceptions=False,1783    )1784    assert result.return_value == {1785        "f": ("flag", "other", "flag"),1786        "a": "1",1787        "b": ("a", "b"),1788    }178917901791def test_type_from_flag_value():1792    param = click.Option(["-a", "x"], default=True, flag_value=4)1793    assert param.type is click.INT1794    param = click.Option(["-b", "x"], flag_value=8)1795    assert param.type is click.INT1796    # Non-basic types auto-detect as UNPROCESSED to avoid stringification.1797    param = click.Option(["-c", "x"], flag_value=EngineType.OSS)1798    assert param.type is click.UNPROCESSED1799    param = click.Option(["-d", "x"], flag_value=frozenset())1800    assert param.type is click.UNPROCESSED1801    param = click.Option(["-e", "x"], flag_value=set())1802    assert param.type is click.UNPROCESSED1803    param = click.Option(["-f", "x"], flag_value={})1804    assert param.type is click.UNPROCESSED180518061807@pytest.mark.parametrize(1808    ("opt_params", "args", "expected"),1809    [1810        # The type passed to the option is responsible to converting the value, whether1811        # we pass the option flag or not.1812        ({"type": bool}, [], False),1813        ({"type": bool}, ["--foo"], True),1814        ({"type": click.BOOL}, [], False),1815        ({"type": click.BOOL}, ["--foo"], True),1816        ({"type": str}, [], None),1817        ({"type": str}, ["--foo"], "True"),1818        # Default value is given as-is to the --foo option when it is not passed,1819        # whatever the type. Now if --foo is passed, the value is always True, whatever1820        # the type. In both case the type of the option is responsible for the1821        # conversion of the value.1822        ({"type": bool, "default": True}, [], True),1823        ({"type": bool, "default": True}, ["--foo"], True),1824        ({"type": bool, "default": False}, [], False),1825        ({"type": bool, "default": False}, ["--foo"], True),1826        # ({"type": bool, "default": "foo"}, [], "foo"),1827        ({"type": bool, "default": "foo"}, ["--foo"], True),1828        ({"type": bool, "default": None}, [], None),1829        ({"type": bool, "default": None}, ["--foo"], True),1830        ({"type": click.BOOL, "default": True}, [], True),1831        ({"type": click.BOOL, "default": True}, ["--foo"], True),1832        ({"type": click.BOOL, "default": False}, [], False),1833        ({"type": click.BOOL, "default": False}, ["--foo"], True),1834        # ({"type": click.BOOL, "default": "foo"}, [], "foo"),1835        ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),1836        ({"type": click.BOOL, "default": None}, [], None),1837        ({"type": click.BOOL, "default": None}, ["--foo"], True),1838        ({"type": str, "default": True}, [], "True"),1839        ({"type": str, "default": True}, ["--foo"], "True"),1840        ({"type": str, "default": False}, [], "False"),1841        ({"type": str, "default": False}, ["--foo"], "True"),1842        ({"type": str, "default": "foo"}, [], "foo"),1843        ({"type": str, "default": "foo"}, ["--foo"], "True"),1844        ({"type": str, "default": None}, [], None),1845        ({"type": str, "default": None}, ["--foo"], "True"),1846        # Flag value is given as-is to the --foo option when it is passed, then1847        # converted by the option type.1848        ({"type": bool, "flag_value": True}, [], False),1849        ({"type": bool, "flag_value": True}, ["--foo"], True),1850        ({"type": bool, "flag_value": False}, [], False),1851        ({"type": bool, "flag_value": False}, ["--foo"], False),1852        ({"type": bool, "flag_value": None}, [], False),1853        ({"type": bool, "flag_value": None}, ["--foo"], None),1854        ({"type": click.BOOL, "flag_value": True}, [], False),1855        ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),1856        ({"type": click.BOOL, "flag_value": False}, [], False),1857        ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),1858        ({"type": click.BOOL, "flag_value": None}, [], False),1859        ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),1860        ({"type": str, "flag_value": True}, [], None),1861        ({"type": str, "flag_value": True}, ["--foo"], "True"),1862        ({"type": str, "flag_value": False}, [], None),1863        ({"type": str, "flag_value": False}, ["--foo"], "False"),1864        ({"type": str, "flag_value": "foo"}, [], None),1865        ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1866        ({"type": str, "flag_value": None}, [], None),1867        ({"type": str, "flag_value": None}, ["--foo"], None),1868        # Not passing --foo returns the default value as-is, in its Python type, then1869        # converted by the option type. For boolean flags, default=True is a literal1870        # value, not a sentinel meaning "activate flag". So it is NOT substituted with1871        # flag_value. See: https://github.com/pallets/click/issues/31111872        # https://github.com/pallets/click/pull/32391873        ({"type": bool, "default": True, "flag_value": True}, [], True),1874        ({"type": bool, "default": True, "flag_value": False}, [], True),1875        ({"type": bool, "default": False, "flag_value": True}, [], False),1876        ({"type": bool, "default": False, "flag_value": False}, [], False),1877        ({"type": bool, "default": None, "flag_value": True}, [], None),1878        ({"type": bool, "default": None, "flag_value": False}, [], None),1879        ({"type": str, "default": True, "flag_value": True}, [], "True"),1880        ({"type": str, "default": True, "flag_value": False}, [], "False"),1881        ({"type": str, "default": False, "flag_value": True}, [], "False"),1882        ({"type": str, "default": False, "flag_value": False}, [], "False"),1883        ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1884        ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),1885        ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),1886        ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),1887        ({"type": str, "default": None, "flag_value": True}, [], None),1888        ({"type": str, "default": None, "flag_value": False}, [], None),1889        # Passing --foo returns the flag_value that was explicitly set by the user,1890        # with its Python type, but still converted by the option type.1891        ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),1892        ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),1893        ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),1894        ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),1895        ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),1896        ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),1897        ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),1898        ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),1899        ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),1900        ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),1901        ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),1902        ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),1903        ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),1904        ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),1905        ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),1906        ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),1907    ],1908)1909def test_flag_value_and_default(runner, opt_params, args, expected):1910    @click.command()1911    @click.option("--foo", is_flag=True, **opt_params)1912    def cmd(foo):1913        click.echo(repr(foo), nl=False)19141915    result = runner.invoke(cmd, args)1916    assert result.output == repr(expected)191719181919@pytest.mark.parametrize(1920    ("args", "opts"),1921    [1922        ([], {"type": bool, "default": "foo"}),1923        ([], {"type": click.BOOL, "default": "foo"}),1924        (["--foo"], {"type": bool, "flag_value": "foo"}),1925        (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),1926    ],1927)1928def test_invalid_flag_definition(runner, args, opts):1929    @click.command()1930    @click.option("--foo", is_flag=True, **opts)1931    def cmd(foo):1932        click.echo(foo)19331934    result = runner.invoke(cmd, args)1935    assert (1936        "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1937        in result.output1938    )193919401941@pytest.mark.parametrize(1942    ("default", "args", "expected"),1943    # These test cases are similar to the ones in1944    # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync.1945    (1946        # Each option is returning its own flag_value, whatever the default is.1947        (True, ["--js"], "js"),1948        (True, ["--xml"], "xml"),1949        (False, ["--js"], "js"),1950        (False, ["--xml"], "xml"),1951        (None, ["--js"], "js"),1952        (None, ["--xml"], "xml"),1953        (UNSET, ["--js"], "js"),1954        (UNSET, ["--xml"], "xml"),1955        # Check that the last option wins when both are specified.1956        (True, ["--js", "--xml"], "xml"),1957        (True, ["--xml", "--js"], "js"),1958        # Check that the default is returned as-is when no option is specified.1959        ("js", [], "js"),1960        ("xml", [], "xml"),1961        ("jS", [], "jS"),1962        ("xMl", [], "xMl"),1963        (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),1964        (None, [], None),1965        # Special case: UNSET is not provided as-is to the callback, but normalized to1966        # None.1967        (UNSET, [], None),1968        # Special case: if default=True and flag_value is set, the value returned is the1969        # flag_value, not the True Python value itself.1970        (True, [], "js"),1971        # Non-string defaults are process as strings by the default Parameter's type.1972        (False, [], "False"),1973        (42, [], "42"),1974        (12.3, [], "12.3"),1975    ),1976)1977def test_default_dual_option_callback(runner, default, args, expected):1978    """Check how default is processed by the callback when options compete for the same1979    variable name.19801981    Reproduction of the issue reported in1982    https://github.com/pallets/click/pull/3030#discussion_r227157181919831984    .. hint::1985        Similar to ``test_basic.py::test_flag_value_dual_options``.19861987        ``test_defaults.py::test_shared_param_prefers_first_default``1988        is a smoke-test complement that exercises both default placements.1989    """19901991    def _my_func(ctx, param, value):1992        # Print the value received by the callback as-is, so we can check for it.1993        return f"Callback value: {value!r}"19941995    @click.command()1996    @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)1997    @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)1998    def main(fmt):1999        click.secho(fmt, nl=False)2000

The first 2,000 of 3,945 lines.