Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

920 lines · 27.9 KiB · Python

Last changed by

Merge branch '8.1.x'David Lordbefore adoptiond9af5cf

History of this file

Take it

The walk stopped after 200 commits: lines older than 98e471f point at it.

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

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

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 8–36why, 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 message343536def test_invalid_nargs(runner):

Merge pull request #1852 from pallets/validate-multiDavid Lordbefore adoptioncef43de

line 37why, one step back
37 with pytest.raises(TypeError, match="nargs=-1"):

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 38–86why, one step back
38
39 @click.command()40 @click.option("--foo", nargs=-1)41 def cli(foo):42 pass434445def test_nargs_tup_composite_mult(runner):46 @click.command()47 @click.option("--item", type=(str, int), multiple=True)48 def copy(item):49 for name, id in item:50 click.echo(f"name={name} id={id:d}")5152 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])53 assert not result.exception54 assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]555657def test_counting(runner):58 @click.command()59 @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))60 def cli(v):61 click.echo(f"verbosity={v:d}")6263 result = runner.invoke(cli, ["-vvv"])64 assert not result.exception65 assert result.output == "verbosity=3\n"6667 result = runner.invoke(cli, ["-vvvv"])68 assert result.exception69 assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output7071 result = runner.invoke(cli, [])72 assert not result.exception73 assert result.output == "verbosity=0\n"7475 result = runner.invoke(cli, ["--help"])76 assert re.search(r"-v\s+Verbosity", result.output) is not None777879@pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])80def test_unknown_options(runner, unknown_flag):81 @click.command()82 def cli():83 pass8485 result = runner.invoke(cli, [unknown_flag])86 assert result.exception

Merge pull request #1829 from MLH-Fellowship/add-i18nDavid Lordbefore adoptionc454226

line 87why, one step back
87 assert f"No such option: {unknown_flag}" in result.output

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 88–120why, one step back
88
8990@pytest.mark.parametrize(91 ("value", "expect"),92 [93 ("--cat", "Did you mean --count?"),94 ("--bounds", "(Possible options: --bound, --count)"),95 ("--bount", "(Possible options: --bound, --count)"),96 ],97)98def test_suggest_possible_options(runner, value, expect):99 cli = click.Command(100 "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]101 )102 result = runner.invoke(cli, [value])103 assert expect in result.output104105106def test_multiple_required(runner):107 @click.command()108 @click.option("-m", "--message", multiple=True, required=True)109 def cli(message):110 click.echo("\n".join(message))111112 result = runner.invoke(cli, ["-m", "foo", "-mbar"])113 assert not result.exception114 assert result.output == "foo\nbar\n"115116 result = runner.invoke(cli, [])117 assert result.exception118 assert "Error: Missing option '-m' / '--message'." in result.output119120

Merge pull request #1852 from pallets/validate-multiDavid Lordbefore adoptioncef43de

lines 121–137why, one step back
121@pytest.mark.parametrize(
122 ("multiple", "nargs", "default"),123 [124 (True, 1, []),125 (True, 1, [1]),126 # (False, -1, []),127 # (False, -1, [1]),128 (False, 2, [1, 2]),129 # (True, -1, [[]]),130 # (True, -1, []),131 # (True, -1, [[1]]),132 (True, 2, []),133 (True, 2, [[1, 2]]),134 ],135)136def test_init_good_default_list(runner, multiple, nargs, default):137 click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)

Better error message for bad parameter default (#1805)Saif Kazibefore adoption1cb8609

line 138why, one step back
138

Merge pull request #1852 from pallets/validate-multiDavid Lordbefore adoptioncef43de

lines 139–153why, one step back
139
140@pytest.mark.parametrize(141 ("multiple", "nargs", "default"),142 [143 (True, 1, 1),144 # (False, -1, 1),145 (False, 2, [1]),146 (True, 2, [[1]]),147 ],148)149def test_init_bad_default_list(runner, multiple, nargs, default):150 type = (str, str) if nargs == 2 else None151152 with pytest.raises(ValueError, match="default"):153 click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)

Better error message for bad parameter default (#1805)Saif Kazibefore adoption1cb8609

lines 154–155why, one step back
154
155

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

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

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 158–162why, one step back
158 @click.command()
159 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")160 def cli(mypath):161 click.echo(f"mypath: {mypath}")162

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

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

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 165–255why, one step back
165 assert result.output == "mypath: None\n"
166167168def test_multiple_envvar(runner):169 @click.command()170 @click.option("--arg", multiple=True)171 def cmd(arg):172 click.echo("|".join(arg))173174 result = runner.invoke(175 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}176 )177 assert not result.exception178 assert result.output == "foo|bar|baz\n"179180 @click.command()181 @click.option("--arg", multiple=True, envvar="X")182 def cmd(arg):183 click.echo("|".join(arg))184185 result = runner.invoke(cmd, [], env={"X": "foo bar baz"})186 assert not result.exception187 assert result.output == "foo|bar|baz\n"188189 @click.command()190 @click.option("--arg", multiple=True, type=click.Path())191 def cmd(arg):192 click.echo("|".join(arg))193194 result = runner.invoke(195 cmd,196 [],197 auto_envvar_prefix="TEST",198 env={"TEST_ARG": f"foo{os.path.pathsep}bar"},199 )200 assert not result.exception201 assert result.output == "foo|bar\n"202203204def test_trailing_blanks_boolean_envvar(runner):205 @click.command()206 @click.option("--shout/--no-shout", envvar="SHOUT")207 def cli(shout):208 click.echo(f"shout: {shout!r}")209210 result = runner.invoke(cli, [], env={"SHOUT": " true "})211 assert result.exit_code == 0212 assert result.output == "shout: True\n"213214215def test_multiple_default_help(runner):216 @click.command()217 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)218 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)219 def cmd(arg, arg2):220 pass221222 result = runner.invoke(cmd, ["--help"])223 assert not result.exception224 assert "foo, bar" in result.output225 assert "1, 2" in result.output226227228def test_show_default_default_map(runner):229 @click.command()230 @click.option("--arg", default="a", show_default=True)231 def cmd(arg):232 click.echo(arg)233234 result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})235236 assert not result.exception237 assert "[default: b]" in result.output238239240def test_multiple_default_type():241 opt = click.Option(["-a"], multiple=True, default=(1, 2))242 assert opt.nargs == 1243 assert opt.multiple244 assert opt.type is click.INT245 ctx = click.Context(click.Command("test"))246 assert opt.get_default(ctx) == (1, 2)247248249def test_multiple_default_composite_type():250 opt = click.Option(["-a"], multiple=True, default=[(1, "a")])251 assert opt.nargs == 2252 assert opt.multiple253 assert isinstance(opt.type, click.Tuple)254 assert opt.type.types == [click.INT, click.STRING]255 ctx = click.Context(click.Command("test"))

Merge branch '8.0.x'David Lordbefore adoption0a81393

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

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 257–308why, one step back
257
258259def test_parse_multiple_default_composite_type(runner):260 @click.command()261 @click.option("-a", multiple=True, default=("a", "b"))262 @click.option("-b", multiple=True, default=[(1, "a")])263 def cmd(a, b):264 click.echo(a)265 click.echo(b)266267 # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())268 # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"269 result = runner.invoke(cmd)270 assert result.output == "('a', 'b')\n((1, 'a'),)\n"271272273def test_dynamic_default_help_unset(runner):274 @click.command()275 @click.option(276 "--username",277 prompt=True,278 default=lambda: os.environ.get("USER", ""),279 show_default=True,280 )281 def cmd(username):282 print("Hello,", username)283284 result = runner.invoke(cmd, ["--help"])285 assert result.exit_code == 0286 assert "--username" in result.output287 assert "lambda" not in result.output288 assert "(dynamic)" in result.output289290291def test_dynamic_default_help_text(runner):292 @click.command()293 @click.option(294 "--username",295 prompt=True,296 default=lambda: os.environ.get("USER", ""),297 show_default="current user",298 )299 def cmd(username):300 print("Hello,", username)301302 result = runner.invoke(cmd, ["--help"])303 assert result.exit_code == 0304 assert "--username" in result.output305 assert "lambda" not in result.output306 assert "(current user)" in result.output307308

Merge branch '8.0.x'David Lordbefore adoptionc63c70d

lines 309–321why, one step back
309def test_dynamic_default_help_special_method(runner):
310 class Value:311 def __call__(self):312 return 42313314 def __str__(self):315 return "special value"316317 opt = click.Option(["-a"], default=Value(), show_default=True)318 ctx = click.Context(click.Command("cli"))319 assert "special value" in opt.get_help_record(ctx)[1]320321

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 322–330why, one step back
322@pytest.mark.parametrize(
323 ("type", "expect"),324 [325 (click.IntRange(1, 32), "1<=x<=32"),326 (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),327 (click.IntRange(1), "x>=1"),328 (click.IntRange(max=32), "x<=32"),329 ],330)

Merge branch '8.0.x'David Lordbefore adoption0a81393

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

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 333–337why, one step back
333 context = click.Context(click.Command("test"))
334 result = option.get_help_record(context)[1]335 assert expect in result336337

Merge branch '8.0.x'David Lordbefore adoption0a81393

lines 338–360why, one step back
338def test_count_default_type_help():
339 """A count option with the default type should not show >=0 in help."""340 option = click.Option(["--count"], count=True, help="some words")341 context = click.Context(click.Command("test"))342 result = option.get_help_record(context)[1]343 assert result == "some words"344345346def test_file_type_help_default():347 """The default for a File type is a filename string. The string348 should be displayed in help, not an open file object.349350 Type casting is only applied to defaults in processing, not when351 getting the default value.352 """353 option = click.Option(354 ["--in"], type=click.File(), default=__file__, show_default=True355 )356 context = click.Context(click.Command("test"))357 result = option.get_help_record(context)[1]358 assert __file__ in result359360

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 361–451why, one step back
361def test_toupper_envvar_prefix(runner):
362 @click.command()363 @click.option("--arg")364 def cmd(arg):365 click.echo(arg)366367 result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})368 assert not result.exception369 assert result.output == "foo\n"370371372def test_nargs_envvar(runner):373 @click.command()374 @click.option("--arg", nargs=2)375 def cmd(arg):376 click.echo("|".join(arg))377378 result = runner.invoke(379 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}380 )381 assert not result.exception382 assert result.output == "foo|bar\n"383384 @click.command()385 @click.option("--arg", nargs=2, multiple=True)386 def cmd(arg):387 for item in arg:388 click.echo("|".join(item))389390 result = runner.invoke(391 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}392 )393 assert not result.exception394 assert result.output == "x|1\ny|2\n"395396397def test_show_envvar(runner):398 @click.command()399 @click.option("--arg1", envvar="ARG1", show_envvar=True)400 def cmd(arg):401 pass402403 result = runner.invoke(cmd, ["--help"])404 assert not result.exception405 assert "ARG1" in result.output406407408def test_show_envvar_auto_prefix(runner):409 @click.command()410 @click.option("--arg1", show_envvar=True)411 def cmd(arg):412 pass413414 result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")415 assert not result.exception416 assert "TEST_ARG1" in result.output417418419def test_show_envvar_auto_prefix_dash_in_command(runner):420 @click.group()421 def cli():422 pass423424 @cli.command()425 @click.option("--baz", show_envvar=True)426 def foo_bar(baz):427 pass428429 result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")430 assert not result.exception431 assert "TEST_FOO_BAR_BAZ" in result.output432433434def test_custom_validation(runner):435 def validate_pos_int(ctx, param, value):436 if value < 0:437 raise click.BadParameter("Value needs to be positive")438 return value439440 @click.command()441 @click.option("--foo", callback=validate_pos_int, default=1)442 def cmd(foo):443 click.echo(foo)444445 result = runner.invoke(cmd, ["--foo", "-1"])446 assert "Invalid value for '--foo': Value needs to be positive" in result.output447448 result = runner.invoke(cmd, ["--foo", "42"])449 assert result.output == "42\n"450451

Merge pull request #1785 from MLH-Fellowship/sanitize-inputDavid Lordbefore adoption80086c4

lines 452–467why, one step back
452def test_callback_validates_prompt(runner, monkeypatch):
453 def validate(ctx, param, value):454 if value < 0:455 raise click.BadParameter("should be positive")456457 return value458459 @click.command()460 @click.option("-a", type=int, callback=validate, prompt=True)461 def cli(a):462 click.echo(a)463464 result = runner.invoke(cli, input="-12\n60\n")465 assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"466467

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 468–500why, one step back
468def test_winstyle_options(runner):
469 @click.command()470 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")471 def cmd(debug):472 click.echo(debug)473474 result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])475 assert result.output == "True\n"476 result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])477 assert result.output == "False\n"478 result = runner.invoke(cmd, [], help_option_names=["/?"])479 assert result.output == "False\n"480 result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])481 assert "/debug; /no-debug Enables or disables debug mode." in result.output482 assert "/? Show this message and exit." in result.output483484485def test_legacy_options(runner):486 @click.command()487 @click.option("-whatever")488 def cmd(whatever):489 click.echo(whatever)490491 result = runner.invoke(cmd, ["-whatever", "42"])492 assert result.output == "42\n"493 result = runner.invoke(cmd, ["-whatever=23"])494 assert result.output == "23\n"495496497def test_missing_option_string_cast():498 ctx = click.Context(click.Command(""))499500 with pytest.raises(click.MissingParameter) as excinfo:

Merge pull request #1785 from MLH-Fellowship/sanitize-inputDavid Lordbefore adoption80086c4

line 501why, one step back
501 click.Option(["-a"], required=True).process_value(ctx, None)

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

line 502why, one step back
502

Merge pull request #1829 from MLH-Fellowship/add-i18nDavid Lordbefore adoptionc454226

line 503why, one step back
503 assert str(excinfo.value) == "Missing parameter: a"

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 504–505why, one step back
504
505

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

lines 506–514why, one step back
506def test_missing_required_flag(runner):
507 cli = click.Command(508 "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]509 )510 result = runner.invoke(cli)511 assert result.exit_code == 2512 assert "Error: Missing option '--on'." in result.output513514

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 515–602why, one step back
515def test_missing_choice(runner):
516 @click.command()517 @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)518 def cmd(foo):519 click.echo(foo)520521 result = runner.invoke(cmd)522 assert result.exit_code == 2523 error, separator, choices = result.output.partition("Choose from")524 assert "Error: Missing option '--foo'. " in error525 assert "Choose from" in separator526 assert "foo" in choices527 assert "bar" in choices528529530def test_case_insensitive_choice(runner):531 @click.command()532 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))533 def cmd(foo):534 click.echo(foo)535536 result = runner.invoke(cmd, ["--foo", "apple"])537 assert result.exit_code == 0538 assert result.output == "Apple\n"539540 result = runner.invoke(cmd, ["--foo", "oRANGe"])541 assert result.exit_code == 0542 assert result.output == "Orange\n"543544 result = runner.invoke(cmd, ["--foo", "Apple"])545 assert result.exit_code == 0546 assert result.output == "Apple\n"547548 @click.command()549 @click.option("--foo", type=click.Choice(["Orange", "Apple"]))550 def cmd2(foo):551 click.echo(foo)552553 result = runner.invoke(cmd2, ["--foo", "apple"])554 assert result.exit_code == 2555556 result = runner.invoke(cmd2, ["--foo", "oRANGe"])557 assert result.exit_code == 2558559 result = runner.invoke(cmd2, ["--foo", "Apple"])560 assert result.exit_code == 0561562563def test_case_insensitive_choice_returned_exactly(runner):564 @click.command()565 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))566 def cmd(foo):567 click.echo(foo)568569 result = runner.invoke(cmd, ["--foo", "apple"])570 assert result.exit_code == 0571 assert result.output == "Apple\n"572573574def test_option_help_preserve_paragraphs(runner):575 @click.command()576 @click.option(577 "-C",578 "--config",579 type=click.Path(),580 help="""Configuration file to use.581582 If not given, the environment variable CONFIG_FILE is consulted583 and used if set. If neither are given, a default configuration584 file is loaded.""",585 )586 def cmd(config):587 pass588589 result = runner.invoke(cmd, ["--help"])590 assert result.exit_code == 0591 i = " " * 21592 assert (593 " -C, --config PATH Configuration file to use.\n"594 f"{i}\n"595 f"{i}If not given, the environment variable CONFIG_FILE is\n"596 f"{i}consulted and used if set. If neither are given, a default\n"597 f"{i}configuration file is loaded."598 ) in result.output599600601def test_argument_custom_class(runner):602 class CustomArgument(click.Argument):

Merge branch '8.0.x'David Lordbefore adoption29df879

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

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 604–747why, one step back
604 """a dumb override of a default value for testing"""
605 return "I am a default"606607 @click.command()608 @click.argument("testarg", cls=CustomArgument, default="you wont see me")609 def cmd(testarg):610 click.echo(testarg)611612 result = runner.invoke(cmd)613 assert "I am a default" in result.output614 assert "you wont see me" not in result.output615616617def test_option_custom_class(runner):618 class CustomOption(click.Option):619 def get_help_record(self, ctx):620 """a dumb override of a help text for testing"""621 return ("--help", "I am a help text")622623 @click.command()624 @click.option("--testoption", cls=CustomOption, help="you wont see me")625 def cmd(testoption):626 click.echo(testoption)627628 result = runner.invoke(cmd, ["--help"])629 assert "I am a help text" in result.output630 assert "you wont see me" not in result.output631632633def test_option_custom_class_reusable(runner):634 """Ensure we can reuse a custom class option. See Issue #926"""635636 class CustomOption(click.Option):637 def get_help_record(self, ctx):638 """a dumb override of a help text for testing"""639 return ("--help", "I am a help text")640641 # Assign to a variable to re-use the decorator.642 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")643644 @click.command()645 @testoption646 def cmd1(testoption):647 click.echo(testoption)648649 @click.command()650 @testoption651 def cmd2(testoption):652 click.echo(testoption)653654 # Both of the commands should have the --help option now.655 for cmd in (cmd1, cmd2):656 result = runner.invoke(cmd, ["--help"])657 assert "I am a help text" in result.output658 assert "you wont see me" not in result.output659660661def test_bool_flag_with_type(runner):662 @click.command()663 @click.option("--shout/--no-shout", default=False, type=bool)664 def cmd(shout):665 pass666667 result = runner.invoke(cmd)668 assert not result.exception669670671def test_aliases_for_flags(runner):672 @click.command()673 @click.option("--warnings/--no-warnings", " /-W", default=True)674 def cli(warnings):675 click.echo(warnings)676677 result = runner.invoke(cli, ["--warnings"])678 assert result.output == "True\n"679 result = runner.invoke(cli, ["--no-warnings"])680 assert result.output == "False\n"681 result = runner.invoke(cli, ["-W"])682 assert result.output == "False\n"683684 @click.command()685 @click.option("--warnings/--no-warnings", "-w", default=True)686 def cli_alt(warnings):687 click.echo(warnings)688689 result = runner.invoke(cli_alt, ["--warnings"])690 assert result.output == "True\n"691 result = runner.invoke(cli_alt, ["--no-warnings"])692 assert result.output == "False\n"693 result = runner.invoke(cli_alt, ["-w"])694 assert result.output == "True\n"695696697@pytest.mark.parametrize(698 "option_args,expected",699 [700 (["--aggressive", "--all", "-a"], "aggressive"),701 (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),702 (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),703 (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),704 (["-a", "-b", "-c"], "a"),705 (["-c", "-b", "-a"], "c"),706 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),707 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),708 (["--from", "-f", "_from"], "_from"),709 (["--return", "-r", "_ret"], "_ret"),710 ],711)712def test_option_names(runner, option_args, expected):713 @click.command()714 @click.option(*option_args, is_flag=True)715 def cmd(**kwargs):716 click.echo(str(kwargs[expected]))717718 assert cmd.params[0].name == expected719720 for form in option_args:721 if form.startswith("-"):722 result = runner.invoke(cmd, [form])723 assert result.output == "True\n"724725726def test_flag_duplicate_names(runner):727 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):728 click.Option(["--foo/--foo"], default=False)729730731@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])732def test_show_default_boolean_flag_name(runner, default, expect):733 """When a boolean flag has distinct True/False opts, it should show734 the default opt name instead of the default value. It should only735 show one name even if multiple are declared.736 """737 opt = click.Option(738 ("--cache/--no-cache", "--c/--nc"),739 default=default,740 show_default=True,741 help="Enable/Disable the cache.",742 )743 ctx = click.Context(click.Command("test"))744 message = opt.get_help_record(ctx)[1]745 assert f"[default: {expect}]" in message746747

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

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

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 751–752why, one step back
751 """
752 opt = click.Option(

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

lines 753–757why, one step back
753 ("--cache",),
754 is_flag=True,755 show_default=True,756 default=True,757 help="Enable the cache.",

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 758–760why, one step back
758 )
759 ctx = click.Context(click.Command("test"))760 message = opt.get_help_record(ctx)[1]

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

lines 761–778why, one step back
761 assert "[default: True]" in message
762763764@pytest.mark.parametrize("default", [False, None])765def test_hide_false_default_boolean_flag_value(runner, default):766 """When a boolean flag only has one opt and its default is False or767 None, it will not show the default768 """769 opt = click.Option(770 ("--cache",),771 is_flag=True,772 show_default=True,773 default=default,774 help="Enable the cache.",775 )776 ctx = click.Context(click.Command("test"))777 message = opt.get_help_record(ctx)[1]778 assert "[default: " not in message

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 779–796why, one step back
779
780781def test_show_default_string(runner):782 """When show_default is a string show that value as default."""783 opt = click.Option(["--limit"], show_default="unlimited")784 ctx = click.Context(click.Command("cli"))785 message = opt.get_help_record(ctx)[1]786 assert "[default: (unlimited)]" in message787788789def test_do_not_show_no_default(runner):790 """When show_default is True and no default is set do not show None."""791 opt = click.Option(["--limit"], show_default=True)792 ctx = click.Context(click.Command("cli"))793 message = opt.get_help_record(ctx)[1]794 assert "[default: None]" not in message795796

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

lines 797–804why, one step back
797def test_do_not_show_default_empty_multiple():
798 """When show_default is True and multiple=True is set, it should not799 print empty default value in --help output.800 """801 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)802 ctx = click.Context(click.Command("cli"))803 message = opt.get_help_record(ctx)[1]804 assert message == "values"

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

lines 805–826why, one step back
805
806807@pytest.mark.parametrize(808 ("ctx_value", "opt_value", "expect"),809 [810 (None, None, False),811 (None, False, False),812 (None, True, True),813 (False, None, False),814 (False, False, False),815 (False, True, True),816 (True, None, True),817 (True, False, False),818 (True, True, True),819 (False, "one", True),820 ],821)822def test_show_default_precedence(ctx_value, opt_value, expect):823 ctx = click.Context(click.Command("test"), show_default=ctx_value)824 opt = click.Option("-a", default=1, help="value", show_default=opt_value)825 help = opt.get_help_record(ctx)[1]826 assert ("default:" in help) is expect

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

lines 827–828why, one step back
827
828

Merge pull request #1792 from pallets/consistencyDavid Lordbefore adoption98e471f

lines 829–857why, one step back
829@pytest.mark.parametrize(
830 ("args", "expect"),831 [832 (None, (None, None, ())),833 (["--opt"], ("flag", None, ())),834 (["--opt", "-a", 42], ("flag", "42", ())),835 (["--opt", "test", "-a", 42], ("test", "42", ())),836 (["--opt=test", "-a", 42], ("test", "42", ())),837 (["-o"], ("flag", None, ())),838 (["-o", "-a", 42], ("flag", "42", ())),839 (["-o", "test", "-a", 42], ("test", "42", ())),840 (["-otest", "-a", 42], ("test", "42", ())),841 (["a", "b", "c"], (None, None, ("a", "b", "c"))),842 (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),843 (["--opt", "test"], ("test", None, ())),844 (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),845 (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),846 ],847)848def test_option_with_optional_value(runner, args, expect):849 @click.command()850 @click.option("-o", "--opt", is_flag=False, flag_value="flag")851 @click.option("-a")852 @click.argument("b", nargs=-1)853 def cli(opt, a, b):854 return opt, a, b855856 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)857 assert result.return_value == expect

Merge branch '8.0.x'David Lordbefore adoption0a81393

lines 858–880why, one step back
858
859860def test_multiple_option_with_optional_value(runner):861 cli = click.Command(862 "cli",863 params=[864 click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),865 click.Option(["-a"]),866 click.Argument(["b"], nargs=-1),867 ],868 callback=lambda **kwargs: kwargs,869 )870 result = runner.invoke(871 cli,872 ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],873 standalone_mode=False,874 catch_exceptions=False,875 )876 assert result.return_value == {877 "f": ("flag", "other", "flag"),878 "a": "1",879 "b": ("a", "b"),880 }

Merge branch '8.0.x'David Lordbefore adoption29df879

lines 881–887why, one step back
881
882883def test_type_from_flag_value():884 param = click.Option(["-a", "x"], default=True, flag_value=4)885 assert param.type is click.INT886 param = click.Option(["-b", "x"], flag_value=8)887 assert param.type is click.INT

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

lines 888–906why, one step back
888
889890@pytest.mark.parametrize(891 ("option", "expected"),892 [893 # Not boolean flags894 pytest.param(Option(["-a"], type=int), False, id="int option"),895 pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),896 pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),897 pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),898 pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),899 # Boolean flags900 pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),901 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),902 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),903 ],904)905def test_is_bool_flag_is_correctly_set(option, expected):906 assert option.is_bool_flag is expected

Merge branch '8.1.x'David Lordbefore adoption0aec116

lines 907–920why, one step back
907
908909@pytest.mark.parametrize(910 ("kwargs", "message"),911 [912 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),913 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),914 ],915)916def test_invalid_flag_combinations(runner, kwargs, message):917 with pytest.raises(TypeError) as e:918 click.Option(["-a"], **kwargs)919920 assert message in str(e.value)