Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

1,063 lines · 32.5 KiB · Python

Last changed by

Introduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31

History of this file

Take it

The walk stopped after 200 commits: lines older than 21e3587 point at it.

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 1–6why, one step back
1import os
2import re34import pytest56import click

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd

line 7why, one step back
7from click import Option

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 8–35why, one step back
8
910def test_prefixes(runner):11 @click.command()12 @click.option("++foo", is_flag=True, help="das foo")13 @click.option("--bar", is_flag=True, help="das bar")14 def cli(foo, bar):15 click.echo(f"foo={foo} bar={bar}")1617 result = runner.invoke(cli, ["++foo", "--bar"])18 assert not result.exception19 assert result.output == "foo=True bar=True\n"2021 result = runner.invoke(cli, ["--help"])22 assert re.search(r"\+\+foo\s+das foo", result.output) is not None23 assert re.search(r"--bar\s+das bar", result.output) is not None242526def test_invalid_option(runner):27 with pytest.raises(TypeError, match="name was passed") as exc_info:28 click.Option(["foo"])2930 message = str(exc_info.value)31 assert "name was passed (foo)" in message32 assert "declare an argument" in message33 assert "'--foo'" in message3435

Introduce Parameter.deprecated + Command.deprecated message customization (#2271)Peacockbefore adoption5961d31

lines 36–81why, one step back
36@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])
37def test_deprecated_usage(runner, deprecated):38 @click.command()39 @click.option("--foo", default="bar", deprecated=deprecated)40 def cmd(foo):41 click.echo(foo)4243 result = runner.invoke(cmd, ["--help"])44 assert "(DEPRECATED" in result.output4546 if isinstance(deprecated, str):47 assert deprecated in result.output484950@pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])51def test_deprecated_warning(runner, deprecated):52 @click.command()53 @click.option(54 "--my-option", required=False, deprecated=deprecated, default="default option"55 )56 def cli(my_option: str):57 click.echo(f"{my_option}")5859 # defaults should not give a deprecated warning60 result = runner.invoke(cli, [])61 assert result.exit_code == 0, result.output62 assert "is deprecated" not in result.output6364 result = runner.invoke(cli, ["--my-option", "hello"])65 assert result.exit_code == 0, result.output66 assert "option 'my_option' is deprecated" in result.output6768 if isinstance(deprecated, str):69 assert deprecated in result.output707172def test_deprecated_required(runner):73 with pytest.raises(ValueError, match="is deprecated and still required"):74 click.Option(["--a"], required=True, deprecated=True)757677def test_deprecated_prompt(runner):78 with pytest.raises(ValueError, match="`deprecated` options cannot use `prompt`"):79 click.Option(["--a"], prompt=True, deprecated=True)8081

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 82–201why, one step back
82def test_invalid_nargs(runner):
83 with pytest.raises(TypeError, match="nargs=-1"):8485 @click.command()86 @click.option("--foo", nargs=-1)87 def cli(foo):88 pass899091def test_nargs_tup_composite_mult(runner):92 @click.command()93 @click.option("--item", type=(str, int), multiple=True)94 def copy(item):95 for name, id in item:96 click.echo(f"name={name} id={id:d}")9798 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])99 assert not result.exception100 assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]101102103def test_counting(runner):104 @click.command()105 @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))106 def cli(v):107 click.echo(f"verbosity={v:d}")108109 result = runner.invoke(cli, ["-vvv"])110 assert not result.exception111 assert result.output == "verbosity=3\n"112113 result = runner.invoke(cli, ["-vvvv"])114 assert result.exception115 assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output116117 result = runner.invoke(cli, [])118 assert not result.exception119 assert result.output == "verbosity=0\n"120121 result = runner.invoke(cli, ["--help"])122 assert re.search(r"-v\s+Verbosity", result.output) is not None123124125@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])126def test_unknown_options(runner, unknown_flag):127 @click.command()128 def cli():129 pass130131 result = runner.invoke(cli, [unknown_flag])132 assert result.exception133 assert f"No such option: {unknown_flag}" in result.output134135136@pytest.mark.parametrize(137 ("value", "expect"),138 [139 ("--cat", "Did you mean --count?"),140 ("--bounds", "(Possible options: --bound, --count)"),141 ("--bount", "(Possible options: --bound, --count)"),142 ],143)144def test_suggest_possible_options(runner, value, expect):145 cli = click.Command(146 "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]147 )148 result = runner.invoke(cli, [value])149 assert expect in result.output150151152def test_multiple_required(runner):153 @click.command()154 @click.option("-m", "--message", multiple=True, required=True)155 def cli(message):156 click.echo("\n".join(message))157158 result = runner.invoke(cli, ["-m", "foo", "-mbar"])159 assert not result.exception160 assert result.output == "foo\nbar\n"161162 result = runner.invoke(cli, [])163 assert result.exception164 assert "Error: Missing option '-m' / '--message'." in result.output165166167@pytest.mark.parametrize(168 ("multiple", "nargs", "default"),169 [170 (True, 1, []),171 (True, 1, [1]),172 # (False, -1, []),173 # (False, -1, [1]),174 (False, 2, [1, 2]),175 # (True, -1, [[]]),176 # (True, -1, []),177 # (True, -1, [[1]]),178 (True, 2, []),179 (True, 2, [[1, 2]]),180 ],181)182def test_init_good_default_list(runner, multiple, nargs, default):183 click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)184185186@pytest.mark.parametrize(187 ("multiple", "nargs", "default"),188 [189 (True, 1, 1),190 # (False, -1, 1),191 (False, 2, [1]),192 (True, 2, [[1]]),193 ],194)195def test_init_bad_default_list(runner, multiple, nargs, default):196 type = (str, str) if nargs == 2 else None197198 with pytest.raises(ValueError, match="default"):199 click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)200201

Merge pull request #2223 from pallets/env-varDavid Lordbefore adoption20c88f0

lines 202–203why, one step back
202@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])
203def test_empty_envvar(runner, env_key):

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 204–208why, one step back
204 @click.command()
205 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")206 def cli(mypath):207 click.echo(f"mypath: {mypath}")208

Merge pull request #2223 from pallets/env-varDavid Lordbefore adoption20c88f0

lines 209–210why, one step back
209 result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO")
210 assert result.exception is None

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 211–301why, one step back
211 assert result.output == "mypath: None\n"
212213214def test_multiple_envvar(runner):215 @click.command()216 @click.option("--arg", multiple=True)217 def cmd(arg):218 click.echo("|".join(arg))219220 result = runner.invoke(221 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}222 )223 assert not result.exception224 assert result.output == "foo|bar|baz\n"225226 @click.command()227 @click.option("--arg", multiple=True, envvar="X")228 def cmd(arg):229 click.echo("|".join(arg))230231 result = runner.invoke(cmd, [], env={"X": "foo bar baz"})232 assert not result.exception233 assert result.output == "foo|bar|baz\n"234235 @click.command()236 @click.option("--arg", multiple=True, type=click.Path())237 def cmd(arg):238 click.echo("|".join(arg))239240 result = runner.invoke(241 cmd,242 [],243 auto_envvar_prefix="TEST",244 env={"TEST_ARG": f"foo{os.path.pathsep}bar"},245 )246 assert not result.exception247 assert result.output == "foo|bar\n"248249250def test_trailing_blanks_boolean_envvar(runner):251 @click.command()252 @click.option("--shout/--no-shout", envvar="SHOUT")253 def cli(shout):254 click.echo(f"shout: {shout!r}")255256 result = runner.invoke(cli, [], env={"SHOUT": " true "})257 assert result.exit_code == 0258 assert result.output == "shout: True\n"259260261def test_multiple_default_help(runner):262 @click.command()263 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)264 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)265 def cmd(arg, arg2):266 pass267268 result = runner.invoke(cmd, ["--help"])269 assert not result.exception270 assert "foo, bar" in result.output271 assert "1, 2" in result.output272273274def test_show_default_default_map(runner):275 @click.command()276 @click.option("--arg", default="a", show_default=True)277 def cmd(arg):278 click.echo(arg)279280 result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})281282 assert not result.exception283 assert "[default: b]" in result.output284285286def test_multiple_default_type():287 opt = click.Option(["-a"], multiple=True, default=(1, 2))288 assert opt.nargs == 1289 assert opt.multiple290 assert opt.type is click.INT291 ctx = click.Context(click.Command("test"))292 assert opt.get_default(ctx) == (1, 2)293294295def test_multiple_default_composite_type():296 opt = click.Option(["-a"], multiple=True, default=[(1, "a")])297 assert opt.nargs == 2298 assert opt.multiple299 assert isinstance(opt.type, click.Tuple)300 assert opt.type.types == [click.INT, click.STRING]301 ctx = click.Context(click.Command("test"))

Merge branch '8.0.x'David Lordbefore adoption0a81393

line 302why, one step back
302 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 303–354why, one step back
303
304305def test_parse_multiple_default_composite_type(runner):306 @click.command()307 @click.option("-a", multiple=True, default=("a", "b"))308 @click.option("-b", multiple=True, default=[(1, "a")])309 def cmd(a, b):310 click.echo(a)311 click.echo(b)312313 # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())314 # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"315 result = runner.invoke(cmd)316 assert result.output == "('a', 'b')\n((1, 'a'),)\n"317318319def test_dynamic_default_help_unset(runner):320 @click.command()321 @click.option(322 "--username",323 prompt=True,324 default=lambda: os.environ.get("USER", ""),325 show_default=True,326 )327 def cmd(username):328 print("Hello,", username)329330 result = runner.invoke(cmd, ["--help"])331 assert result.exit_code == 0332 assert "--username" in result.output333 assert "lambda" not in result.output334 assert "(dynamic)" in result.output335336337def test_dynamic_default_help_text(runner):338 @click.command()339 @click.option(340 "--username",341 prompt=True,342 default=lambda: os.environ.get("USER", ""),343 show_default="current user",344 )345 def cmd(username):346 print("Hello,", username)347348 result = runner.invoke(cmd, ["--help"])349 assert result.exit_code == 0350 assert "--username" in result.output351 assert "lambda" not in result.output352 assert "(current user)" in result.output353354

Merge branch '8.0.x'David Lordbefore adoptionc63c70d

lines 355–364why, one step back
355def test_dynamic_default_help_special_method(runner):
356 class Value:357 def __call__(self):358 return 42359360 def __str__(self):361 return "special value"362363 opt = click.Option(["-a"], default=Value(), show_default=True)364 ctx = click.Context(click.Command("cli"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 365why, one step back
365 assert opt.get_help_extra(ctx) == {"default": "special value"}

Merge branch '8.0.x'David Lordbefore adoptionc63c70d

lines 366–368why, one step back
366 assert "special value" in opt.get_help_record(ctx)[1]
367368

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 369–377why, one step back
369@pytest.mark.parametrize(
370 ("type", "expect"),371 [372 (click.IntRange(1, 32), "1<=x<=32"),373 (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),374 (click.IntRange(1), "x>=1"),375 (click.IntRange(max=32), "x<=32"),376 ],377)

Merge branch '8.0.x'David Lordbefore adoption0a81393

lines 378–379why, one step back
378def test_intrange_default_help_text(type, expect):
379 option = click.Option(["--num"], type=type, show_default=True, default=2)

mention click in deprecation messageDavid Lordbefore adoption21e3587

line 380why, one step back
380 context = click.Context(click.Command("test"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 381why, one step back
381 assert option.get_help_extra(context) == {"default": "2", "range": expect}

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 382–385why, one step back
382 result = option.get_help_record(context)[1]
383 assert expect in result384385

Merge branch '8.0.x'David Lordbefore adoption0a81393

lines 386–389why, one step back
386def test_count_default_type_help():
387 """A count option with the default type should not show >=0 in help."""388 option = click.Option(["--count"], count=True, help="some words")389 context = click.Context(click.Command("test"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 390why, one step back
390 assert option.get_help_extra(context) == {}

Merge branch '8.0.x'David Lordbefore adoption0a81393

lines 391–405why, one step back
391 result = option.get_help_record(context)[1]
392 assert result == "some words"393394395def test_file_type_help_default():396 """The default for a File type is a filename string. The string397 should be displayed in help, not an open file object.398399 Type casting is only applied to defaults in processing, not when400 getting the default value.401 """402 option = click.Option(403 ["--in"], type=click.File(), default=__file__, show_default=True404 )405 context = click.Context(click.Command("test"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 406why, one step back
406 assert option.get_help_extra(context) == {"default": __file__}

Merge branch '8.0.x'David Lordbefore adoption0a81393

lines 407–410why, one step back
407 result = option.get_help_record(context)[1]
408 assert __file__ in result409410

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 411–555why, one step back
411def test_toupper_envvar_prefix(runner):
412 @click.command()413 @click.option("--arg")414 def cmd(arg):415 click.echo(arg)416417 result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})418 assert not result.exception419 assert result.output == "foo\n"420421422def test_nargs_envvar(runner):423 @click.command()424 @click.option("--arg", nargs=2)425 def cmd(arg):426 click.echo("|".join(arg))427428 result = runner.invoke(429 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}430 )431 assert not result.exception432 assert result.output == "foo|bar\n"433434 @click.command()435 @click.option("--arg", nargs=2, multiple=True)436 def cmd(arg):437 for item in arg:438 click.echo("|".join(item))439440 result = runner.invoke(441 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}442 )443 assert not result.exception444 assert result.output == "x|1\ny|2\n"445446447def test_show_envvar(runner):448 @click.command()449 @click.option("--arg1", envvar="ARG1", show_envvar=True)450 def cmd(arg):451 pass452453 result = runner.invoke(cmd, ["--help"])454 assert not result.exception455 assert "ARG1" in result.output456457458def test_show_envvar_auto_prefix(runner):459 @click.command()460 @click.option("--arg1", show_envvar=True)461 def cmd(arg):462 pass463464 result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")465 assert not result.exception466 assert "TEST_ARG1" in result.output467468469def test_show_envvar_auto_prefix_dash_in_command(runner):470 @click.group()471 def cli():472 pass473474 @cli.command()475 @click.option("--baz", show_envvar=True)476 def foo_bar(baz):477 pass478479 result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")480 assert not result.exception481 assert "TEST_FOO_BAR_BAZ" in result.output482483484def test_custom_validation(runner):485 def validate_pos_int(ctx, param, value):486 if value < 0:487 raise click.BadParameter("Value needs to be positive")488 return value489490 @click.command()491 @click.option("--foo", callback=validate_pos_int, default=1)492 def cmd(foo):493 click.echo(foo)494495 result = runner.invoke(cmd, ["--foo", "-1"])496 assert "Invalid value for '--foo': Value needs to be positive" in result.output497498 result = runner.invoke(cmd, ["--foo", "42"])499 assert result.output == "42\n"500501502def test_callback_validates_prompt(runner, monkeypatch):503 def validate(ctx, param, value):504 if value < 0:505 raise click.BadParameter("should be positive")506507 return value508509 @click.command()510 @click.option("-a", type=int, callback=validate, prompt=True)511 def cli(a):512 click.echo(a)513514 result = runner.invoke(cli, input="-12\n60\n")515 assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"516517518def test_winstyle_options(runner):519 @click.command()520 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")521 def cmd(debug):522 click.echo(debug)523524 result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])525 assert result.output == "True\n"526 result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])527 assert result.output == "False\n"528 result = runner.invoke(cmd, [], help_option_names=["/?"])529 assert result.output == "False\n"530 result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])531 assert "/debug; /no-debug Enables or disables debug mode." in result.output532 assert "/? Show this message and exit." in result.output533534535def test_legacy_options(runner):536 @click.command()537 @click.option("-whatever")538 def cmd(whatever):539 click.echo(whatever)540541 result = runner.invoke(cmd, ["-whatever", "42"])542 assert result.output == "42\n"543 result = runner.invoke(cmd, ["-whatever=23"])544 assert result.output == "23\n"545546547def test_missing_option_string_cast():548 ctx = click.Context(click.Command(""))549550 with pytest.raises(click.MissingParameter) as excinfo:551 click.Option(["-a"], required=True).process_value(ctx, None)552553 assert str(excinfo.value) == "Missing parameter: a"554555

Merge pull request #1990 from dannysepler/dsepler/enforce-required-flagDavid Lordbefore adoption4262661

lines 556–564why, one step back
556def test_missing_required_flag(runner):
557 cli = click.Command(558 "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]559 )560 result = runner.invoke(cli)561 assert result.exit_code == 2562 assert "Error: Missing option '--on'." in result.output563564

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 565–579why, one step back
565def test_missing_choice(runner):
566 @click.command()567 @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)568 def cmd(foo):569 click.echo(foo)570571 result = runner.invoke(cmd)572 assert result.exit_code == 2573 error, separator, choices = result.output.partition("Choose from")574 assert "Error: Missing option '--foo'. " in error575 assert "Choose from" in separator576 assert "foo" in choices577 assert "bar" in choices578579

show env var in error hint (#2696)KotlinIslandbefore adoption1b524bb

lines 580–595why, one step back
580def test_missing_envvar(runner):
581 cli = click.Command(582 "cli", params=[click.Option(["--foo"], envvar="bar", required=True)]583 )584 result = runner.invoke(cli)585 assert result.exit_code == 2586 assert "Error: Missing option '--foo'." in result.output587 cli = click.Command(588 "cli",589 params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)],590 )591 result = runner.invoke(cli)592 assert result.exit_code == 2593 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output594595

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 596–668why, one step back
596def test_case_insensitive_choice(runner):
597 @click.command()598 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))599 def cmd(foo):600 click.echo(foo)601602 result = runner.invoke(cmd, ["--foo", "apple"])603 assert result.exit_code == 0604 assert result.output == "Apple\n"605606 result = runner.invoke(cmd, ["--foo", "oRANGe"])607 assert result.exit_code == 0608 assert result.output == "Orange\n"609610 result = runner.invoke(cmd, ["--foo", "Apple"])611 assert result.exit_code == 0612 assert result.output == "Apple\n"613614 @click.command()615 @click.option("--foo", type=click.Choice(["Orange", "Apple"]))616 def cmd2(foo):617 click.echo(foo)618619 result = runner.invoke(cmd2, ["--foo", "apple"])620 assert result.exit_code == 2621622 result = runner.invoke(cmd2, ["--foo", "oRANGe"])623 assert result.exit_code == 2624625 result = runner.invoke(cmd2, ["--foo", "Apple"])626 assert result.exit_code == 0627628629def test_case_insensitive_choice_returned_exactly(runner):630 @click.command()631 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))632 def cmd(foo):633 click.echo(foo)634635 result = runner.invoke(cmd, ["--foo", "apple"])636 assert result.exit_code == 0637 assert result.output == "Apple\n"638639640def test_option_help_preserve_paragraphs(runner):641 @click.command()642 @click.option(643 "-C",644 "--config",645 type=click.Path(),646 help="""Configuration file to use.647648 If not given, the environment variable CONFIG_FILE is consulted649 and used if set. If neither are given, a default configuration650 file is loaded.""",651 )652 def cmd(config):653 pass654655 result = runner.invoke(cmd, ["--help"])656 assert result.exit_code == 0657 i = " " * 21658 assert (659 " -C, --config PATH Configuration file to use.\n"660 f"{i}\n"661 f"{i}If not given, the environment variable CONFIG_FILE is\n"662 f"{i}consulted and used if set. If neither are given, a default\n"663 f"{i}configuration file is loaded."664 ) in result.output665666667def test_argument_custom_class(runner):668 class CustomArgument(click.Argument):

Merge branch '8.0.x'David Lordbefore adoption29df879

line 669why, one step back
669 def get_default(self, ctx, call=True):

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 670–809why, one step back
670 """a dumb override of a default value for testing"""
671 return "I am a default"672673 @click.command()674 @click.argument("testarg", cls=CustomArgument, default="you wont see me")675 def cmd(testarg):676 click.echo(testarg)677678 result = runner.invoke(cmd)679 assert "I am a default" in result.output680 assert "you wont see me" not in result.output681682683def test_option_custom_class(runner):684 class CustomOption(click.Option):685 def get_help_record(self, ctx):686 """a dumb override of a help text for testing"""687 return ("--help", "I am a help text")688689 @click.command()690 @click.option("--testoption", cls=CustomOption, help="you wont see me")691 def cmd(testoption):692 click.echo(testoption)693694 result = runner.invoke(cmd, ["--help"])695 assert "I am a help text" in result.output696 assert "you wont see me" not in result.output697698699def test_option_custom_class_reusable(runner):700 """Ensure we can reuse a custom class option. See Issue #926"""701702 class CustomOption(click.Option):703 def get_help_record(self, ctx):704 """a dumb override of a help text for testing"""705 return ("--help", "I am a help text")706707 # Assign to a variable to re-use the decorator.708 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")709710 @click.command()711 @testoption712 def cmd1(testoption):713 click.echo(testoption)714715 @click.command()716 @testoption717 def cmd2(testoption):718 click.echo(testoption)719720 # Both of the commands should have the --help option now.721 for cmd in (cmd1, cmd2):722 result = runner.invoke(cmd, ["--help"])723 assert "I am a help text" in result.output724 assert "you wont see me" not in result.output725726727def test_bool_flag_with_type(runner):728 @click.command()729 @click.option("--shout/--no-shout", default=False, type=bool)730 def cmd(shout):731 pass732733 result = runner.invoke(cmd)734 assert not result.exception735736737def test_aliases_for_flags(runner):738 @click.command()739 @click.option("--warnings/--no-warnings", " /-W", default=True)740 def cli(warnings):741 click.echo(warnings)742743 result = runner.invoke(cli, ["--warnings"])744 assert result.output == "True\n"745 result = runner.invoke(cli, ["--no-warnings"])746 assert result.output == "False\n"747 result = runner.invoke(cli, ["-W"])748 assert result.output == "False\n"749750 @click.command()751 @click.option("--warnings/--no-warnings", "-w", default=True)752 def cli_alt(warnings):753 click.echo(warnings)754755 result = runner.invoke(cli_alt, ["--warnings"])756 assert result.output == "True\n"757 result = runner.invoke(cli_alt, ["--no-warnings"])758 assert result.output == "False\n"759 result = runner.invoke(cli_alt, ["-w"])760 assert result.output == "True\n"761762763@pytest.mark.parametrize(764 "option_args,expected",765 [766 (["--aggressive", "--all", "-a"], "aggressive"),767 (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),768 (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),769 (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),770 (["-a", "-b", "-c"], "a"),771 (["-c", "-b", "-a"], "c"),772 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),773 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),774 (["--from", "-f", "_from"], "_from"),775 (["--return", "-r", "_ret"], "_ret"),776 ],777)778def test_option_names(runner, option_args, expected):779 @click.command()780 @click.option(*option_args, is_flag=True)781 def cmd(**kwargs):782 click.echo(str(kwargs[expected]))783784 assert cmd.params[0].name == expected785786 for form in option_args:787 if form.startswith("-"):788 result = runner.invoke(cmd, [form])789 assert result.output == "True\n"790791792def test_flag_duplicate_names(runner):793 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):794 click.Option(["--foo/--foo"], default=False)795796797@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])798def test_show_default_boolean_flag_name(runner, default, expect):799 """When a boolean flag has distinct True/False opts, it should show800 the default opt name instead of the default value. It should only801 show one name even if multiple are declared.802 """803 opt = click.Option(804 ("--cache/--no-cache", "--c/--nc"),805 default=default,806 show_default=True,807 help="Enable/Disable the cache.",808 )809 ctx = click.Context(click.Command("test"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 810why, one step back
810 assert opt.get_help_extra(ctx) == {"default": expect}

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 811–814why, one step back
811 message = opt.get_help_record(ctx)[1]
812 assert f"[default: {expect}]" in message813814

Merge pull request #1998 from MLH-Fellowship/1971-hide-defaultsDavid Lordbefore adoption5d759e0

lines 815–817why, one step back
815def test_show_true_default_boolean_flag_value(runner):
816 """When a boolean flag only has one opt and its default is True,817 it will show the default value, not the opt name.

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 818–819why, one step back
818 """
819 opt = click.Option(

Merge pull request #1998 from MLH-Fellowship/1971-hide-defaultsDavid Lordbefore adoption5d759e0

lines 820–824why, one step back
820 ("--cache",),
821 is_flag=True,822 show_default=True,823 default=True,824 help="Enable the cache.",

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 825–826why, one step back
825 )
826 ctx = click.Context(click.Command("test"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 827why, one step back
827 assert opt.get_help_extra(ctx) == {"default": "True"}

mention click in deprecation messageDavid Lordbefore adoption21e3587

line 828why, one step back
828 message = opt.get_help_record(ctx)[1]

Merge pull request #1998 from MLH-Fellowship/1971-hide-defaultsDavid Lordbefore adoption5d759e0

lines 829–844why, one step back
829 assert "[default: True]" in message
830831832@pytest.mark.parametrize("default", [False, None])833def test_hide_false_default_boolean_flag_value(runner, default):834 """When a boolean flag only has one opt and its default is False or835 None, it will not show the default836 """837 opt = click.Option(838 ("--cache",),839 is_flag=True,840 show_default=True,841 default=default,842 help="Enable the cache.",843 )844 ctx = click.Context(click.Command("test"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 845why, one step back
845 assert opt.get_help_extra(ctx) == {}

Merge pull request #1998 from MLH-Fellowship/1971-hide-defaultsDavid Lordbefore adoption5d759e0

lines 846–847why, one step back
846 message = opt.get_help_record(ctx)[1]
847 assert "[default: " not in message

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 848–853why, one step back
848
849850def test_show_default_string(runner):851 """When show_default is a string show that value as default."""852 opt = click.Option(["--limit"], show_default="unlimited")853 ctx = click.Context(click.Command("cli"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 854why, one step back
854 assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 855–858why, one step back
855 message = opt.get_help_record(ctx)[1]
856 assert "[default: (unlimited)]" in message857858

Merge branch '8.1.x'David Lordbefore adoption99015e1

lines 859–866why, one step back
859def test_show_default_with_empty_string(runner):
860 """When show_default is True and default is set to an empty string."""861 opt = click.Option(["--limit"], default="", show_default=True)862 ctx = click.Context(click.Command("cli"))863 message = opt.get_help_record(ctx)[1]864 assert '[default: ""]' in message865866

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 867–870why, one step back
867def test_do_not_show_no_default(runner):
868 """When show_default is True and no default is set do not show None."""869 opt = click.Option(["--limit"], show_default=True)870 ctx = click.Context(click.Command("cli"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 871why, one step back
871 assert opt.get_help_extra(ctx) == {}

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 872–875why, one step back
872 message = opt.get_help_record(ctx)[1]
873 assert "[default: None]" not in message874875

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd

lines 876–881why, one step back
876def test_do_not_show_default_empty_multiple():
877 """When show_default is True and multiple=True is set, it should not878 print empty default value in --help output.879 """880 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)881 ctx = click.Context(click.Command("cli"))

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 882why, one step back
882 assert opt.get_help_extra(ctx) == {}

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd

lines 883–884why, one step back
883 message = opt.get_help_record(ctx)[1]
884 assert message == "values"

Merge pull request #1964 from janluke/fix/show_default-priorityDavid Lordbefore adoption166b312

lines 885–887why, one step back
885
886887@pytest.mark.parametrize(

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 888why, one step back
888 ("ctx_value", "opt_value", "extra_value", "expect"),

Merge pull request #1964 from janluke/fix/show_default-priorityDavid Lordbefore adoption166b312

line 889why, one step back
889 [

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

lines 890–899why, one step back
890 (None, None, {}, False),
891 (None, False, {}, False),892 (None, True, {"default": "1"}, True),893 (False, None, {}, False),894 (False, False, {}, False),895 (False, True, {"default": "1"}, True),896 (True, None, {"default": "1"}, True),897 (True, False, {}, False),898 (True, True, {"default": "1"}, True),899 (False, "one", {"default": "(one)"}, True),

Merge pull request #1964 from janluke/fix/show_default-priorityDavid Lordbefore adoption166b312

lines 900–901why, one step back
900 ],
901)

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 902why, one step back
902def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):

Merge pull request #1964 from janluke/fix/show_default-priorityDavid Lordbefore adoption166b312

lines 903–904why, one step back
903 ctx = click.Context(click.Command("test"), show_default=ctx_value)
904 opt = click.Option("-a", default=1, help="value", show_default=opt_value)

Split generation of help extra items and rendering (#2517)Kevin Deldyckebefore adoption948d7a7

line 905why, one step back
905 assert opt.get_help_extra(ctx) == extra_value

Merge pull request #1964 from janluke/fix/show_default-priorityDavid Lordbefore adoption166b312

lines 906–907why, one step back
906 help = opt.get_help_record(ctx)[1]
907 assert ("default:" in help) is expect

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd

lines 908–909why, one step back
908
909

mention click in deprecation messageDavid Lordbefore adoption21e3587

lines 910–938why, one step back
910@pytest.mark.parametrize(
911 ("args", "expect"),912 [913 (None, (None, None, ())),914 (["--opt"], ("flag", None, ())),915 (["--opt", "-a", 42], ("flag", "42", ())),916 (["--opt", "test", "-a", 42], ("test", "42", ())),917 (["--opt=test", "-a", 42], ("test", "42", ())),918 (["-o"], ("flag", None, ())),919 (["-o", "-a", 42], ("flag", "42", ())),920 (["-o", "test", "-a", 42], ("test", "42", ())),921 (["-otest", "-a", 42], ("test", "42", ())),922 (["a", "b", "c"], (None, None, ("a", "b", "c"))),923 (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),924 (["--opt", "test"], ("test", None, ())),925 (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),926 (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),927 ],928)929def test_option_with_optional_value(runner, args, expect):930 @click.command()931 @click.option("-o", "--opt", is_flag=False, flag_value="flag")932 @click.option("-a")933 @click.argument("b", nargs=-1)934 def cli(opt, a, b):935 return opt, a, b936937 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)938 assert result.return_value == expect

Merge branch '8.0.x'David Lordbefore adoption0a81393

lines 939–961why, one step back
939
940941def test_multiple_option_with_optional_value(runner):942 cli = click.Command(943 "cli",944 params=[945 click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),946 click.Option(["-a"]),947 click.Argument(["b"], nargs=-1),948 ],949 callback=lambda **kwargs: kwargs,950 )951 result = runner.invoke(952 cli,953 ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],954 standalone_mode=False,955 catch_exceptions=False,956 )957 assert result.return_value == {958 "f": ("flag", "other", "flag"),959 "a": "1",960 "b": ("a", "b"),961 }

Merge branch '8.0.x'David Lordbefore adoption29df879

lines 962–968why, one step back
962
963964def test_type_from_flag_value():965 param = click.Option(["-a", "x"], default=True, flag_value=4)966 assert param.type is click.INT967 param = click.Option(["-b", "x"], flag_value=8)968 assert param.type is click.INT

Merge remote-tracking branch 'origin/8.0.x'David Lordbefore adoptionce152bd

lines 969–987why, one step back
969
970971@pytest.mark.parametrize(972 ("option", "expected"),973 [974 # Not boolean flags975 pytest.param(Option(["-a"], type=int), False, id="int option"),976 pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),977 pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),978 pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),979 pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),980 # Boolean flags981 pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),982 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),983 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),984 ],985)986def test_is_bool_flag_is_correctly_set(option, expected):987 assert option.is_bool_flag is expected

Merge branch '8.1.x'David Lordbefore adoption0aec116

lines 988–1001why, one step back
988
989990@pytest.mark.parametrize(991 ("kwargs", "message"),992 [993 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),994 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),995 ],996)997def test_invalid_flag_combinations(runner, kwargs, message):998 with pytest.raises(TypeError) as e:999 click.Option(["-a"], **kwargs)10001001 assert message in str(e.value)

Fix metavar for Choice options when show_choices=False (#2365)mrmupsbefore adoption1a4d8c1

lines 1002–1037why, one step back
1002
10031004@pytest.mark.parametrize(1005 ("choices", "metavars"),1006 [1007 pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1008 pytest.param([1, 2], "[INTEGER]", id="int choices"),1009 pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1010 pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1011 pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1012 ],1013)1014def test_usage_show_choices(runner, choices, metavars):1015 """When show_choices=False is set, the --help output1016 should print choice metavars instead of values.1017 """10181019 @click.command()1020 @click.option("-g", type=click.Choice(choices))1021 def cli_with_choices(g):1022 pass10231024 @click.command()1025 @click.option(1026 "-g",1027 type=click.Choice(choices),1028 show_choices=False,1029 )1030 def cli_without_choices(g):1031 pass10321033 result = runner.invoke(cli_with_choices, ["--help"])1034 assert f"[{'|'.join([str(i) for i in choices])}]" in result.output10351036 result = runner.invoke(cli_without_choices, ["--help"])1037 assert metavars in result.output

Give a UserWarning when Parameter is overriden by name (#2397)Ed Rogersbefore adoption3800083

lines 1038–1063why, one step back
1038
10391040@pytest.mark.parametrize(1041 "opts_one,opts_two",1042 [1043 # No duplicate shortnames1044 (1045 ("-a", "--aardvark"),1046 ("-a", "--avocado"),1047 ),1048 # No duplicate long names1049 (1050 ("-a", "--aardvark"),1051 ("-b", "--aardvark"),1052 ),1053 ],1054)1055def test_duplicate_names_warning(runner, opts_one, opts_two):1056 @click.command()1057 @click.option(*opts_one)1058 @click.option(*opts_two)1059 def cli(one, two):1060 pass10611062 with pytest.warns(UserWarning):1063 runner.invoke(cli, [])