Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

2,575 lines · 84.9 KiB · Python

Last changed by

Show default string in prompt (#3328)Rowlando13before adoption76552ff

History of this file

Take it

1import enum2import os3import re4import sys5import tempfile6from contextlib import nullcontext7from typing import Literal89if sys.version_info < (3, 11):10    enum.StrEnum = enum.Enum  # type: ignore[assignment]1112import pytest1314import click15from click import Option16from click import UNPROCESSED17from click._utils import UNSET18from click.testing import CliRunner192021def test_prefixes(runner):22    @click.command()23    @click.option("++foo", is_flag=True, help="das foo")24    @click.option("--bar", is_flag=True, help="das bar")25    def cli(foo, bar):26        click.echo(f"foo={foo} bar={bar}")2728    result = runner.invoke(cli, ["++foo", "--bar"])29    assert not result.exception30    assert result.output == "foo=True bar=True\n"3132    result = runner.invoke(cli, ["--help"])33    assert re.search(r"\+\+foo\s+das foo", result.output) is not None34    assert re.search(r"--bar\s+das bar", result.output) is not None353637def test_invalid_option(runner):38    with pytest.raises(TypeError, match="name was passed") as exc_info:39        click.Option(["foo"])4041    message = str(exc_info.value)42    assert "name was passed (foo)" in message43    assert "declare an argument" in message44    assert "'--foo'" in message454647@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])48def test_deprecated_usage(runner, deprecated):49    @click.command()50    @click.option("--foo", default="bar", deprecated=deprecated)51    def cmd(foo):52        click.echo(foo)5354    result = runner.invoke(cmd, ["--help"])55    assert "(DEPRECATED" in result.output5657    if isinstance(deprecated, str):58        assert deprecated in result.output596061@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])62def test_deprecated_warning(runner, deprecated):63    @click.command()64    @click.option(65        "--my-option", required=False, deprecated=deprecated, default="default option"66    )67    def cli(my_option: str):68        click.echo(f"{my_option}")6970    # defaults should not give a deprecated warning71    result = runner.invoke(cli, [])72    assert result.exit_code == 0, result.output73    assert "is deprecated" not in result.output7475    result = runner.invoke(cli, ["--my-option", "hello"])76    assert result.exit_code == 0, result.output77    assert "option 'my_option' is deprecated" in result.output7879    if isinstance(deprecated, str):80        assert deprecated in result.output818283def test_deprecated_required(runner):84    with pytest.raises(ValueError, match="is deprecated and still required"):85        click.Option(["--a"], required=True, deprecated=True)868788def test_deprecated_prompt(runner):89    with pytest.raises(ValueError, match="`deprecated` options cannot use `prompt`"):90        click.Option(["--a"], prompt=True, deprecated=True)919293def test_invalid_nargs(runner):94    with pytest.raises(TypeError, match="nargs=-1 is not supported for options."):9596        @click.command()97        @click.option("--foo", nargs=-1)98        def cli(foo):99            pass100101102def test_nargs_tup_composite_mult(runner):103    @click.command()104    @click.option("--item", type=(str, int), multiple=True)105    def copy(item):106        for name, id in item:107            click.echo(f"name={name} id={id:d}")108109    result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])110    assert not result.exception111    assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]112113114def test_counting(runner):115    @click.command()116    @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))117    def cli(v):118        click.echo(f"verbosity={v:d}")119120    result = runner.invoke(cli, ["-vvv"])121    assert not result.exception122    assert result.output == "verbosity=3\n"123124    result = runner.invoke(cli, ["-vvvv"])125    assert result.exception126    assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output127128    result = runner.invoke(cli, [])129    assert not result.exception130    assert result.output == "verbosity=0\n"131132    result = runner.invoke(cli, ["--help"])133    assert re.search(r"-v\s+Verbosity", result.output) is not None134135136@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])137def test_unknown_options(runner, unknown_flag):138    @click.command()139    def cli():140        pass141142    result = runner.invoke(cli, [unknown_flag])143    assert result.exception144    assert f"No such option: {unknown_flag}" in result.output145146147@pytest.mark.parametrize(148    ("value", "expect"),149    [150        ("--cat", "Did you mean --count?"),151        ("--bounds", "(Possible options: --bound, --count)"),152        ("--bount", "(Possible options: --bound, --count)"),153    ],154)155def test_suggest_possible_options(runner, value, expect):156    cli = click.Command(157        "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]158    )159    result = runner.invoke(cli, [value])160    assert expect in result.output161162163def test_multiple_required(runner):164    @click.command()165    @click.option("-m", "--message", multiple=True, required=True)166    def cli(message):167        click.echo("\n".join(message))168169    result = runner.invoke(cli, ["-m", "foo", "-mbar"])170    assert not result.exception171    assert result.output == "foo\nbar\n"172173    result = runner.invoke(cli, [])174    assert result.exception175    assert "Error: Missing option '-m' / '--message'." in result.output176177178@pytest.mark.parametrize(179    ("multiple", "nargs", "default", "expected"),180    [181        # If multiple values are allowed, defaults should be iterable.182        (True, 1, [], ()),183        (True, 1, (), ()),184        (True, 1, tuple(), ()),185        (True, 1, set(), ()),186        (True, 1, frozenset(), ()),187        (True, 1, {}, ()),188        # Special values.189        (True, 1, None, ()),190        (True, 1, UNSET, ()),191        # Number of values are kept as-is in the default.192        (True, 1, [1], (1,)),193        (True, 1, [1, 2], (1, 2)),194        (True, 1, [1, 2, 3], (1, 2, 3)),195        (True, 1, [1.1, 2.2], (1.1, 2.2)),196        (True, 1, ["1", "2"], ("1", "2")),197        (True, 1, [None, None], (None, None)),198        # Contrary to list or tuples, native Python types not supported by Click are199        # not recognized and are converted to the default format: tuple of strings.200        # Refs: https://github.com/pallets/click/issues/3036201        (True, 1, {1, 2}, ("1", "2")),202        (True, 1, frozenset([1, 2]), ("1", "2")),203        (True, 1, {1: "a", 2: "b"}, ("1", "2")),204        # Multiple values with nargs > 1.205        (True, 2, [], ()),206        (True, 2, (), ()),207        (True, 2, tuple(), ()),208        (True, 2, set(), ()),209        (True, 2, frozenset(), ()),210        (True, 2, {}, ()),211        (True, 2, None, ()),212        (True, 2, UNSET, ()),213        (True, 2, [[1, 2]], ((1, 2),)),214        (True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))),215        (True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))),216        (True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))),217        (True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))),218        (True, 2, [[None, None], [None, None]], ((None, None), (None, None))),219        (True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))),220        (True, 2, [[1, 2.2], None], ((1, 2.2), None)),221        # Default of the right length works for non-multiples.222        (False, 2, [1, 2], (1, 2)),223    ],224)225def test_good_defaults_for_multiple(runner, multiple, nargs, default, expected):226    """Comprehensive check of default-value processing for options with227    ``multiple=True`` and/or ``nargs > 1``.228229    .. hint::230        An argument-specific equivalent is in231        ``test_arguments.py::test_good_defaults_for_nargs``.232233        Smoke tests are in ``test_defaults.py``:234        ``test_multiple_defaults`` (explicit ``type=FLOAT``)235        and ``test_nargs_plus_multiple`` (``nargs=2``).236    """237238    @click.command()239    @click.option("-a", multiple=multiple, nargs=nargs, default=default)240    def cmd(a):241        click.echo(repr(a), nl=False)242243    result = runner.invoke(cmd)244    assert result.output == repr(expected)245246247@pytest.mark.parametrize(248    ("multiple", "nargs", "default", "exception", "message"),249    [250        # Non-iterables defaults.251        (252            True,253            1,254            "Yo",255            None,256            "Error: Invalid value for '-a': Value must be an iterable.",257        ),258        (259            True,260            1,261            "",262            None,263            "Error: Invalid value for '-a': Value must be an iterable.",264        ),265        (266            True,267            1,268            True,269            None,270            "Error: Invalid value for '-a': Value must be an iterable.",271        ),272        (273            True,274            1,275            False,276            None,277            "Error: Invalid value for '-a': Value must be an iterable.",278        ),279        (280            True,281            1,282            12,283            None,284            "Error: Invalid value for '-a': Value must be an iterable.",285        ),286        (287            True,288            1,289            7.9,290            None,291            "Error: Invalid value for '-a': Value must be an iterable.",292        ),293        (294            False,295            2,296            42,297            None,298            "Error: Invalid value for '-a': Value must be an iterable.",299        ),300        (301            True,302            2,303            ["test string which is not a list in the list"],304            None,305            "Error: Invalid value for '-a': Value must be an iterable.",306        ),307        # Multiple options, each with 2 args, but with wrong length.308        (309            True,310            2,311            (1,),312            None,313            "Error: Invalid value for '-a': Value must be an iterable.",314        ),315        (316            True,317            2,318            (1, 2, 3),319            None,320            "Error: Invalid value for '-a': Value must be an iterable.",321        ),322        (323            True,324            2,325            [tuple()],326            ValueError,327            r"'nargs' must be 0 \(or None\) for type <click\.types\.Tuple object at "328            r"0x[0-9A-Fa-f]+>, but it was 2\.",329        ),330        (331            True,332            2,333            [(1,)],334            ValueError,335            r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "336            r"0x[0-9A-Fa-f]+>, but it was 2\.",337        ),338        (339            True,340            2,341            [(1, 2, 3)],342            ValueError,343            r"'nargs' must be 3 \(or None\) for type <click\.types\.Tuple object at "344            r"0x[0-9A-Fa-f]+>, but it was 2\.",345        ),346        # A mix of valid and invalid defaults.347        (348            True,349            2,350            [[1, 2.2], []],351            None,352            "Error: Invalid value for '-a': 2 values are required, but 0 were given.",353        ),354        # Default values that are iterable but not of the right length.355        (356            False,357            2,358            [1],359            None,360            "Error: Invalid value for '-a': Takes 2 values but 1 was given.",361        ),362        (363            True,364            2,365            [[1]],366            ValueError,367            r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "368            r"0x[0-9A-Fa-f]+>, but it was 2\.",369        ),370    ],371)372def test_bad_defaults_for_multiple(373    runner, multiple, nargs, default, exception, message374):375    if exception:376        assert issubclass(exception, Exception)377    else:378        assert exception is None379380    with (381        pytest.raises(exception, match=re.compile(message))382        if exception383        else nullcontext()384    ):385386        @click.command()387        @click.option("-a", multiple=multiple, nargs=nargs, default=default)388        def cmd(a):389            click.echo(repr(a))390391        result = runner.invoke(cmd)392        assert message in result.stderr393394395@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])396def test_empty_envvar(runner, env_key):397    @click.command()398    @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")399    def cli(mypath):400        click.echo(f"mypath: {mypath}")401402    result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO")403    assert result.exception is None404    assert result.output == "mypath: None\n"405406407def test_multiple_envvar(runner):408    @click.command()409    @click.option("--arg", multiple=True)410    def cmd(arg):411        click.echo("|".join(arg))412413    result = runner.invoke(414        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}415    )416    assert not result.exception417    assert result.output == "foo|bar|baz\n"418419    @click.command()420    @click.option("--arg", multiple=True, envvar="X")421    def cmd(arg):422        click.echo("|".join(arg))423424    result = runner.invoke(cmd, [], env={"X": "foo bar baz"})425    assert not result.exception426    assert result.output == "foo|bar|baz\n"427428    @click.command()429    @click.option("--arg", multiple=True, type=click.Path())430    def cmd(arg):431        click.echo("|".join(arg))432433    result = runner.invoke(434        cmd,435        [],436        auto_envvar_prefix="TEST",437        env={"TEST_ARG": f"foo{os.path.pathsep}bar"},438    )439    assert not result.exception440    assert result.output == "foo|bar\n"441442443@pytest.mark.parametrize(444    ("envvar_name", "envvar_value", "expected"),445    (446        # Lower-cased variations of value.447        ("SHOUT", "true", True),448        ("SHOUT", "false", False),449        # Title-cased variations of value.450        ("SHOUT", "True", True),451        ("SHOUT", "False", False),452        # Upper-cased variations of value.453        ("SHOUT", "TRUE", True),454        ("SHOUT", "FALSE", False),455        # Random-cased variations of value.456        ("SHOUT", "TruE", True),457        ("SHOUT", "truE", True),458        ("SHOUT", "FaLsE", False),459        ("SHOUT", "falsE", False),460        # Extra spaces around the value.461        ("SHOUT", "true    ", True),462        ("SHOUT", "  true  ", True),463        ("SHOUT", "    true", True),464        ("SHOUT", "false   ", False),465        ("SHOUT", "  false ", False),466        ("SHOUT", "   false", False),467        # Integer variations.468        ("SHOUT", "1", True),469        ("SHOUT", "0", False),470        # Alternative states.471        ("SHOUT", "t", True),472        ("SHOUT", "T", True),473        ("SHOUT", "  T  ", True),474        ("SHOUT", "f", False),475        ("SHOUT", "y", True),476        ("SHOUT", "n", False),477        ("SHOUT", "yes", True),478        ("SHOUT", "no", False),479        ("SHOUT", "on", True),480        ("SHOUT", "off", False),481        # Blank value variations.482        ("SHOUT", None, False),483        ("SHOUT", "", False),484        ("SHOUT", " ", False),485        ("SHOUT", "       ", False),486        # Variable names are not stripped of spaces and so don't match the487        # flag, which then naturraly takes its default value.488        ("SHOUT    ", "True", False),489        ("SHOUT    ", "False", False),490        ("  SHOUT  ", "True", False),491        ("  SHOUT  ", "False", False),492        ("    SHOUT", "True", False),493        ("    SHOUT", "False", False),494        ("SH    OUT", "True", False),495        ("SH    OUT", "False", False),496        # Same for random and reverse environment variable names: they are not497        # recognized by the option.498        ("RANDOM", "True", False),499        ("NO_SHOUT", "True", False),500        ("NO_SHOUT", "False", False),501        ("NOSHOUT", "True", False),502        ("NOSHOUT", "False", False),503    ),504)505def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):506    assert isinstance(envvar_name, str)507    assert isinstance(envvar_value, str) or envvar_value is None508509    @click.command()510    @click.option("--shout/--no-shout", envvar="SHOUT")511    def cli(shout):512        click.echo(repr(shout), nl=False)513514    result = runner.invoke(cli, [], env={envvar_name: envvar_value})515    assert result.exit_code == 0516    assert result.output == repr(expected)517518519@pytest.mark.parametrize(520    "value",521    (522        # Extra spaces inside the value.523        "tr ue",524        "fa lse",525        # Numbers.526        "10",527        "01",528        "00",529        "11",530        "0.0",531        "1.1",532        # Random strings.533        "randomstring",534        "None",535        "'None'",536        "A B",537        " 1 2 ",538        "9.3",539        "a;n",540        "x:y",541        "i/o",542    ),543)544def test_boolean_envvar_bad_values(runner, value):545    @click.command()546    @click.option("--shout/--no-shout", envvar="SHOUT")547    def cli(shout):548        click.echo(shout)549550    result = runner.invoke(cli, [], env={"SHOUT": value})551    assert result.exit_code == 2552    assert (553        f"Invalid value for '--shout': {value!r} is not a valid boolean."554        in result.output555    )556557558def test_multiple_default_help(runner):559    @click.command()560    @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)561    @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)562    def cmd(arg, arg2):563        pass564565    result = runner.invoke(cmd, ["--help"])566    assert not result.exception567    assert "foo, bar" in result.output568    assert "1, 2" in result.output569570571def test_show_default_default_map(runner):572    @click.command()573    @click.option("--arg", default="a", show_default=True)574    def cmd(arg):575        click.echo(arg)576577    result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})578579    assert not result.exception580    assert "[default: b]" in result.output581582583def test_multiple_default_type():584    opt = click.Option(["-a"], multiple=True, default=(1, 2))585    assert opt.nargs == 1586    assert opt.multiple587    assert opt.type is click.INT588    ctx = click.Context(click.Command("test"))589    assert opt.get_default(ctx) == (1, 2)590591592def test_multiple_default_composite_type():593    opt = click.Option(["-a"], multiple=True, default=[(1, "a")])594    assert opt.nargs == 2595    assert opt.multiple596    assert isinstance(opt.type, click.Tuple)597    assert opt.type.types == [click.INT, click.STRING]598    ctx = click.Context(click.Command("test"))599    assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)600601602def test_parse_multiple_default_composite_type(runner):603    @click.command()604    @click.option("-a", multiple=True, default=("a", "b"))605    @click.option("-b", multiple=True, default=[(1, "a")])606    def cmd(a, b):607        click.echo(a)608        click.echo(b)609610    # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())611    # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"612    result = runner.invoke(cmd)613    assert result.output == "('a', 'b')\n((1, 'a'),)\n"614615616def test_dynamic_default_help_unset(runner):617    @click.command()618    @click.option(619        "--username",620        prompt=True,621        default=lambda: os.environ.get("USER", ""),622        show_default=True,623    )624    def cmd(username):625        print("Hello,", username)626627    result = runner.invoke(cmd, ["--help"])628    assert result.exit_code == 0629    assert "--username" in result.output630    assert "lambda" not in result.output631    assert "(dynamic)" in result.output632633634def test_dynamic_default_help_text(runner):635    @click.command()636    @click.option(637        "--username",638        prompt=True,639        default=lambda: os.environ.get("USER", ""),640        show_default="current user",641    )642    def cmd(username):643        print("Hello,", username)644645    result = runner.invoke(cmd, ["--help"])646    assert result.exit_code == 0647    assert "--username" in result.output648    assert "lambda" not in result.output649    assert "(current user)" in result.output650651652def test_dynamic_default_help_special_method(runner):653    class Value:654        def __call__(self):655            return 42656657        def __str__(self):658            return "special value"659660    opt = click.Option(["-a"], default=Value(), show_default=True)661    ctx = click.Context(click.Command("cli"))662    assert opt.get_help_extra(ctx) == {"default": "special value"}663    assert "special value" in opt.get_help_record(ctx)[1]664665666@pytest.mark.parametrize(667    ("type", "expect"),668    [669        (click.IntRange(1, 32), "1<=x<=32"),670        (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),671        (click.IntRange(1), "x>=1"),672        (click.IntRange(max=32), "x<=32"),673    ],674)675def test_intrange_default_help_text(type, expect):676    option = click.Option(["--num"], type=type, show_default=True, default=2)677    context = click.Context(click.Command("test"))678    assert option.get_help_extra(context) == {"default": "2", "range": expect}679    result = option.get_help_record(context)[1]680    assert expect in result681682683def test_count_default_type_help():684    """A count option with the default type should not show >=0 in help."""685    option = click.Option(["--count"], count=True, help="some words")686    context = click.Context(click.Command("test"))687    assert option.get_help_extra(context) == {}688    result = option.get_help_record(context)[1]689    assert result == "some words"690691692def test_file_type_help_default():693    """The default for a File type is a filename string. The string694    should be displayed in help, not an open file object.695696    Type casting is only applied to defaults in processing, not when697    getting the default value.698    """699    option = click.Option(700        ["--in"], type=click.File(), default=__file__, show_default=True701    )702    context = click.Context(click.Command("test"))703    assert option.get_help_extra(context) == {"default": __file__}704    result = option.get_help_record(context)[1]705    assert __file__ in result706707708def test_toupper_envvar_prefix(runner):709    @click.command()710    @click.option("--arg")711    def cmd(arg):712        click.echo(arg)713714    result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})715    assert not result.exception716    assert result.output == "foo\n"717718719def test_nargs_envvar(runner):720    @click.command()721    @click.option("--arg", nargs=2)722    def cmd(arg):723        click.echo("|".join(arg))724725    result = runner.invoke(726        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}727    )728    assert not result.exception729    assert result.output == "foo|bar\n"730731    @click.command()732    @click.option("--arg", nargs=2, multiple=True)733    def cmd(arg):734        for item in arg:735            click.echo("|".join(item))736737    result = runner.invoke(738        cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}739    )740    assert not result.exception741    assert result.output == "x|1\ny|2\n"742743744def test_show_envvar(runner):745    @click.command()746    @click.option("--arg1", envvar="ARG1", show_envvar=True)747    def cmd(arg):748        pass749750    result = runner.invoke(cmd, ["--help"])751    assert not result.exception752    assert "ARG1" in result.output753754755def test_show_envvar_auto_prefix(runner):756    @click.command()757    @click.option("--arg1", show_envvar=True)758    def cmd(arg):759        pass760761    result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")762    assert not result.exception763    assert "TEST_ARG1" in result.output764765766def test_show_envvar_auto_prefix_dash_in_command(runner):767    @click.group()768    def cli():769        pass770771    @cli.command()772    @click.option("--baz", show_envvar=True)773    def foo_bar(baz):774        pass775776    result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")777    assert not result.exception778    assert "TEST_FOO_BAR_BAZ" in result.output779780781def test_custom_validation(runner):782    def validate_pos_int(ctx, param, value):783        if value < 0:784            raise click.BadParameter("Value needs to be positive")785        return value786787    @click.command()788    @click.option("--foo", callback=validate_pos_int, default=1)789    def cmd(foo):790        click.echo(foo)791792    result = runner.invoke(cmd, ["--foo", "-1"])793    assert "Invalid value for '--foo': Value needs to be positive" in result.output794795    result = runner.invoke(cmd, ["--foo", "42"])796    assert result.output == "42\n"797798799def test_callback_validates_prompt(runner, monkeypatch):800    def validate(ctx, param, value):801        if value < 0:802            raise click.BadParameter("should be positive")803804        return value805806    @click.command()807    @click.option("-a", type=int, callback=validate, prompt=True)808    def cli(a):809        click.echo(a)810811    result = runner.invoke(cli, input="-12\n60\n")812    assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"813814815def test_winstyle_options(runner):816    @click.command()817    @click.option("/debug;/no-debug", help="Enables or disables debug mode.")818    def cmd(debug):819        click.echo(debug)820821    result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])822    assert result.output == "True\n"823    result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])824    assert result.output == "False\n"825    result = runner.invoke(cmd, [], help_option_names=["/?"])826    assert result.output == "False\n"827    result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])828    assert "/debug; /no-debug  Enables or disables debug mode." in result.output829    assert "/?                 Show this message and exit." in result.output830831832def test_legacy_options(runner):833    @click.command()834    @click.option("-whatever")835    def cmd(whatever):836        click.echo(whatever)837838    result = runner.invoke(cmd, ["-whatever", "42"])839    assert result.output == "42\n"840    result = runner.invoke(cmd, ["-whatever=23"])841    assert result.output == "23\n"842843844@pytest.mark.parametrize(845    ("value", "expect_missing", "processed_value"),846    [847        (UNSET, True, None),848        (None, False, None),849        # Default type of the argument is str, so everything is processed as strings.850        ("", False, ""),851        ("  ", False, "  "),852        ("foo", False, "foo"),853        ("12", False, "12"),854        (12, False, "12"),855        (12.1, False, "12.1"),856        (list(), False, "[]"),857        (tuple(), False, "()"),858        (set(), False, "set()"),859        (frozenset(), False, "frozenset()"),860        (dict(), False, "{}"),861    ],862)863def test_required_option(value, expect_missing, processed_value):864    ctx = click.Context(click.Command(""))865    argument = click.Option(["-a"], required=True)866867    if expect_missing:868        with pytest.raises(click.MissingParameter) as excinfo:869            argument.process_value(ctx, value)870        assert str(excinfo.value) == "Missing parameter: a"871872    else:873        value = argument.process_value(ctx, value)874        assert value == processed_value875876877def test_missing_required_flag(runner):878    cli = click.Command(879        "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]880    )881    result = runner.invoke(cli)882    assert result.exit_code == 2883    assert "Error: Missing option '--on'." in result.output884885886def test_missing_choice(runner):887    @click.command()888    @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)889    def cmd(foo):890        click.echo(foo)891892    result = runner.invoke(cmd)893    assert result.exit_code == 2894    error, separator, choices = result.output.partition("Choose from")895    assert "Error: Missing option '--foo'. " in error896    assert "Choose from" in separator897    assert "foo" in choices898    assert "bar" in choices899900901def test_missing_envvar(runner):902    cli = click.Command(903        "cli", params=[click.Option(["--foo"], envvar="bar", required=True)]904    )905    result = runner.invoke(cli)906    assert result.exit_code == 2907    assert "Error: Missing option '--foo'." in result.output908    cli = click.Command(909        "cli",910        params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)],911    )912    result = runner.invoke(cli)913    assert result.exit_code == 2914    assert "Error: Missing option '--foo' (env var: 'bar')." in result.output915916    cli = click.Command(917        "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]918    )919    result = runner.invoke(cli)920    assert result.exit_code == 2921    assert "Error: Missing option '--foo'." in result.output922923924def test_case_insensitive_choice(runner):925    @click.command()926    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))927    def cmd(foo):928        click.echo(foo)929930    result = runner.invoke(cmd, ["--foo", "apple"])931    assert result.exit_code == 0932    assert result.output == "Apple\n"933934    result = runner.invoke(cmd, ["--foo", "oRANGe"])935    assert result.exit_code == 0936    assert result.output == "Orange\n"937938    result = runner.invoke(cmd, ["--foo", "Apple"])939    assert result.exit_code == 0940    assert result.output == "Apple\n"941942    @click.command()943    @click.option("--foo", type=click.Choice(["Orange", "Apple"]))944    def cmd2(foo):945        click.echo(foo)946947    result = runner.invoke(cmd2, ["--foo", "apple"])948    assert result.exit_code == 2949950    result = runner.invoke(cmd2, ["--foo", "oRANGe"])951    assert result.exit_code == 2952953    result = runner.invoke(cmd2, ["--foo", "Apple"])954    assert result.exit_code == 0955956957def test_case_insensitive_choice_returned_exactly(runner):958    @click.command()959    @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))960    def cmd(foo):961        click.echo(foo)962963    result = runner.invoke(cmd, ["--foo", "apple"])964    assert result.exit_code == 0965    assert result.output == "Apple\n"966967968def test_option_help_preserve_paragraphs(runner):969    @click.command()970    @click.option(971        "-C",972        "--config",973        type=click.Path(),974        help="""Configuration file to use.975976        If not given, the environment variable CONFIG_FILE is consulted977        and used if set. If neither are given, a default configuration978        file is loaded.""",979    )980    def cmd(config):981        pass982983    result = runner.invoke(cmd, ["--help"])984    assert result.exit_code == 0985    i = " " * 21986    assert (987        "  -C, --config PATH  Configuration file to use.\n"988        f"{i}\n"989        f"{i}If not given, the environment variable CONFIG_FILE is\n"990        f"{i}consulted and used if set. If neither are given, a default\n"991        f"{i}configuration file is loaded."992    ) in result.output993994995def test_argument_custom_class(runner):996    class CustomArgument(click.Argument):997        def get_default(self, ctx, call=True):998            """a dumb override of a default value for testing"""999            return "I am a default"10001001    @click.command()1002    @click.argument("testarg", cls=CustomArgument, default="you wont see me")1003    def cmd(testarg):1004        click.echo(testarg)10051006    result = runner.invoke(cmd)1007    assert "I am a default" in result.output1008    assert "you wont see me" not in result.output100910101011def test_option_custom_class(runner):1012    class CustomOption(click.Option):1013        def get_help_record(self, ctx):1014            """a dumb override of a help text for testing"""1015            return ("--help", "I am a help text")10161017    @click.command()1018    @click.option("--testoption", cls=CustomOption, help="you wont see me")1019    def cmd(testoption):1020        click.echo(testoption)10211022    result = runner.invoke(cmd, ["--help"])1023    assert "I am a help text" in result.output1024    assert "you wont see me" not in result.output102510261027@pytest.mark.parametrize(1028    ("param_decl", "option_kwargs", "pass_argv"),1029    (1030        # there is a large potential parameter space to explore here1031        # this is just a very small sample of it1032        ("--opt", {}, []),1033        ("--opt", {"multiple": True}, []),1034        ("--opt", {"is_flag": True}, []),1035        ("--opt/--no-opt", {"is_flag": True, "default": None}, []),1036        ("--req", {"is_flag": True, "required": True}, ["--req"]),1037    ),1038)1039def test_option_custom_class_can_override_type_cast_value_and_never_sees_unset(1040    runner, param_decl, option_kwargs, pass_argv1041):1042    """1043    Test that overriding type_cast_value is supported10441045    In particular, the option is never passed an UNSET sentinel value.1046    """10471048    class CustomOption(click.Option):1049        def type_cast_value(self, ctx, value):1050            assert value is not UNSET1051            return value10521053    @click.command()1054    @click.option("myparam", param_decl, **option_kwargs, cls=CustomOption)1055    def cmd(myparam):1056        click.echo("ok")10571058    result = runner.invoke(cmd, pass_argv)1059    assert not result.exception1060    assert result.exit_code == 0106110621063def test_option_custom_class_reusable(runner):1064    """Ensure we can reuse a custom class option. See Issue #926"""10651066    class CustomOption(click.Option):1067        def get_help_record(self, ctx):1068            """a dumb override of a help text for testing"""1069            return ("--help", "I am a help text")10701071    # Assign to a variable to re-use the decorator.1072    testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")10731074    @click.command()1075    @testoption1076    def cmd1(testoption):1077        click.echo(testoption)10781079    @click.command()1080    @testoption1081    def cmd2(testoption):1082        click.echo(testoption)10831084    # Both of the commands should have the --help option now.1085    for cmd in (cmd1, cmd2):1086        result = runner.invoke(cmd, ["--help"])1087        assert "I am a help text" in result.output1088        assert "you wont see me" not in result.output108910901091@pytest.mark.parametrize("custom_class", (True, False))1092@pytest.mark.parametrize(1093    ("name_specs", "expected"),1094    (1095        (1096            ("-h", "--help"),1097            "  -h, --help  Show this message and exit.\n",1098        ),1099        (1100            ("-h",),1101            "  -h      Show this message and exit.\n"1102            "  --help  Show this message and exit.\n",1103        ),1104        (1105            ("--help",),1106            "  --help  Show this message and exit.\n",1107        ),1108    ),1109)1110def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):1111    class CustomHelpOption(click.Option):1112        pass11131114    option_attrs = {}1115    if custom_class:1116        option_attrs["cls"] = CustomHelpOption11171118    @click.command()1119    @click.help_option(*name_specs, **option_attrs)1120    def cmd():1121        pass11221123    for arg in name_specs:1124        result = runner.invoke(cmd, [arg])1125        assert not result.exception1126        assert result.exit_code == 01127        assert expected in result.output112811291130def test_bool_flag_with_type(runner):1131    @click.command()1132    @click.option("--shout/--no-shout", default=False, type=bool)1133    def cmd(shout):1134        pass11351136    result = runner.invoke(cmd)1137    assert not result.exception113811391140def test_aliases_for_flags(runner):1141    @click.command()1142    @click.option("--warnings/--no-warnings", " /-W", default=True)1143    def cli(warnings):1144        click.echo(warnings)11451146    result = runner.invoke(cli, ["--warnings"])1147    assert result.output == "True\n"1148    result = runner.invoke(cli, ["--no-warnings"])1149    assert result.output == "False\n"1150    result = runner.invoke(cli, ["-W"])1151    assert result.output == "False\n"11521153    @click.command()1154    @click.option("--warnings/--no-warnings", "-w", default=True)1155    def cli_alt(warnings):1156        click.echo(warnings)11571158    result = runner.invoke(cli_alt, ["--warnings"])1159    assert result.output == "True\n"1160    result = runner.invoke(cli_alt, ["--no-warnings"])1161    assert result.output == "False\n"1162    result = runner.invoke(cli_alt, ["-w"])1163    assert result.output == "True\n"116411651166@pytest.mark.parametrize(1167    "option_args,expected",1168    [1169        (["--aggressive", "--all", "-a"], "aggressive"),1170        (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),1171        (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),1172        (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),1173        (["-a", "-b", "-c"], "a"),1174        (["-c", "-b", "-a"], "c"),1175        (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),1176        (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),1177        (["--from", "-f", "_from"], "_from"),1178        (["--return", "-r", "_ret"], "_ret"),1179    ],1180)1181def test_option_names(runner, option_args, expected):1182    @click.command()1183    @click.option(*option_args, is_flag=True)1184    def cmd(**kwargs):1185        click.echo(str(kwargs[expected]))11861187    assert cmd.params[0].name == expected11881189    for form in option_args:1190        if form.startswith("-"):1191            result = runner.invoke(cmd, [form])1192            assert result.output == "True\n"119311941195def test_flag_duplicate_names(runner):1196    with pytest.raises(ValueError, match="cannot use the same flag for true/false"):1197        click.Option(["--foo/--foo"], default=False)119811991200@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])1201def test_show_default_boolean_flag_name(runner, default, expect):1202    """When a boolean flag has distinct True/False opts, it should show1203    the default opt name instead of the default value. It should only1204    show one name even if multiple are declared.1205    """1206    opt = click.Option(1207        ("--cache/--no-cache", "--c/--nc"),1208        default=default,1209        show_default=True,1210        help="Enable/Disable the cache.",1211    )1212    ctx = click.Context(click.Command("test"))1213    assert opt.get_help_extra(ctx) == {"default": expect}1214    message = opt.get_help_record(ctx)[1]1215    assert f"[default: {expect}]" in message121612171218def test_show_true_default_boolean_flag_value(runner):1219    """When a boolean flag only has one opt and its default is True,1220    it will show the default value, not the opt name.1221    """1222    opt = click.Option(1223        ("--cache",),1224        is_flag=True,1225        show_default=True,1226        default=True,1227        help="Enable the cache.",1228    )1229    ctx = click.Context(click.Command("test"))1230    assert opt.get_help_extra(ctx) == {"default": "True"}1231    message = opt.get_help_record(ctx)[1]1232    assert "[default: True]" in message123312341235@pytest.mark.parametrize("default", [False, None])1236def test_hide_false_default_boolean_flag_value(runner, default):1237    """When a boolean flag only has one opt and its default is False or1238    None, it will not show the default1239    """1240    opt = click.Option(1241        ("--cache",),1242        is_flag=True,1243        show_default=True,1244        default=default,1245        help="Enable the cache.",1246    )1247    ctx = click.Context(click.Command("test"))1248    assert opt.get_help_extra(ctx) == {}1249    message = opt.get_help_record(ctx)[1]1250    assert "[default: " not in message125112521253def test_show_default_string(runner):1254    """When show_default is a string show that value as default."""1255    opt = click.Option(["--limit"], show_default="unlimited")1256    ctx = click.Context(click.Command("cli"))1257    assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}1258    message = opt.get_help_record(ctx)[1]1259    assert "[default: (unlimited)]" in message126012611262def test_string_show_default_shows_custom_string_in_prompt(runner):1263    @click.command()1264    @click.option(1265        "--arg1", show_default="custom", prompt=True, default="my-default-value"1266    )1267    def cmd(arg1):1268        pass12691270    result = runner.invoke(cmd, input="my-input", standalone_mode=False)1271    assert "(custom)" in result.output1272    assert "my-default-value" not in result.output127312741275class _StrictEq:1276    """Object whose ``__eq__`` raises on string comparison (like semver.Version)."""12771278    def __eq__(self, other):1279        if isinstance(other, str):1280            raise ValueError("cannot compare to string")1281        return NotImplemented12821283    def __str__(self):1284        return "strict"128512861287@pytest.mark.parametrize(1288    ("default", "expected"),1289    [1290        ("", '[default: ""]'),1291        (_StrictEq(), "[default: strict]"),1292    ],1293    ids=["empty-string", "non-string-comparable-object"],1294)1295def test_show_default_with_empty_string(runner, default, expected):1296    """The empty-string check in help rendering must not break on objects1297    whose ``__eq__`` raises for string operands.12981299    Regression test for https://github.com/pallets/click/issues/3298.1300    """1301    opt = click.Option(["--limit"], default=default, show_default=True)1302    ctx = click.Context(click.Command("cli"))1303    message = opt.get_help_record(ctx)[1]1304    assert expected in message130513061307def test_do_not_show_no_default(runner):1308    """When show_default is True and no default is set do not show None."""1309    opt = click.Option(["--limit"], show_default=True)1310    ctx = click.Context(click.Command("cli"))1311    assert opt.get_help_extra(ctx) == {}1312    message = opt.get_help_record(ctx)[1]1313    assert "[default: None]" not in message131413151316def test_do_not_show_default_empty_multiple():1317    """When show_default is True and multiple=True is set, it should not1318    print empty default value in --help output.1319    """1320    opt = click.Option(["-a"], multiple=True, help="values", show_default=True)1321    ctx = click.Context(click.Command("cli"))1322    assert opt.get_help_extra(ctx) == {}1323    message = opt.get_help_record(ctx)[1]1324    assert message == "values"132513261327@pytest.mark.parametrize(1328    ("ctx_value", "opt_value", "extra_value", "expect"),1329    [1330        (None, None, {}, False),1331        (None, False, {}, False),1332        (None, True, {"default": "1"}, True),1333        (False, None, {}, False),1334        (False, False, {}, False),1335        (False, True, {"default": "1"}, True),1336        (True, None, {"default": "1"}, True),1337        (True, False, {}, False),1338        (True, True, {"default": "1"}, True),1339        (False, "one", {"default": "(one)"}, True),1340    ],1341)1342def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):1343    ctx = click.Context(click.Command("test"), show_default=ctx_value)1344    opt = click.Option("-a", default=1, help="value", show_default=opt_value)1345    assert opt.get_help_extra(ctx) == extra_value1346    help = opt.get_help_record(ctx)[1]1347    assert ("default:" in help) is expect134813491350@pytest.mark.parametrize(1351    ("args", "expect"),1352    [1353        (None, (None, None, ())),1354        (["--opt"], ("flag", None, ())),1355        (["--opt", "-a", 42], ("flag", "42", ())),1356        (["--opt", "test", "-a", 42], ("test", "42", ())),1357        (["--opt=test", "-a", 42], ("test", "42", ())),1358        (["-o"], ("flag", None, ())),1359        (["-o", "-a", 42], ("flag", "42", ())),1360        (["-o", "test", "-a", 42], ("test", "42", ())),1361        (["-otest", "-a", 42], ("test", "42", ())),1362        (["a", "b", "c"], (None, None, ("a", "b", "c"))),1363        (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),1364        (["--opt", "test"], ("test", None, ())),1365        (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1366        (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1367    ],1368)1369def test_option_with_optional_value(runner, args, expect):1370    @click.command()1371    @click.option("-o", "--opt", is_flag=False, flag_value="flag")1372    @click.option("-a")1373    @click.argument("b", nargs=-1)1374    def cli(opt, a, b):1375        return opt, a, b13761377    result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)1378    assert result.return_value == expect137913801381def test_multiple_option_with_optional_value(runner):1382    cli = click.Command(1383        "cli",1384        params=[1385            click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),1386            click.Option(["-a"]),1387            click.Argument(["b"], nargs=-1),1388        ],1389        callback=lambda **kwargs: kwargs,1390    )1391    result = runner.invoke(1392        cli,1393        ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],1394        standalone_mode=False,1395        catch_exceptions=False,1396    )1397    assert result.return_value == {1398        "f": ("flag", "other", "flag"),1399        "a": "1",1400        "b": ("a", "b"),1401    }140214031404def test_type_from_flag_value():1405    param = click.Option(["-a", "x"], default=True, flag_value=4)1406    assert param.type is click.INT1407    param = click.Option(["-b", "x"], flag_value=8)1408    assert param.type is click.INT140914101411@pytest.mark.parametrize(1412    ("opt_params", "args", "expected"),1413    [1414        # The type passed to the option is responsible to converting the value, whether1415        # we pass the option flag or not.1416        ({"type": bool}, [], False),1417        ({"type": bool}, ["--foo"], True),1418        ({"type": click.BOOL}, [], False),1419        ({"type": click.BOOL}, ["--foo"], True),1420        ({"type": str}, [], None),1421        ({"type": str}, ["--foo"], "True"),1422        # Default value is given as-is to the --foo option when it is not passed,1423        # whatever the type. Now if --foo is passed, the value is always True, whatever1424        # the type. In both case the type of the option is responsible for the1425        # conversion of the value.1426        ({"type": bool, "default": True}, [], True),1427        ({"type": bool, "default": True}, ["--foo"], True),1428        ({"type": bool, "default": False}, [], False),1429        ({"type": bool, "default": False}, ["--foo"], True),1430        # ({"type": bool, "default": "foo"}, [], "foo"),1431        ({"type": bool, "default": "foo"}, ["--foo"], True),1432        ({"type": bool, "default": None}, [], None),1433        ({"type": bool, "default": None}, ["--foo"], True),1434        ({"type": click.BOOL, "default": True}, [], True),1435        ({"type": click.BOOL, "default": True}, ["--foo"], True),1436        ({"type": click.BOOL, "default": False}, [], False),1437        ({"type": click.BOOL, "default": False}, ["--foo"], True),1438        # ({"type": click.BOOL, "default": "foo"}, [], "foo"),1439        ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),1440        ({"type": click.BOOL, "default": None}, [], None),1441        ({"type": click.BOOL, "default": None}, ["--foo"], True),1442        ({"type": str, "default": True}, [], "True"),1443        ({"type": str, "default": True}, ["--foo"], "True"),1444        ({"type": str, "default": False}, [], "False"),1445        ({"type": str, "default": False}, ["--foo"], "True"),1446        ({"type": str, "default": "foo"}, [], "foo"),1447        ({"type": str, "default": "foo"}, ["--foo"], "True"),1448        ({"type": str, "default": None}, [], None),1449        ({"type": str, "default": None}, ["--foo"], "True"),1450        # Flag value is given as-is to the --foo option when it is passed, then1451        # converted by the option type.1452        ({"type": bool, "flag_value": True}, [], False),1453        ({"type": bool, "flag_value": True}, ["--foo"], True),1454        ({"type": bool, "flag_value": False}, [], False),1455        ({"type": bool, "flag_value": False}, ["--foo"], False),1456        ({"type": bool, "flag_value": None}, [], False),1457        ({"type": bool, "flag_value": None}, ["--foo"], None),1458        ({"type": click.BOOL, "flag_value": True}, [], False),1459        ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),1460        ({"type": click.BOOL, "flag_value": False}, [], False),1461        ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),1462        ({"type": click.BOOL, "flag_value": None}, [], False),1463        ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),1464        ({"type": str, "flag_value": True}, [], None),1465        ({"type": str, "flag_value": True}, ["--foo"], "True"),1466        ({"type": str, "flag_value": False}, [], None),1467        ({"type": str, "flag_value": False}, ["--foo"], "False"),1468        ({"type": str, "flag_value": "foo"}, [], None),1469        ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1470        ({"type": str, "flag_value": None}, [], None),1471        ({"type": str, "flag_value": None}, ["--foo"], None),1472        # Not passing --foo returns the default value as-is, in its Python type, then1473        # converted by the option type. For boolean flags, default=True is a literal1474        # value, not a sentinel meaning "activate flag". So it is NOT substituted with1475        # flag_value. See: https://github.com/pallets/click/issues/31111476        # https://github.com/pallets/click/pull/32391477        ({"type": bool, "default": True, "flag_value": True}, [], True),1478        ({"type": bool, "default": True, "flag_value": False}, [], True),1479        ({"type": bool, "default": False, "flag_value": True}, [], False),1480        ({"type": bool, "default": False, "flag_value": False}, [], False),1481        ({"type": bool, "default": None, "flag_value": True}, [], None),1482        ({"type": bool, "default": None, "flag_value": False}, [], None),1483        ({"type": str, "default": True, "flag_value": True}, [], "True"),1484        ({"type": str, "default": True, "flag_value": False}, [], "False"),1485        ({"type": str, "default": False, "flag_value": True}, [], "False"),1486        ({"type": str, "default": False, "flag_value": False}, [], "False"),1487        ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1488        ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),1489        ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),1490        ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),1491        ({"type": str, "default": None, "flag_value": True}, [], None),1492        ({"type": str, "default": None, "flag_value": False}, [], None),1493        # Passing --foo returns the flag_value that was explicitly set by the user,1494        # with its Python type, but still converted by the option type.1495        ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),1496        ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),1497        ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),1498        ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),1499        ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),1500        ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),1501        ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),1502        ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),1503        ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),1504        ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),1505        ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),1506        ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),1507        ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),1508        ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),1509        ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),1510        ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),1511    ],1512)1513def test_flag_value_and_default(runner, opt_params, args, expected):1514    @click.command()1515    @click.option("--foo", is_flag=True, **opt_params)1516    def cmd(foo):1517        click.echo(repr(foo), nl=False)15181519    result = runner.invoke(cmd, args)1520    assert result.output == repr(expected)152115221523@pytest.mark.parametrize(1524    ("args", "opts"),1525    [1526        ([], {"type": bool, "default": "foo"}),1527        ([], {"type": click.BOOL, "default": "foo"}),1528        (["--foo"], {"type": bool, "flag_value": "foo"}),1529        (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),1530    ],1531)1532def test_invalid_flag_definition(runner, args, opts):1533    @click.command()1534    @click.option("--foo", is_flag=True, **opts)1535    def cmd(foo):1536        click.echo(foo)15371538    result = runner.invoke(cmd, args)1539    assert (1540        "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1541        in result.output1542    )154315441545@pytest.mark.parametrize(1546    ("default", "args", "expected"),1547    # These test cases are similar to the ones in1548    # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync.1549    (1550        # Each option is returning its own flag_value, whatever the default is.1551        (True, ["--js"], "js"),1552        (True, ["--xml"], "xml"),1553        (False, ["--js"], "js"),1554        (False, ["--xml"], "xml"),1555        (None, ["--js"], "js"),1556        (None, ["--xml"], "xml"),1557        (UNSET, ["--js"], "js"),1558        (UNSET, ["--xml"], "xml"),1559        # Check that the last option wins when both are specified.1560        (True, ["--js", "--xml"], "xml"),1561        (True, ["--xml", "--js"], "js"),1562        # Check that the default is returned as-is when no option is specified.1563        ("js", [], "js"),1564        ("xml", [], "xml"),1565        ("jS", [], "jS"),1566        ("xMl", [], "xMl"),1567        (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),1568        (None, [], None),1569        # Special case: UNSET is not provided as-is to the callback, but normalized to1570        # None.1571        (UNSET, [], None),1572        # Special case: if default=True and flag_value is set, the value returned is the1573        # flag_value, not the True Python value itself.1574        (True, [], "js"),1575        # Non-string defaults are process as strings by the default Parameter's type.1576        (False, [], "False"),1577        (42, [], "42"),1578        (12.3, [], "12.3"),1579    ),1580)1581def test_default_dual_option_callback(runner, default, args, expected):1582    """Check how default is processed by the callback when options compete for the same1583    variable name.15841585    Reproduction of the issue reported in1586    https://github.com/pallets/click/pull/3030#discussion_r227157181915871588    .. hint::1589        Similar to ``test_basic.py::test_flag_value_dual_options``.15901591        ``test_defaults.py::test_shared_param_prefers_first_default``1592        is a smoke-test complement that exercises both default placements.1593    """15941595    def _my_func(ctx, param, value):1596        # Print the value received by the callback as-is, so we can check for it.1597        return f"Callback value: {value!r}"15981599    @click.command()1600    @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)1601    @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)1602    def main(fmt):1603        click.secho(fmt, nl=False)16041605    result = runner.invoke(main, args)1606    assert result.output == f"Callback value: {expected!r}"1607    assert result.exit_code == 0160816091610@pytest.mark.parametrize(1611    ("flag_value", "envvar_value", "expected"),1612    [1613        # The envvar match exactly the flag value and is case-sensitive.1614        ("bar", "bar", "bar"),1615        ("BAR", "BAR", "BAR"),1616        (" bar ", " bar ", " bar "),1617        ("42", "42", "42"),1618        ("None", "None", "None"),1619        ("True", "True", "True"),1620        ("False", "False", "False"),1621        ("true", "true", "true"),1622        ("false", "false", "false"),1623        ("A B", "A B", "A B"),1624        (" 1 2 ", " 1 2 ", " 1 2 "),1625        ("9.3", "9.3", "9.3"),1626        ("a;n", "a;n", "a;n"),1627        ("x:y", "x:y", "x:y"),1628        ("i/o", "i/o", "i/o"),1629        # Empty or absent envvar is consider unset, so the flag default value is1630        # returned, which is None in this case.1631        ("bar", "", None),1632        ("bar", None, None),1633        ("BAR", "", None),1634        ("BAR", None, None),1635        (" bar ", "", None),1636        (" bar ", None, None),1637        (42, "", None),1638        (42, None, None),1639        ("42", "", None),1640        ("42", None, None),1641        (None, "", None),1642        (None, None, None),1643        ("None", "", None),1644        ("None", None, None),1645        (True, "", None),1646        (True, None, None),1647        ("True", "", None),1648        ("True", None, None),1649        ("true", "", None),1650        ("true", None, None),1651        (False, "", None),1652        (False, None, None),1653        ("False", "", None),1654        ("False", None, None),1655        ("false", "", None),1656        ("false", None, None),1657        # Activate the flag with a value recognized as True by the envvar, which1658        # returns the flag_value.1659        ("bar", "True", "bar"),1660        ("bar", "true", "bar"),1661        ("bar", "trUe", "bar"),1662        ("bar", "  TRUE  ", "bar"),1663        ("bar", "1", "bar"),1664        ("bar", "yes", "bar"),1665        ("bar", "on", "bar"),1666        ("bar", "t", "bar"),1667        ("bar", "y", "bar"),1668        # Deactivating the flag with a value recognized as False by the envvar, which1669        # explicitly return the 'False' as the option is explicitly declared as a1670        # string.1671        ("bar", "False", "False"),1672        ("bar", "false", "False"),1673        ("bar", "faLse", "False"),1674        ("bar", "  FALSE  ", "False"),1675        ("bar", "0", "False"),1676        ("bar", "no", "False"),1677        ("bar", "off", "False"),1678        ("bar", "f", "False"),1679        ("bar", "n", "False"),1680        # Any other value than the flag_value, or a recogned True or False value, fails1681        # to explicitly activate or deactivate the flag. So the flag default value is1682        # returned, which is None in this case.1683        ("bar", " bar ", None),1684        ("bar", "BAR", None),1685        ("bar", "random", None),1686        ("bar", "bar random", None),1687        ("bar", "random bar", None),1688        ("BAR", "bar", None),1689        (" bar ", "bar", None),1690        (" bar ", "BAR", None),1691        (42, "42", None),1692        (42, "foo", None),1693        (None, "foo", None),1694        ("None", "foo", None),1695    ],1696)1697def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):1698    """Ensure that flag_value is recognized by the envvar."""16991700    @click.command()1701    @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER")1702    def cmd(upper):1703        click.echo(repr(upper), nl=False)17041705    result = runner.invoke(cmd, env={"UPPER": envvar_value})1706    assert result.exit_code == 01707    assert result.output == repr(expected)170817091710@pytest.mark.parametrize(1711    ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"),1712    [1713        # Not boolean flags.1714        ("-a", {"type": int}, False, False),1715        ("-a", {"type": bool}, False, False),1716        ("-a", {"default": True}, False, False),1717        ("-a", {"default": False}, False, False),1718        ("-a", {"flag_value": 1}, True, False),1719        # Boolean flags.1720        ("-a", {"is_flag": True}, True, True),1721        ("-a/-A", {}, True, True),1722        ("-a", {"flag_value": True}, True, True),1723        # Non-flag with flag_value.1724        ("-a", {"is_flag": False, "flag_value": 1}, False, False),1725    ],1726)1727def test_flag_auto_detection(1728    opt_decls, opt_params, expect_is_flag, expect_is_bool_flag1729):1730    option = Option([opt_decls], **opt_params)1731    assert option.is_flag is expect_is_flag1732    assert option.is_bool_flag is expect_is_bool_flag173317341735@pytest.mark.parametrize(1736    ("kwargs", "message"),1737    [1738        ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),1739        ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),1740    ],1741)1742def test_invalid_flag_combinations(runner, kwargs, message):1743    with pytest.raises(TypeError) as e:1744        click.Option(["-a"], **kwargs)17451746    assert message in str(e.value)174717481749def test_non_flag_with_non_negatable_default(runner):1750    class NonNegatable:1751        def __bool__(self):1752            raise ValueError("Cannot negate this object")17531754    @click.command()1755    @click.option("--foo", default=NonNegatable())1756    def cmd(foo):1757        pass17581759    result = runner.invoke(cmd)1760    assert result.exit_code == 0176117621763class HashType(enum.Enum):1764    MD5 = "MD5"1765    SHA1 = "SHA1"1766    SHA256 = "SHA-256"176717681769class Number(enum.IntEnum):1770    ONE = enum.auto()1771    TWO = enum.auto()177217731774class Letter(enum.StrEnum):1775    NAME_1 = "Value-1"1776    NAME_2 = "Value_2"1777    NAME_3 = "42_value"177817791780class Color(enum.Flag):1781    RED = enum.auto()1782    GREEN = enum.auto()1783    BLUE = enum.auto()178417851786class ColorInt(enum.IntFlag):1787    RED = enum.auto()1788    GREEN = enum.auto()1789    BLUE = enum.auto()179017911792@pytest.mark.parametrize(1793    ("choices", "metavar"),1794    [1795        (["foo", "bar"], "[TEXT]"),1796        ([1, 2], "[INTEGER]"),1797        ([1.0, 2.0], "[FLOAT]"),1798        ([True, False], "[BOOLEAN]"),1799        (["foo", 1], "[TEXT|INTEGER]"),1800        (HashType, "[HASHTYPE]"),1801        (Number, "[NUMBER]"),1802        (Letter, "[LETTER]"),1803        (Color, "[COLOR]"),1804        (ColorInt, "[COLORINT]"),1805    ],1806)1807def test_choice_usage_rendering(runner, choices, metavar):1808    """BY default ``--help`` prints choice's values in the usage message.18091810    But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of1811    values.18121813    Also check that usage error message always suggests the actual values.1814    """18151816    @click.command()1817    @click.option("-g", type=click.Choice(choices))1818    def cli_with_choices(g):1819        pass18201821    @click.command()1822    @click.option("-g", type=click.Choice(choices), show_choices=False)1823    def cli_without_choices(g):1824        pass18251826    display_values = tuple(1827        i.name if isinstance(i, enum.Enum) else str(i) for i in choices1828    )18291830    # Check that the choices values are rendered as-is in the usage message.1831    result = runner.invoke(cli_with_choices, ["--help"])1832    assert f"[{'|'.join(display_values)}]" in result.stdout1833    assert not result.stderr1834    assert result.exit_code == 018351836    # Check that the metavar is rendered instead of the choices values themselves.1837    result = runner.invoke(cli_without_choices, ["--help"])1838    assert metavar in result.stdout1839    assert not result.stderr1840    assert result.exit_code == 018411842    # Check the usage error message suggests the actual accepted values.1843    for cli in (cli_with_choices, cli_without_choices):1844        result = runner.invoke(cli, ["-g", "random"])1845        assert (1846            "\n\nError: Invalid value for '-g': 'random' is not one of "1847            f"{', '.join(map(repr, display_values))}.\n" in result.stderr1848        )1849        assert not result.stdout1850        assert result.exit_code == 2185118521853@pytest.mark.parametrize(1854    ("choices", "default", "default_string"),1855    [1856        (["foo", "bar"], "bar", "bar"),1857        # The default value is not enforced to be in the choices.1858        (["foo", "bar"], "random", "random"),1859        # None cannot be a default value as-is: it left the default value as unset.1860        (["foo", "bar"], None, None),1861        ([0, 1], 0, "0"),1862        # Values are not coerced to the type of the choice, even if equivalent.1863        ([0, 1], 0.0, "0.0"),1864        ([1, 2], 2, "2"),1865        ([1.0, 2.0], 2, "2"),1866        ([1.0, 2.0], 2.0, "2.0"),1867        ([True, False], True, "True"),1868        ([True, False], False, "False"),1869        (["foo", 1], "foo", "foo"),1870        (["foo", 1], 1, "1"),1871        # Enum choices are rendered as their names, not values.1872        # See: https://github.com/pallets/click/issues/29111873        (HashType, HashType.SHA1, "SHA1"),1874        # Enum choices allow defaults strings that are their names.1875        (HashType, HashType.SHA256, "SHA256"),1876        (HashType, "SHA256", "SHA256"),1877        (Number, Number.TWO, "TWO"),1878        (Number, "TWO", "TWO"),1879        (Letter, Letter.NAME_1, "NAME_1"),1880        (Letter, Letter.NAME_2, "NAME_2"),1881        (Letter, Letter.NAME_3, "NAME_3"),1882        (Letter, "NAME_1", "NAME_1"),1883        (Letter, "NAME_2", "NAME_2"),1884        (Letter, "NAME_3", "NAME_3"),1885        (Color, Color.GREEN, "GREEN"),1886        (Color, "GREEN", "GREEN"),1887        (ColorInt, ColorInt.GREEN, "GREEN"),1888        (ColorInt, "GREEN", "GREEN"),1889    ],1890)1891def test_choice_default_rendering(runner, choices, default, default_string):1892    @click.command()1893    @click.option("-g", type=click.Choice(choices), default=default, show_default=True)1894    def cli_with_choices(g):1895        pass18961897    # Check that the default value is kept normalized to the type of the choice.1898    assert cli_with_choices.params[0].default == default18991900    result = runner.invoke(cli_with_choices, ["--help"])1901    extra_usage = f"[default: {default_string}]"1902    if default_string is None:1903        assert extra_usage not in result.output1904    else:1905        assert extra_usage in result.output190619071908@pytest.mark.parametrize(1909    "opts_one,opts_two",1910    [1911        # No duplicate shortnames1912        (1913            ("-a", "--aardvark"),1914            ("-a", "--avocado"),1915        ),1916        # No duplicate long names1917        (1918            ("-a", "--aardvark"),1919            ("-b", "--aardvark"),1920        ),1921    ],1922)1923def test_duplicate_names_warning(runner, opts_one, opts_two):1924    @click.command()1925    @click.option(*opts_one)1926    @click.option(*opts_two)1927    def cli(one, two):1928        pass19291930    with pytest.warns(UserWarning):1931        runner.invoke(cli, [])193219331934OBJECT_SENTINEL = object()1935"""An object-based sentinel value."""193619371938class EnumSentinel(enum.Enum):1939    FALSY_SENTINEL = object()19401941    def __bool__(self) -> Literal[False]:1942        """Force the sentinel to be falsy to make sure it is not caught by Click1943        internal implementation.19441945        Falsy sentinels have been discussed in:1946        https://github.com/pallets/click/pull/3030#pullrequestreview-31066047951947        https://github.com/pallets/click/pull/3030#pullrequestreview-31084715521948        """1949        return False195019511952# Any kind of sentinel value is recognized by Click as a valid flag value.1953@pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))1954@pytest.mark.parametrize(1955    ("args", "expected"),1956    (1957        # Option default to None.1958        ([], None),1959        # Config has no default value, and no flag value, so it requires an argument.1960        (1961            ["--config"],1962            re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1963        ),1964        (1965            ["--no-config", "--config"],1966            re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1967        ),1968        # Passing --no-config defaults to the sentinel value because of the flag_value,1969        # and then the custom type receives that sentinel and returns a message.1970        (["--no-config"], "No configuration file provided."),1971        # Passing --config with an argument returns the file path.1972        (["--config", "foo.conf"], "foo.conf"),1973        # An argument is not allowed for --no-config, so it raises an error.1974        (1975            ["--no-config", "foo.conf"],1976            re.compile(1977                r"Usage: main \[OPTIONS\]\n"1978                r"Try 'main --help' for help.\n"1979                r"\n"1980                r"Error: Got unexpected extra argument (.+)\n"1981            ),1982        ),1983        # Passing --config with an argument that does not exist raises an error.1984        (1985            ["--config", "random-file.conf"],1986            re.compile(1987                r"Usage: main \[OPTIONS\]\n"1988                r"Try 'main --help' for help.\n"1989                r"\n"1990                r"Error: Invalid value for '-c' / '--config': "1991                r"File 'random-file.conf' does not exist.\n"1992            ),1993        ),1994        (1995            ["--config", "--no-config"],1996            re.compile(1997                r"Usage: main \[OPTIONS\]\n"1998                r"Try 'main --help' for help.\n"1999                r"\n"2000                r"Error: Invalid value for '-c' / '--config': "

The first 2,000 of 2,575 lines.