test_options.py
This file
Path
tests/test_options.py
2,321 lines · 76.2 KiB · Python
Last changed by
Fix handling of options which set both is_flag=False and flag_value=... (#3152)Rowlando13before adoptionebcd548
History of this fileTake 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 @click.command()227 @click.option("-a", multiple=multiple, nargs=nargs, default=default)228 def cmd(a):229 click.echo(repr(a), nl=False)230231 result = runner.invoke(cmd)232 assert result.output == repr(expected)233234235@pytest.mark.parametrize(236 ("multiple", "nargs", "default", "exception", "message"),237 [238 # Non-iterables defaults.239 (240 True,241 1,242 "Yo",243 None,244 "Error: Invalid value for '-a': Value must be an iterable.",245 ),246 (247 True,248 1,249 "",250 None,251 "Error: Invalid value for '-a': Value must be an iterable.",252 ),253 (254 True,255 1,256 True,257 None,258 "Error: Invalid value for '-a': Value must be an iterable.",259 ),260 (261 True,262 1,263 False,264 None,265 "Error: Invalid value for '-a': Value must be an iterable.",266 ),267 (268 True,269 1,270 12,271 None,272 "Error: Invalid value for '-a': Value must be an iterable.",273 ),274 (275 True,276 1,277 7.9,278 None,279 "Error: Invalid value for '-a': Value must be an iterable.",280 ),281 #282 (283 False,284 2,285 42,286 None,287 "Error: Invalid value for '-a': Value must be an iterable.",288 ),289 (290 True,291 2,292 ["test string which is not a list in the list"],293 None,294 "Error: Invalid value for '-a': Value must be an iterable.",295 ),296 # Multiple options, each with 2 args, but with wrong length.297 (298 True,299 2,300 (1,),301 None,302 "Error: Invalid value for '-a': Value must be an iterable.",303 ),304 (305 True,306 2,307 (1, 2, 3),308 None,309 "Error: Invalid value for '-a': Value must be an iterable.",310 ),311 (312 True,313 2,314 [tuple()],315 ValueError,316 r"'nargs' must be 0 \(or None\) for type <click\.types\.Tuple object at "317 r"0x[0-9A-Fa-f]+>, but it was 2\.",318 ),319 (320 True,321 2,322 [(1,)],323 ValueError,324 r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "325 r"0x[0-9A-Fa-f]+>, but it was 2\.",326 ),327 (328 True,329 2,330 [(1, 2, 3)],331 ValueError,332 r"'nargs' must be 3 \(or None\) for type <click\.types\.Tuple object at "333 r"0x[0-9A-Fa-f]+>, but it was 2\.",334 ),335 # A mix of valid and invalid defaults.336 (337 True,338 2,339 [[1, 2.2], []],340 None,341 "Error: Invalid value for '-a': 2 values are required, but 0 were given.",342 ),343 # Default values that are iterable but not of the right length.344 (345 False,346 2,347 [1],348 None,349 "Error: Invalid value for '-a': Takes 2 values but 1 was given.",350 ),351 (352 True,353 2,354 [[1]],355 ValueError,356 r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "357 r"0x[0-9A-Fa-f]+>, but it was 2\.",358 ),359 ],360)361def test_bad_defaults_for_multiple(362 runner, multiple, nargs, default, exception, message363):364 if exception:365 assert issubclass(exception, Exception)366 else:367 assert exception is None368369 with (370 pytest.raises(exception, match=re.compile(message))371 if exception372 else nullcontext()373 ):374375 @click.command()376 @click.option("-a", multiple=multiple, nargs=nargs, default=default)377 def cmd(a):378 click.echo(repr(a))379380 result = runner.invoke(cmd)381 assert message in result.stderr382383384@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])385def test_empty_envvar(runner, env_key):386 @click.command()387 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")388 def cli(mypath):389 click.echo(f"mypath: {mypath}")390391 result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO")392 assert result.exception is None393 assert result.output == "mypath: None\n"394395396def test_multiple_envvar(runner):397 @click.command()398 @click.option("--arg", multiple=True)399 def cmd(arg):400 click.echo("|".join(arg))401402 result = runner.invoke(403 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}404 )405 assert not result.exception406 assert result.output == "foo|bar|baz\n"407408 @click.command()409 @click.option("--arg", multiple=True, envvar="X")410 def cmd(arg):411 click.echo("|".join(arg))412413 result = runner.invoke(cmd, [], env={"X": "foo bar baz"})414 assert not result.exception415 assert result.output == "foo|bar|baz\n"416417 @click.command()418 @click.option("--arg", multiple=True, type=click.Path())419 def cmd(arg):420 click.echo("|".join(arg))421422 result = runner.invoke(423 cmd,424 [],425 auto_envvar_prefix="TEST",426 env={"TEST_ARG": f"foo{os.path.pathsep}bar"},427 )428 assert not result.exception429 assert result.output == "foo|bar\n"430431432@pytest.mark.parametrize(433 ("envvar_name", "envvar_value", "expected"),434 (435 # Lower-cased variations of value.436 ("SHOUT", "true", True),437 ("SHOUT", "false", False),438 # Title-cased variations of value.439 ("SHOUT", "True", True),440 ("SHOUT", "False", False),441 # Upper-cased variations of value.442 ("SHOUT", "TRUE", True),443 ("SHOUT", "FALSE", False),444 # Random-cased variations of value.445 ("SHOUT", "TruE", True),446 ("SHOUT", "truE", True),447 ("SHOUT", "FaLsE", False),448 ("SHOUT", "falsE", False),449 # Extra spaces around the value.450 ("SHOUT", "true ", True),451 ("SHOUT", " true ", True),452 ("SHOUT", " true", True),453 ("SHOUT", "false ", False),454 ("SHOUT", " false ", False),455 ("SHOUT", " false", False),456 # Integer variations.457 ("SHOUT", "1", True),458 ("SHOUT", "0", False),459 # Alternative states.460 ("SHOUT", "t", True),461 ("SHOUT", "T", True),462 ("SHOUT", " T ", True),463 ("SHOUT", "f", False),464 ("SHOUT", "y", True),465 ("SHOUT", "n", False),466 ("SHOUT", "yes", True),467 ("SHOUT", "no", False),468 ("SHOUT", "on", True),469 ("SHOUT", "off", False),470 # Blank value variations.471 ("SHOUT", None, False),472 ("SHOUT", "", False),473 ("SHOUT", " ", False),474 ("SHOUT", " ", False),475 # Variable names are not stripped of spaces and so don't match the476 # flag, which then naturraly takes its default value.477 ("SHOUT ", "True", False),478 ("SHOUT ", "False", False),479 (" SHOUT ", "True", False),480 (" SHOUT ", "False", False),481 (" SHOUT", "True", False),482 (" SHOUT", "False", False),483 ("SH OUT", "True", False),484 ("SH OUT", "False", False),485 # Same for random and reverse environment variable names: they are not486 # recognized by the option.487 ("RANDOM", "True", False),488 ("NO_SHOUT", "True", False),489 ("NO_SHOUT", "False", False),490 ("NOSHOUT", "True", False),491 ("NOSHOUT", "False", False),492 ),493)494def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):495 assert isinstance(envvar_name, str)496 assert isinstance(envvar_value, str) or envvar_value is None497498 @click.command()499 @click.option("--shout/--no-shout", envvar="SHOUT")500 def cli(shout):501 click.echo(repr(shout), nl=False)502503 result = runner.invoke(cli, [], env={envvar_name: envvar_value})504 assert result.exit_code == 0505 assert result.output == repr(expected)506507508@pytest.mark.parametrize(509 "value",510 (511 # Extra spaces inside the value.512 "tr ue",513 "fa lse",514 # Numbers.515 "10",516 "01",517 "00",518 "11",519 "0.0",520 "1.1",521 # Random strings.522 "randomstring",523 "None",524 "'None'",525 "A B",526 " 1 2 ",527 "9.3",528 "a;n",529 "x:y",530 "i/o",531 ),532)533def test_boolean_envvar_bad_values(runner, value):534 @click.command()535 @click.option("--shout/--no-shout", envvar="SHOUT")536 def cli(shout):537 click.echo(shout)538539 result = runner.invoke(cli, [], env={"SHOUT": value})540 assert result.exit_code == 2541 assert (542 f"Invalid value for '--shout': {value!r} is not a valid boolean."543 in result.output544 )545546547def test_multiple_default_help(runner):548 @click.command()549 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)550 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)551 def cmd(arg, arg2):552 pass553554 result = runner.invoke(cmd, ["--help"])555 assert not result.exception556 assert "foo, bar" in result.output557 assert "1, 2" in result.output558559560def test_show_default_default_map(runner):561 @click.command()562 @click.option("--arg", default="a", show_default=True)563 def cmd(arg):564 click.echo(arg)565566 result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})567568 assert not result.exception569 assert "[default: b]" in result.output570571572def test_multiple_default_type():573 opt = click.Option(["-a"], multiple=True, default=(1, 2))574 assert opt.nargs == 1575 assert opt.multiple576 assert opt.type is click.INT577 ctx = click.Context(click.Command("test"))578 assert opt.get_default(ctx) == (1, 2)579580581def test_multiple_default_composite_type():582 opt = click.Option(["-a"], multiple=True, default=[(1, "a")])583 assert opt.nargs == 2584 assert opt.multiple585 assert isinstance(opt.type, click.Tuple)586 assert opt.type.types == [click.INT, click.STRING]587 ctx = click.Context(click.Command("test"))588 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)589590591def test_parse_multiple_default_composite_type(runner):592 @click.command()593 @click.option("-a", multiple=True, default=("a", "b"))594 @click.option("-b", multiple=True, default=[(1, "a")])595 def cmd(a, b):596 click.echo(a)597 click.echo(b)598599 # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())600 # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"601 result = runner.invoke(cmd)602 assert result.output == "('a', 'b')\n((1, 'a'),)\n"603604605def test_dynamic_default_help_unset(runner):606 @click.command()607 @click.option(608 "--username",609 prompt=True,610 default=lambda: os.environ.get("USER", ""),611 show_default=True,612 )613 def cmd(username):614 print("Hello,", username)615616 result = runner.invoke(cmd, ["--help"])617 assert result.exit_code == 0618 assert "--username" in result.output619 assert "lambda" not in result.output620 assert "(dynamic)" in result.output621622623def test_dynamic_default_help_text(runner):624 @click.command()625 @click.option(626 "--username",627 prompt=True,628 default=lambda: os.environ.get("USER", ""),629 show_default="current user",630 )631 def cmd(username):632 print("Hello,", username)633634 result = runner.invoke(cmd, ["--help"])635 assert result.exit_code == 0636 assert "--username" in result.output637 assert "lambda" not in result.output638 assert "(current user)" in result.output639640641def test_dynamic_default_help_special_method(runner):642 class Value:643 def __call__(self):644 return 42645646 def __str__(self):647 return "special value"648649 opt = click.Option(["-a"], default=Value(), show_default=True)650 ctx = click.Context(click.Command("cli"))651 assert opt.get_help_extra(ctx) == {"default": "special value"}652 assert "special value" in opt.get_help_record(ctx)[1]653654655@pytest.mark.parametrize(656 ("type", "expect"),657 [658 (click.IntRange(1, 32), "1<=x<=32"),659 (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),660 (click.IntRange(1), "x>=1"),661 (click.IntRange(max=32), "x<=32"),662 ],663)664def test_intrange_default_help_text(type, expect):665 option = click.Option(["--num"], type=type, show_default=True, default=2)666 context = click.Context(click.Command("test"))667 assert option.get_help_extra(context) == {"default": "2", "range": expect}668 result = option.get_help_record(context)[1]669 assert expect in result670671672def test_count_default_type_help():673 """A count option with the default type should not show >=0 in help."""674 option = click.Option(["--count"], count=True, help="some words")675 context = click.Context(click.Command("test"))676 assert option.get_help_extra(context) == {}677 result = option.get_help_record(context)[1]678 assert result == "some words"679680681def test_file_type_help_default():682 """The default for a File type is a filename string. The string683 should be displayed in help, not an open file object.684685 Type casting is only applied to defaults in processing, not when686 getting the default value.687 """688 option = click.Option(689 ["--in"], type=click.File(), default=__file__, show_default=True690 )691 context = click.Context(click.Command("test"))692 assert option.get_help_extra(context) == {"default": __file__}693 result = option.get_help_record(context)[1]694 assert __file__ in result695696697def test_toupper_envvar_prefix(runner):698 @click.command()699 @click.option("--arg")700 def cmd(arg):701 click.echo(arg)702703 result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})704 assert not result.exception705 assert result.output == "foo\n"706707708def test_nargs_envvar(runner):709 @click.command()710 @click.option("--arg", nargs=2)711 def cmd(arg):712 click.echo("|".join(arg))713714 result = runner.invoke(715 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}716 )717 assert not result.exception718 assert result.output == "foo|bar\n"719720 @click.command()721 @click.option("--arg", nargs=2, multiple=True)722 def cmd(arg):723 for item in arg:724 click.echo("|".join(item))725726 result = runner.invoke(727 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}728 )729 assert not result.exception730 assert result.output == "x|1\ny|2\n"731732733def test_show_envvar(runner):734 @click.command()735 @click.option("--arg1", envvar="ARG1", show_envvar=True)736 def cmd(arg):737 pass738739 result = runner.invoke(cmd, ["--help"])740 assert not result.exception741 assert "ARG1" in result.output742743744def test_show_envvar_auto_prefix(runner):745 @click.command()746 @click.option("--arg1", show_envvar=True)747 def cmd(arg):748 pass749750 result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")751 assert not result.exception752 assert "TEST_ARG1" in result.output753754755def test_show_envvar_auto_prefix_dash_in_command(runner):756 @click.group()757 def cli():758 pass759760 @cli.command()761 @click.option("--baz", show_envvar=True)762 def foo_bar(baz):763 pass764765 result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")766 assert not result.exception767 assert "TEST_FOO_BAR_BAZ" in result.output768769770def test_custom_validation(runner):771 def validate_pos_int(ctx, param, value):772 if value < 0:773 raise click.BadParameter("Value needs to be positive")774 return value775776 @click.command()777 @click.option("--foo", callback=validate_pos_int, default=1)778 def cmd(foo):779 click.echo(foo)780781 result = runner.invoke(cmd, ["--foo", "-1"])782 assert "Invalid value for '--foo': Value needs to be positive" in result.output783784 result = runner.invoke(cmd, ["--foo", "42"])785 assert result.output == "42\n"786787788def test_callback_validates_prompt(runner, monkeypatch):789 def validate(ctx, param, value):790 if value < 0:791 raise click.BadParameter("should be positive")792793 return value794795 @click.command()796 @click.option("-a", type=int, callback=validate, prompt=True)797 def cli(a):798 click.echo(a)799800 result = runner.invoke(cli, input="-12\n60\n")801 assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"802803804def test_winstyle_options(runner):805 @click.command()806 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")807 def cmd(debug):808 click.echo(debug)809810 result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])811 assert result.output == "True\n"812 result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])813 assert result.output == "False\n"814 result = runner.invoke(cmd, [], help_option_names=["/?"])815 assert result.output == "False\n"816 result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])817 assert "/debug; /no-debug Enables or disables debug mode." in result.output818 assert "/? Show this message and exit." in result.output819820821def test_legacy_options(runner):822 @click.command()823 @click.option("-whatever")824 def cmd(whatever):825 click.echo(whatever)826827 result = runner.invoke(cmd, ["-whatever", "42"])828 assert result.output == "42\n"829 result = runner.invoke(cmd, ["-whatever=23"])830 assert result.output == "23\n"831832833@pytest.mark.parametrize(834 ("value", "expect_missing", "processed_value"),835 [836 (UNSET, True, None),837 (None, False, None),838 # Default type of the argument is str, so everything is processed as strings.839 ("", False, ""),840 (" ", False, " "),841 ("foo", False, "foo"),842 ("12", False, "12"),843 (12, False, "12"),844 (12.1, False, "12.1"),845 (list(), False, "[]"),846 (tuple(), False, "()"),847 (set(), False, "set()"),848 (frozenset(), False, "frozenset()"),849 (dict(), False, "{}"),850 ],851)852def test_required_option(value, expect_missing, processed_value):853 ctx = click.Context(click.Command(""))854 argument = click.Option(["-a"], required=True)855856 if expect_missing:857 with pytest.raises(click.MissingParameter) as excinfo:858 argument.process_value(ctx, value)859 assert str(excinfo.value) == "Missing parameter: a"860861 else:862 value = argument.process_value(ctx, value)863 assert value == processed_value864865866def test_missing_required_flag(runner):867 cli = click.Command(868 "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]869 )870 result = runner.invoke(cli)871 assert result.exit_code == 2872 assert "Error: Missing option '--on'." in result.output873874875def test_missing_choice(runner):876 @click.command()877 @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)878 def cmd(foo):879 click.echo(foo)880881 result = runner.invoke(cmd)882 assert result.exit_code == 2883 error, separator, choices = result.output.partition("Choose from")884 assert "Error: Missing option '--foo'. " in error885 assert "Choose from" in separator886 assert "foo" in choices887 assert "bar" in choices888889890def test_missing_envvar(runner):891 cli = click.Command(892 "cli", params=[click.Option(["--foo"], envvar="bar", required=True)]893 )894 result = runner.invoke(cli)895 assert result.exit_code == 2896 assert "Error: Missing option '--foo'." in result.output897 cli = click.Command(898 "cli",899 params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)],900 )901 result = runner.invoke(cli)902 assert result.exit_code == 2903 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output904905 cli = click.Command(906 "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]907 )908 result = runner.invoke(cli)909 assert result.exit_code == 2910 assert "Error: Missing option '--foo'." in result.output911912913def test_case_insensitive_choice(runner):914 @click.command()915 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))916 def cmd(foo):917 click.echo(foo)918919 result = runner.invoke(cmd, ["--foo", "apple"])920 assert result.exit_code == 0921 assert result.output == "Apple\n"922923 result = runner.invoke(cmd, ["--foo", "oRANGe"])924 assert result.exit_code == 0925 assert result.output == "Orange\n"926927 result = runner.invoke(cmd, ["--foo", "Apple"])928 assert result.exit_code == 0929 assert result.output == "Apple\n"930931 @click.command()932 @click.option("--foo", type=click.Choice(["Orange", "Apple"]))933 def cmd2(foo):934 click.echo(foo)935936 result = runner.invoke(cmd2, ["--foo", "apple"])937 assert result.exit_code == 2938939 result = runner.invoke(cmd2, ["--foo", "oRANGe"])940 assert result.exit_code == 2941942 result = runner.invoke(cmd2, ["--foo", "Apple"])943 assert result.exit_code == 0944945946def test_case_insensitive_choice_returned_exactly(runner):947 @click.command()948 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))949 def cmd(foo):950 click.echo(foo)951952 result = runner.invoke(cmd, ["--foo", "apple"])953 assert result.exit_code == 0954 assert result.output == "Apple\n"955956957def test_option_help_preserve_paragraphs(runner):958 @click.command()959 @click.option(960 "-C",961 "--config",962 type=click.Path(),963 help="""Configuration file to use.964965 If not given, the environment variable CONFIG_FILE is consulted966 and used if set. If neither are given, a default configuration967 file is loaded.""",968 )969 def cmd(config):970 pass971972 result = runner.invoke(cmd, ["--help"])973 assert result.exit_code == 0974 i = " " * 21975 assert (976 " -C, --config PATH Configuration file to use.\n"977 f"{i}\n"978 f"{i}If not given, the environment variable CONFIG_FILE is\n"979 f"{i}consulted and used if set. If neither are given, a default\n"980 f"{i}configuration file is loaded."981 ) in result.output982983984def test_argument_custom_class(runner):985 class CustomArgument(click.Argument):986 def get_default(self, ctx, call=True):987 """a dumb override of a default value for testing"""988 return "I am a default"989990 @click.command()991 @click.argument("testarg", cls=CustomArgument, default="you wont see me")992 def cmd(testarg):993 click.echo(testarg)994995 result = runner.invoke(cmd)996 assert "I am a default" in result.output997 assert "you wont see me" not in result.output9989991000def test_option_custom_class(runner):1001 class CustomOption(click.Option):1002 def get_help_record(self, ctx):1003 """a dumb override of a help text for testing"""1004 return ("--help", "I am a help text")10051006 @click.command()1007 @click.option("--testoption", cls=CustomOption, help="you wont see me")1008 def cmd(testoption):1009 click.echo(testoption)10101011 result = runner.invoke(cmd, ["--help"])1012 assert "I am a help text" in result.output1013 assert "you wont see me" not in result.output101410151016@pytest.mark.parametrize(1017 ("param_decl", "option_kwargs", "pass_argv"),1018 (1019 # there is a large potential parameter space to explore here1020 # this is just a very small sample of it1021 ("--opt", {}, []),1022 ("--opt", {"multiple": True}, []),1023 ("--opt", {"is_flag": True}, []),1024 ("--opt/--no-opt", {"is_flag": True, "default": None}, []),1025 ("--req", {"is_flag": True, "required": True}, ["--req"]),1026 ),1027)1028def test_option_custom_class_can_override_type_cast_value_and_never_sees_unset(1029 runner, param_decl, option_kwargs, pass_argv1030):1031 """1032 Test that overriding type_cast_value is supported10331034 In particular, the option is never passed an UNSET sentinel value.1035 """10361037 class CustomOption(click.Option):1038 def type_cast_value(self, ctx, value):1039 assert value is not UNSET1040 return value10411042 @click.command()1043 @click.option("myparam", param_decl, **option_kwargs, cls=CustomOption)1044 def cmd(myparam):1045 click.echo("ok")10461047 result = runner.invoke(cmd, pass_argv)1048 assert not result.exception1049 assert result.exit_code == 0105010511052def test_option_custom_class_reusable(runner):1053 """Ensure we can reuse a custom class option. See Issue #926"""10541055 class CustomOption(click.Option):1056 def get_help_record(self, ctx):1057 """a dumb override of a help text for testing"""1058 return ("--help", "I am a help text")10591060 # Assign to a variable to re-use the decorator.1061 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")10621063 @click.command()1064 @testoption1065 def cmd1(testoption):1066 click.echo(testoption)10671068 @click.command()1069 @testoption1070 def cmd2(testoption):1071 click.echo(testoption)10721073 # Both of the commands should have the --help option now.1074 for cmd in (cmd1, cmd2):1075 result = runner.invoke(cmd, ["--help"])1076 assert "I am a help text" in result.output1077 assert "you wont see me" not in result.output107810791080@pytest.mark.parametrize("custom_class", (True, False))1081@pytest.mark.parametrize(1082 ("name_specs", "expected"),1083 (1084 (1085 ("-h", "--help"),1086 " -h, --help Show this message and exit.\n",1087 ),1088 (1089 ("-h",),1090 " -h Show this message and exit.\n"1091 " --help Show this message and exit.\n",1092 ),1093 (1094 ("--help",),1095 " --help Show this message and exit.\n",1096 ),1097 ),1098)1099def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):1100 class CustomHelpOption(click.Option):1101 pass11021103 option_attrs = {}1104 if custom_class:1105 option_attrs["cls"] = CustomHelpOption11061107 @click.command()1108 @click.help_option(*name_specs, **option_attrs)1109 def cmd():1110 pass11111112 for arg in name_specs:1113 result = runner.invoke(cmd, [arg])1114 assert not result.exception1115 assert result.exit_code == 01116 assert expected in result.output111711181119def test_bool_flag_with_type(runner):1120 @click.command()1121 @click.option("--shout/--no-shout", default=False, type=bool)1122 def cmd(shout):1123 pass11241125 result = runner.invoke(cmd)1126 assert not result.exception112711281129def test_aliases_for_flags(runner):1130 @click.command()1131 @click.option("--warnings/--no-warnings", " /-W", default=True)1132 def cli(warnings):1133 click.echo(warnings)11341135 result = runner.invoke(cli, ["--warnings"])1136 assert result.output == "True\n"1137 result = runner.invoke(cli, ["--no-warnings"])1138 assert result.output == "False\n"1139 result = runner.invoke(cli, ["-W"])1140 assert result.output == "False\n"11411142 @click.command()1143 @click.option("--warnings/--no-warnings", "-w", default=True)1144 def cli_alt(warnings):1145 click.echo(warnings)11461147 result = runner.invoke(cli_alt, ["--warnings"])1148 assert result.output == "True\n"1149 result = runner.invoke(cli_alt, ["--no-warnings"])1150 assert result.output == "False\n"1151 result = runner.invoke(cli_alt, ["-w"])1152 assert result.output == "True\n"115311541155@pytest.mark.parametrize(1156 "option_args,expected",1157 [1158 (["--aggressive", "--all", "-a"], "aggressive"),1159 (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),1160 (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),1161 (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),1162 (["-a", "-b", "-c"], "a"),1163 (["-c", "-b", "-a"], "c"),1164 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),1165 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),1166 (["--from", "-f", "_from"], "_from"),1167 (["--return", "-r", "_ret"], "_ret"),1168 ],1169)1170def test_option_names(runner, option_args, expected):1171 @click.command()1172 @click.option(*option_args, is_flag=True)1173 def cmd(**kwargs):1174 click.echo(str(kwargs[expected]))11751176 assert cmd.params[0].name == expected11771178 for form in option_args:1179 if form.startswith("-"):1180 result = runner.invoke(cmd, [form])1181 assert result.output == "True\n"118211831184def test_flag_duplicate_names(runner):1185 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):1186 click.Option(["--foo/--foo"], default=False)118711881189@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])1190def test_show_default_boolean_flag_name(runner, default, expect):1191 """When a boolean flag has distinct True/False opts, it should show1192 the default opt name instead of the default value. It should only1193 show one name even if multiple are declared.1194 """1195 opt = click.Option(1196 ("--cache/--no-cache", "--c/--nc"),1197 default=default,1198 show_default=True,1199 help="Enable/Disable the cache.",1200 )1201 ctx = click.Context(click.Command("test"))1202 assert opt.get_help_extra(ctx) == {"default": expect}1203 message = opt.get_help_record(ctx)[1]1204 assert f"[default: {expect}]" in message120512061207def test_show_true_default_boolean_flag_value(runner):1208 """When a boolean flag only has one opt and its default is True,1209 it will show the default value, not the opt name.1210 """1211 opt = click.Option(1212 ("--cache",),1213 is_flag=True,1214 show_default=True,1215 default=True,1216 help="Enable the cache.",1217 )1218 ctx = click.Context(click.Command("test"))1219 assert opt.get_help_extra(ctx) == {"default": "True"}1220 message = opt.get_help_record(ctx)[1]1221 assert "[default: True]" in message122212231224@pytest.mark.parametrize("default", [False, None])1225def test_hide_false_default_boolean_flag_value(runner, default):1226 """When a boolean flag only has one opt and its default is False or1227 None, it will not show the default1228 """1229 opt = click.Option(1230 ("--cache",),1231 is_flag=True,1232 show_default=True,1233 default=default,1234 help="Enable the cache.",1235 )1236 ctx = click.Context(click.Command("test"))1237 assert opt.get_help_extra(ctx) == {}1238 message = opt.get_help_record(ctx)[1]1239 assert "[default: " not in message124012411242def test_show_default_string(runner):1243 """When show_default is a string show that value as default."""1244 opt = click.Option(["--limit"], show_default="unlimited")1245 ctx = click.Context(click.Command("cli"))1246 assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}1247 message = opt.get_help_record(ctx)[1]1248 assert "[default: (unlimited)]" in message124912501251def test_show_default_with_empty_string(runner):1252 """When show_default is True and default is set to an empty string."""1253 opt = click.Option(["--limit"], default="", show_default=True)1254 ctx = click.Context(click.Command("cli"))1255 message = opt.get_help_record(ctx)[1]1256 assert '[default: ""]' in message125712581259def test_do_not_show_no_default(runner):1260 """When show_default is True and no default is set do not show None."""1261 opt = click.Option(["--limit"], show_default=True)1262 ctx = click.Context(click.Command("cli"))1263 assert opt.get_help_extra(ctx) == {}1264 message = opt.get_help_record(ctx)[1]1265 assert "[default: None]" not in message126612671268def test_do_not_show_default_empty_multiple():1269 """When show_default is True and multiple=True is set, it should not1270 print empty default value in --help output.1271 """1272 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)1273 ctx = click.Context(click.Command("cli"))1274 assert opt.get_help_extra(ctx) == {}1275 message = opt.get_help_record(ctx)[1]1276 assert message == "values"127712781279@pytest.mark.parametrize(1280 ("ctx_value", "opt_value", "extra_value", "expect"),1281 [1282 (None, None, {}, False),1283 (None, False, {}, False),1284 (None, True, {"default": "1"}, True),1285 (False, None, {}, False),1286 (False, False, {}, False),1287 (False, True, {"default": "1"}, True),1288 (True, None, {"default": "1"}, True),1289 (True, False, {}, False),1290 (True, True, {"default": "1"}, True),1291 (False, "one", {"default": "(one)"}, True),1292 ],1293)1294def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):1295 ctx = click.Context(click.Command("test"), show_default=ctx_value)1296 opt = click.Option("-a", default=1, help="value", show_default=opt_value)1297 assert opt.get_help_extra(ctx) == extra_value1298 help = opt.get_help_record(ctx)[1]1299 assert ("default:" in help) is expect130013011302@pytest.mark.parametrize(1303 ("args", "expect"),1304 [1305 (None, (None, None, ())),1306 (["--opt"], ("flag", None, ())),1307 (["--opt", "-a", 42], ("flag", "42", ())),1308 (["--opt", "test", "-a", 42], ("test", "42", ())),1309 (["--opt=test", "-a", 42], ("test", "42", ())),1310 (["-o"], ("flag", None, ())),1311 (["-o", "-a", 42], ("flag", "42", ())),1312 (["-o", "test", "-a", 42], ("test", "42", ())),1313 (["-otest", "-a", 42], ("test", "42", ())),1314 (["a", "b", "c"], (None, None, ("a", "b", "c"))),1315 (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),1316 (["--opt", "test"], ("test", None, ())),1317 (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1318 (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1319 ],1320)1321def test_option_with_optional_value(runner, args, expect):1322 @click.command()1323 @click.option("-o", "--opt", is_flag=False, flag_value="flag")1324 @click.option("-a")1325 @click.argument("b", nargs=-1)1326 def cli(opt, a, b):1327 return opt, a, b13281329 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)1330 assert result.return_value == expect133113321333def test_multiple_option_with_optional_value(runner):1334 cli = click.Command(1335 "cli",1336 params=[1337 click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),1338 click.Option(["-a"]),1339 click.Argument(["b"], nargs=-1),1340 ],1341 callback=lambda **kwargs: kwargs,1342 )1343 result = runner.invoke(1344 cli,1345 ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],1346 standalone_mode=False,1347 catch_exceptions=False,1348 )1349 assert result.return_value == {1350 "f": ("flag", "other", "flag"),1351 "a": "1",1352 "b": ("a", "b"),1353 }135413551356def test_type_from_flag_value():1357 param = click.Option(["-a", "x"], default=True, flag_value=4)1358 assert param.type is click.INT1359 param = click.Option(["-b", "x"], flag_value=8)1360 assert param.type is click.INT136113621363@pytest.mark.parametrize(1364 ("opt_params", "args", "expected"),1365 [1366 # The type passed to the option is responsible to converting the value, whether1367 # we pass the option flag or not.1368 ({"type": bool}, [], False),1369 ({"type": bool}, ["--foo"], True),1370 ({"type": click.BOOL}, [], False),1371 ({"type": click.BOOL}, ["--foo"], True),1372 ({"type": str}, [], None),1373 ({"type": str}, ["--foo"], "True"),1374 # Default value is given as-is to the --foo option when it is not passed,1375 # whatever the type. Now if --foo is passed, the value is always True, whatever1376 # the type. In both case the type of the option is responsible for the1377 # conversion of the value.1378 ({"type": bool, "default": True}, [], True),1379 ({"type": bool, "default": True}, ["--foo"], True),1380 ({"type": bool, "default": False}, [], False),1381 ({"type": bool, "default": False}, ["--foo"], True),1382 # ({"type": bool, "default": "foo"}, [], "foo"),1383 ({"type": bool, "default": "foo"}, ["--foo"], True),1384 ({"type": bool, "default": None}, [], None),1385 ({"type": bool, "default": None}, ["--foo"], True),1386 ({"type": click.BOOL, "default": True}, [], True),1387 ({"type": click.BOOL, "default": True}, ["--foo"], True),1388 ({"type": click.BOOL, "default": False}, [], False),1389 ({"type": click.BOOL, "default": False}, ["--foo"], True),1390 # ({"type": click.BOOL, "default": "foo"}, [], "foo"),1391 ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),1392 ({"type": click.BOOL, "default": None}, [], None),1393 ({"type": click.BOOL, "default": None}, ["--foo"], True),1394 ({"type": str, "default": True}, [], "True"),1395 ({"type": str, "default": True}, ["--foo"], "True"),1396 ({"type": str, "default": False}, [], "False"),1397 ({"type": str, "default": False}, ["--foo"], "True"),1398 ({"type": str, "default": "foo"}, [], "foo"),1399 ({"type": str, "default": "foo"}, ["--foo"], "True"),1400 ({"type": str, "default": None}, [], None),1401 ({"type": str, "default": None}, ["--foo"], "True"),1402 # Flag value is given as-is to the --foo option when it is passed, then1403 # converted by the option type.1404 ({"type": bool, "flag_value": True}, [], False),1405 ({"type": bool, "flag_value": True}, ["--foo"], True),1406 ({"type": bool, "flag_value": False}, [], False),1407 ({"type": bool, "flag_value": False}, ["--foo"], False),1408 ({"type": bool, "flag_value": None}, [], False),1409 ({"type": bool, "flag_value": None}, ["--foo"], None),1410 ({"type": click.BOOL, "flag_value": True}, [], False),1411 ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),1412 ({"type": click.BOOL, "flag_value": False}, [], False),1413 ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),1414 ({"type": click.BOOL, "flag_value": None}, [], False),1415 ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),1416 ({"type": str, "flag_value": True}, [], None),1417 ({"type": str, "flag_value": True}, ["--foo"], "True"),1418 ({"type": str, "flag_value": False}, [], None),1419 ({"type": str, "flag_value": False}, ["--foo"], "False"),1420 ({"type": str, "flag_value": "foo"}, [], None),1421 ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1422 ({"type": str, "flag_value": None}, [], None),1423 ({"type": str, "flag_value": None}, ["--foo"], None),1424 # Not passing --foo returns the default value as-is, in its Python type, then1425 # converted by the option type.1426 ({"type": bool, "default": True, "flag_value": True}, [], True),1427 ({"type": bool, "default": True, "flag_value": False}, [], False),1428 ({"type": bool, "default": False, "flag_value": True}, [], False),1429 ({"type": bool, "default": False, "flag_value": False}, [], False),1430 ({"type": bool, "default": None, "flag_value": True}, [], None),1431 ({"type": bool, "default": None, "flag_value": False}, [], None),1432 ({"type": str, "default": True, "flag_value": True}, [], "True"),1433 ({"type": str, "default": True, "flag_value": False}, [], "False"),1434 ({"type": str, "default": False, "flag_value": True}, [], "False"),1435 ({"type": str, "default": False, "flag_value": False}, [], "False"),1436 ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1437 ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),1438 ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),1439 ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),1440 ({"type": str, "default": None, "flag_value": True}, [], None),1441 ({"type": str, "default": None, "flag_value": False}, [], None),1442 # Passing --foo returns the flag_value that was explicitly set by the user,1443 # with its Python type, but still converted by the option type.1444 ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),1445 ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),1446 ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),1447 ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),1448 ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),1449 ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),1450 ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),1451 ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),1452 ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),1453 ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),1454 ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),1455 ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),1456 ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),1457 ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),1458 ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),1459 ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),1460 ],1461)1462def test_flag_value_and_default(runner, opt_params, args, expected):1463 @click.command()1464 @click.option("--foo", is_flag=True, **opt_params)1465 def cmd(foo):1466 click.echo(repr(foo), nl=False)14671468 result = runner.invoke(cmd, args)1469 assert result.output == repr(expected)147014711472@pytest.mark.parametrize(1473 ("args", "opts"),1474 [1475 ([], {"type": bool, "default": "foo"}),1476 ([], {"type": click.BOOL, "default": "foo"}),1477 (["--foo"], {"type": bool, "flag_value": "foo"}),1478 (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),1479 ],1480)1481def test_invalid_flag_definition(runner, args, opts):1482 @click.command()1483 @click.option("--foo", is_flag=True, **opts)1484 def cmd(foo):1485 click.echo(foo)14861487 result = runner.invoke(cmd, args)1488 assert (1489 "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1490 in result.output1491 )149214931494@pytest.mark.parametrize(1495 ("default", "args", "expected"),1496 # These test cases are similar to the ones in1497 # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync.1498 (1499 # Each option is returning its own flag_value, whatever the default is.1500 (True, ["--js"], "js"),1501 (True, ["--xml"], "xml"),1502 (False, ["--js"], "js"),1503 (False, ["--xml"], "xml"),1504 (None, ["--js"], "js"),1505 (None, ["--xml"], "xml"),1506 (UNSET, ["--js"], "js"),1507 (UNSET, ["--xml"], "xml"),1508 # Check that the last option wins when both are specified.1509 (True, ["--js", "--xml"], "xml"),1510 (True, ["--xml", "--js"], "js"),1511 # Check that the default is returned as-is when no option is specified.1512 ("js", [], "js"),1513 ("xml", [], "xml"),1514 ("jS", [], "jS"),1515 ("xMl", [], "xMl"),1516 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),1517 (None, [], None),1518 # Special case: UNSET is not provided as-is to the callback, but normalized to1519 # None.1520 (UNSET, [], None),1521 # Special case: if default=True and flag_value is set, the value returned is the1522 # flag_value, not the True Python value itself.1523 (True, [], "js"),1524 # Non-string defaults are process as strings by the default Parameter's type.1525 (False, [], "False"),1526 (42, [], "42"),1527 (12.3, [], "12.3"),1528 ),1529)1530def test_default_dual_option_callback(runner, default, args, expected):1531 """Check how default is processed by the callback when options compete for the same1532 variable name.15331534 Reproduction of the issue reported in1535 https://github.com/pallets/click/pull/3030#discussion_r22715718191536 """15371538 def _my_func(ctx, param, value):1539 # Print the value received by the callback as-is, so we can check for it.1540 return f"Callback value: {value!r}"15411542 @click.command()1543 @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)1544 @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)1545 def main(fmt):1546 click.secho(fmt, nl=False)15471548 result = runner.invoke(main, args)1549 assert result.output == f"Callback value: {expected!r}"1550 assert result.exit_code == 0155115521553@pytest.mark.parametrize(1554 ("flag_value", "envvar_value", "expected"),1555 [1556 # The envvar match exactly the flag value and is case-sensitive.1557 ("bar", "bar", "bar"),1558 ("BAR", "BAR", "BAR"),1559 (" bar ", " bar ", " bar "),1560 ("42", "42", "42"),1561 ("None", "None", "None"),1562 ("True", "True", "True"),1563 ("False", "False", "False"),1564 ("true", "true", "true"),1565 ("false", "false", "false"),1566 ("A B", "A B", "A B"),1567 (" 1 2 ", " 1 2 ", " 1 2 "),1568 ("9.3", "9.3", "9.3"),1569 ("a;n", "a;n", "a;n"),1570 ("x:y", "x:y", "x:y"),1571 ("i/o", "i/o", "i/o"),1572 # Empty or absent envvar is consider unset, so the flag default value is1573 # returned, which is None in this case.1574 ("bar", "", None),1575 ("bar", None, None),1576 ("BAR", "", None),1577 ("BAR", None, None),1578 (" bar ", "", None),1579 (" bar ", None, None),1580 (42, "", None),1581 (42, None, None),1582 ("42", "", None),1583 ("42", None, None),1584 (None, "", None),1585 (None, None, None),1586 ("None", "", None),1587 ("None", None, None),1588 (True, "", None),1589 (True, None, None),1590 ("True", "", None),1591 ("True", None, None),1592 ("true", "", None),1593 ("true", None, None),1594 (False, "", None),1595 (False, None, None),1596 ("False", "", None),1597 ("False", None, None),1598 ("false", "", None),1599 ("false", None, None),1600 # Activate the flag with a value recognized as True by the envvar, which1601 # returns the flag_value.1602 ("bar", "True", "bar"),1603 ("bar", "true", "bar"),1604 ("bar", "trUe", "bar"),1605 ("bar", " TRUE ", "bar"),1606 ("bar", "1", "bar"),1607 ("bar", "yes", "bar"),1608 ("bar", "on", "bar"),1609 ("bar", "t", "bar"),1610 ("bar", "y", "bar"),1611 # Deactivating the flag with a value recognized as False by the envvar, which1612 # explicitly return the 'False' as the option is explicitly declared as a1613 # string.1614 ("bar", "False", "False"),1615 ("bar", "false", "False"),1616 ("bar", "faLse", "False"),1617 ("bar", " FALSE ", "False"),1618 ("bar", "0", "False"),1619 ("bar", "no", "False"),1620 ("bar", "off", "False"),1621 ("bar", "f", "False"),1622 ("bar", "n", "False"),1623 # Any other value than the flag_value, or a recogned True or False value, fails1624 # to explicitly activate or deactivate the flag. So the flag default value is1625 # returned, which is None in this case.1626 ("bar", " bar ", None),1627 ("bar", "BAR", None),1628 ("bar", "random", None),1629 ("bar", "bar random", None),1630 ("bar", "random bar", None),1631 ("BAR", "bar", None),1632 (" bar ", "bar", None),1633 (" bar ", "BAR", None),1634 (42, "42", None),1635 (42, "foo", None),1636 (None, "foo", None),1637 ("None", "foo", None),1638 ],1639)1640def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):1641 """Ensure that flag_value is recognized by the envvar."""16421643 @click.command()1644 @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER")1645 def cmd(upper):1646 click.echo(repr(upper), nl=False)16471648 result = runner.invoke(cmd, env={"UPPER": envvar_value})1649 assert result.exit_code == 01650 assert result.output == repr(expected)165116521653@pytest.mark.parametrize(1654 ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"),1655 [1656 # Not boolean flags.1657 ("-a", {"type": int}, False, False),1658 ("-a", {"type": bool}, False, False),1659 ("-a", {"default": True}, False, False),1660 ("-a", {"default": False}, False, False),1661 ("-a", {"flag_value": 1}, True, False),1662 # Boolean flags.1663 ("-a", {"is_flag": True}, True, True),1664 ("-a/-A", {}, True, True),1665 ("-a", {"flag_value": True}, True, True),1666 # Non-flag with flag_value.1667 ("-a", {"is_flag": False, "flag_value": 1}, False, False),1668 ],1669)1670def test_flag_auto_detection(1671 opt_decls, opt_params, expect_is_flag, expect_is_bool_flag1672):1673 option = Option([opt_decls], **opt_params)1674 assert option.is_flag is expect_is_flag1675 assert option.is_bool_flag is expect_is_bool_flag167616771678@pytest.mark.parametrize(1679 ("kwargs", "message"),1680 [1681 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),1682 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),1683 ],1684)1685def test_invalid_flag_combinations(runner, kwargs, message):1686 with pytest.raises(TypeError) as e:1687 click.Option(["-a"], **kwargs)16881689 assert message in str(e.value)169016911692def test_non_flag_with_non_negatable_default(runner):1693 class NonNegatable:1694 def __bool__(self):1695 raise ValueError("Cannot negate this object")16961697 @click.command()1698 @click.option("--foo", default=NonNegatable())1699 def cmd(foo):1700 pass17011702 result = runner.invoke(cmd)1703 assert result.exit_code == 0170417051706class HashType(enum.Enum):1707 MD5 = "MD5"1708 SHA1 = "SHA1"1709 SHA256 = "SHA-256"171017111712class Number(enum.IntEnum):1713 ONE = enum.auto()1714 TWO = enum.auto()171517161717class Letter(enum.StrEnum):1718 NAME_1 = "Value-1"1719 NAME_2 = "Value_2"1720 NAME_3 = "42_value"172117221723class Color(enum.Flag):1724 RED = enum.auto()1725 GREEN = enum.auto()1726 BLUE = enum.auto()172717281729class ColorInt(enum.IntFlag):1730 RED = enum.auto()1731 GREEN = enum.auto()1732 BLUE = enum.auto()173317341735@pytest.mark.parametrize(1736 ("choices", "metavar"),1737 [1738 (["foo", "bar"], "[TEXT]"),1739 ([1, 2], "[INTEGER]"),1740 ([1.0, 2.0], "[FLOAT]"),1741 ([True, False], "[BOOLEAN]"),1742 (["foo", 1], "[TEXT|INTEGER]"),1743 (HashType, "[HASHTYPE]"),1744 (Number, "[NUMBER]"),1745 (Letter, "[LETTER]"),1746 (Color, "[COLOR]"),1747 (ColorInt, "[COLORINT]"),1748 ],1749)1750def test_choice_usage_rendering(runner, choices, metavar):1751 """BY default ``--help`` prints choice's values in the usage message.17521753 But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of1754 values.17551756 Also check that usage error message always suggests the actual values.1757 """17581759 @click.command()1760 @click.option("-g", type=click.Choice(choices))1761 def cli_with_choices(g):1762 pass17631764 @click.command()1765 @click.option("-g", type=click.Choice(choices), show_choices=False)1766 def cli_without_choices(g):1767 pass17681769 display_values = tuple(1770 i.name if isinstance(i, enum.Enum) else str(i) for i in choices1771 )17721773 # Check that the choices values are rendered as-is in the usage message.1774 result = runner.invoke(cli_with_choices, ["--help"])1775 assert f"[{'|'.join(display_values)}]" in result.stdout1776 assert not result.stderr1777 assert result.exit_code == 017781779 # Check that the metavar is rendered instead of the choices values themselves.1780 result = runner.invoke(cli_without_choices, ["--help"])1781 assert metavar in result.stdout1782 assert not result.stderr1783 assert result.exit_code == 017841785 # Check the usage error message suggests the actual accepted values.1786 for cli in (cli_with_choices, cli_without_choices):1787 result = runner.invoke(cli, ["-g", "random"])1788 assert (1789 "\n\nError: Invalid value for '-g': 'random' is not one of "1790 f"{', '.join(map(repr, display_values))}.\n" in result.stderr1791 )1792 assert not result.stdout1793 assert result.exit_code == 2179417951796@pytest.mark.parametrize(1797 ("choices", "default", "default_string"),1798 [1799 (["foo", "bar"], "bar", "bar"),1800 # The default value is not enforced to be in the choices.1801 (["foo", "bar"], "random", "random"),1802 # None cannot be a default value as-is: it left the default value as unset.1803 (["foo", "bar"], None, None),1804 ([0, 1], 0, "0"),1805 # Values are not coerced to the type of the choice, even if equivalent.1806 ([0, 1], 0.0, "0.0"),1807 ([1, 2], 2, "2"),1808 ([1.0, 2.0], 2, "2"),1809 ([1.0, 2.0], 2.0, "2.0"),1810 ([True, False], True, "True"),1811 ([True, False], False, "False"),1812 (["foo", 1], "foo", "foo"),1813 (["foo", 1], 1, "1"),1814 # Enum choices are rendered as their names, not values.1815 # See: https://github.com/pallets/click/issues/29111816 (HashType, HashType.SHA1, "SHA1"),1817 # Enum choices allow defaults strings that are their names.1818 (HashType, HashType.SHA256, "SHA256"),1819 (HashType, "SHA256", "SHA256"),1820 (Number, Number.TWO, "TWO"),1821 (Number, "TWO", "TWO"),1822 (Letter, Letter.NAME_1, "NAME_1"),1823 (Letter, Letter.NAME_2, "NAME_2"),1824 (Letter, Letter.NAME_3, "NAME_3"),1825 (Letter, "NAME_1", "NAME_1"),1826 (Letter, "NAME_2", "NAME_2"),1827 (Letter, "NAME_3", "NAME_3"),1828 (Color, Color.GREEN, "GREEN"),1829 (Color, "GREEN", "GREEN"),1830 (ColorInt, ColorInt.GREEN, "GREEN"),1831 (ColorInt, "GREEN", "GREEN"),1832 ],1833)1834def test_choice_default_rendering(runner, choices, default, default_string):1835 @click.command()1836 @click.option("-g", type=click.Choice(choices), default=default, show_default=True)1837 def cli_with_choices(g):1838 pass18391840 # Check that the default value is kept normalized to the type of the choice.1841 assert cli_with_choices.params[0].default == default18421843 result = runner.invoke(cli_with_choices, ["--help"])1844 extra_usage = f"[default: {default_string}]"1845 if default_string is None:1846 assert extra_usage not in result.output1847 else:1848 assert extra_usage in result.output184918501851@pytest.mark.parametrize(1852 "opts_one,opts_two",1853 [1854 # No duplicate shortnames1855 (1856 ("-a", "--aardvark"),1857 ("-a", "--avocado"),1858 ),1859 # No duplicate long names1860 (1861 ("-a", "--aardvark"),1862 ("-b", "--aardvark"),1863 ),1864 ],1865)1866def test_duplicate_names_warning(runner, opts_one, opts_two):1867 @click.command()1868 @click.option(*opts_one)1869 @click.option(*opts_two)1870 def cli(one, two):1871 pass18721873 with pytest.warns(UserWarning):1874 runner.invoke(cli, [])187518761877OBJECT_SENTINEL = object()1878"""An object-based sentinel value."""187918801881class EnumSentinel(enum.Enum):1882 FALSY_SENTINEL = object()18831884 def __bool__(self) -> Literal[False]:1885 """Force the sentinel to be falsy to make sure it is not caught by Click1886 internal implementation.18871888 Falsy sentinels have been discussed in:1889 https://github.com/pallets/click/pull/3030#pullrequestreview-31066047951890 https://github.com/pallets/click/pull/3030#pullrequestreview-31084715521891 """1892 return False189318941895# Any kind of sentinel value is recognized by Click as a valid flag value.1896@pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))1897@pytest.mark.parametrize(1898 ("args", "expected"),1899 (1900 # Option default to None.1901 ([], None),1902 # Config has no default value, and no flag value, so it requires an argument.1903 (1904 ["--config"],1905 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1906 ),1907 (1908 ["--no-config", "--config"],1909 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1910 ),1911 # Passing --no-config defaults to the sentinel value because of the flag_value,1912 # and then the custom type receives that sentinel and returns a message.1913 (["--no-config"], "No configuration file provided."),1914 # Passing --config with an argument returns the file path.1915 (["--config", "foo.conf"], "foo.conf"),1916 # An argument is not allowed for --no-config, so it raises an error.1917 (1918 ["--no-config", "foo.conf"],1919 re.compile(1920 r"Usage: main \[OPTIONS\]\n"1921 r"Try 'main --help' for help.\n"1922 r"\n"1923 r"Error: Got unexpected extra argument (.+)\n"1924 ),1925 ),1926 # Passing --config with an argument that does not exist raises an error.1927 (1928 ["--config", "random-file.conf"],1929 re.compile(1930 r"Usage: main \[OPTIONS\]\n"1931 r"Try 'main --help' for help.\n"1932 r"\n"1933 r"Error: Invalid value for '-c' / '--config': "1934 r"File 'random-file.conf' does not exist.\n"1935 ),1936 ),1937 (1938 ["--config", "--no-config"],1939 re.compile(1940 r"Usage: main \[OPTIONS\]\n"1941 r"Try 'main --help' for help.\n"1942 r"\n"1943 r"Error: Invalid value for '-c' / '--config': "1944 r"File '--no-config' does not exist.\n"1945 ),1946 ),1947 (1948 ["--config", "--no-config", "foo.conf"],1949 re.compile(1950 r"Usage: main \[OPTIONS\]\n"1951 r"Try 'main --help' for help.\n"1952 r"\n"1953 r"Error: Invalid value for '-c' / '--config': "1954 r"File '--no-config' does not exist.\n"1955 ),1956 ),1957 # --config is passed last and overrides the --no-config option.1958 (["--no-config", "--config", "foo.conf"], "foo.conf"),1959 ),1960)1961def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected):1962 """Check that an object-based sentinel, used as a flag value, is returned as-is1963 to a custom type that is shared by two options, competing for the same variable1964 name.19651966 A reproduction of1967 https://github.com/pallets/click/issues/3024#issuecomment-31465113561968 """19691970 class ConfigParamType(click.ParamType):1971 """A custom type that accepts a file path or a sentinel value."""19721973 def convert(self, value, param, ctx):1974 if value is sentinel:1975 return "No configuration file provided."1976 else:1977 return click.Path(exists=True, dir_okay=False).convert(1978 value, param, ctx1979 )19801981 @click.command()1982 @click.option("-c", "--config", type=ConfigParamType())1983 @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType())1984 def main(config):1985 click.echo(repr(config), nl=False)19861987 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:1988 if "foo.conf" in args:1989 named_tempfile.write("Blah blah")1990 named_tempfile.flush()1991 args = [named_tempfile.name if a == "foo.conf" else a for a in args]19921993 result = runner.invoke(main, args)19941995 if isinstance(expected, re.Pattern):1996 assert re.match(expected, result.output)1997 else:1998 assert result.output == repr(1999 named_tempfile.name if expected == "foo.conf" else expected2000 )The first 2,000 of 2,321 lines.