Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

1,362 lines · 44.2 KiB · Python

Last changed by

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

History of this file

Take it

The walk stopped after 200 commits: lines older than 6ef3340 point at it.

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 1–35why, one step back
1import os
2import re34import pytest56import click7from click import Option8910def 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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

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):

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 211–249why, 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"248249

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 250–304why, one step back
250@pytest.mark.parametrize(
251 ("name", "value", "expected"),252 (253 # Lower-cased variations of value.254 ("SHOUT", "true", True),255 ("SHOUT", "false", False),256 # Title-cased variations of value.257 ("SHOUT", "True", True),258 ("SHOUT", "False", False),259 # Upper-cased variations of value.260 ("SHOUT", "TRUE", True),261 ("SHOUT", "FALSE", False),262 # Random-cased variations of value.263 ("SHOUT", "TruE", True),264 ("SHOUT", "truE", True),265 ("SHOUT", "FaLsE", False),266 ("SHOUT", "falsE", False),267 # Extra spaces around the value.268 ("SHOUT", "true ", True),269 ("SHOUT", " true", True),270 ("SHOUT", " true ", True),271 ("SHOUT", "false ", False),272 ("SHOUT", " false", False),273 ("SHOUT", " false ", False),274 # Integer variations.275 ("SHOUT", "1", True),276 ("SHOUT", "0", False),277 # Alternative states.278 ("SHOUT", "t", True),279 ("SHOUT", "f", False),280 ("SHOUT", "y", True),281 ("SHOUT", "n", False),282 ("SHOUT", "yes", True),283 ("SHOUT", "no", False),284 ("SHOUT", "on", True),285 ("SHOUT", "off", False),286 # Blank value variations.287 ("SHOUT", None, False),288 ("SHOUT", "", False),289 ("SHOUT", " ", False),290 ("SHOUT", " ", False),291 # Variable names are not stripped of spaces and so don't match the292 # flag, which then naturraly takes its default value.293 ("SHOUT ", "True", False),294 ("SHOUT ", "False", False),295 (" SHOUT ", "True", False),296 (" SHOUT ", "False", False),297 # Same for random and reverse environment variable names: they are not298 # recognized by the option.299 ("RANDOM", "True", False),300 ("NO_SHOUT", "True", False),301 ("NO_SHOUT", "False", False),302 ),303)304def test_boolean_envvar_normalization(runner, name, value, expected):

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 305–309why, one step back
305 @click.command()
306 @click.option("--shout/--no-shout", envvar="SHOUT")307 def cli(shout):308 click.echo(f"shout: {shout!r}")309

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 310why, one step back
310 result = runner.invoke(cli, [], env={name: value})

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

line 311why, one step back
311 assert result.exit_code == 0

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 312why, one step back
312 assert result.output == f"shout: {expected}\n"

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 313–314why, one step back
313
314

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 315–340why, one step back
315@pytest.mark.parametrize(
316 ("name", "value"),317 (318 ("SHOUT", "tr ue"),319 ("SHOUT", "10"),320 ("SHOUT", "01"),321 ("SHOUT", "00"),322 ("SHOUT", "11"),323 ("SHOUT", "randomstring"),324 ("SHOUT", "None"),325 ),326)327def test_boolean_envvar_bad_values(runner, name, value):328 @click.command()329 @click.option("--shout/--no-shout", envvar="SHOUT")330 def cli(shout):331 click.echo(f"shout: {shout!r}")332333 result = runner.invoke(cli, [], env={name: value})334 assert result.exit_code == 2335 assert (336 f"Invalid value for '--shout': {value!r} is not a valid boolean."337 in result.output338 )339340

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 341–444why, one step back
341def test_multiple_default_help(runner):
342 @click.command()343 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)344 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)345 def cmd(arg, arg2):346 pass347348 result = runner.invoke(cmd, ["--help"])349 assert not result.exception350 assert "foo, bar" in result.output351 assert "1, 2" in result.output352353354def test_show_default_default_map(runner):355 @click.command()356 @click.option("--arg", default="a", show_default=True)357 def cmd(arg):358 click.echo(arg)359360 result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})361362 assert not result.exception363 assert "[default: b]" in result.output364365366def test_multiple_default_type():367 opt = click.Option(["-a"], multiple=True, default=(1, 2))368 assert opt.nargs == 1369 assert opt.multiple370 assert opt.type is click.INT371 ctx = click.Context(click.Command("test"))372 assert opt.get_default(ctx) == (1, 2)373374375def test_multiple_default_composite_type():376 opt = click.Option(["-a"], multiple=True, default=[(1, "a")])377 assert opt.nargs == 2378 assert opt.multiple379 assert isinstance(opt.type, click.Tuple)380 assert opt.type.types == [click.INT, click.STRING]381 ctx = click.Context(click.Command("test"))382 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)383384385def test_parse_multiple_default_composite_type(runner):386 @click.command()387 @click.option("-a", multiple=True, default=("a", "b"))388 @click.option("-b", multiple=True, default=[(1, "a")])389 def cmd(a, b):390 click.echo(a)391 click.echo(b)392393 # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())394 # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"395 result = runner.invoke(cmd)396 assert result.output == "('a', 'b')\n((1, 'a'),)\n"397398399def test_dynamic_default_help_unset(runner):400 @click.command()401 @click.option(402 "--username",403 prompt=True,404 default=lambda: os.environ.get("USER", ""),405 show_default=True,406 )407 def cmd(username):408 print("Hello,", username)409410 result = runner.invoke(cmd, ["--help"])411 assert result.exit_code == 0412 assert "--username" in result.output413 assert "lambda" not in result.output414 assert "(dynamic)" in result.output415416417def test_dynamic_default_help_text(runner):418 @click.command()419 @click.option(420 "--username",421 prompt=True,422 default=lambda: os.environ.get("USER", ""),423 show_default="current user",424 )425 def cmd(username):426 print("Hello,", username)427428 result = runner.invoke(cmd, ["--help"])429 assert result.exit_code == 0430 assert "--username" in result.output431 assert "lambda" not in result.output432 assert "(current user)" in result.output433434435def test_dynamic_default_help_special_method(runner):436 class Value:437 def __call__(self):438 return 42439440 def __str__(self):441 return "special value"442443 opt = click.Option(["-a"], default=Value(), show_default=True)444 ctx = click.Context(click.Command("cli"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 446–460why, one step back
446 assert "special value" in opt.get_help_record(ctx)[1]
447448449@pytest.mark.parametrize(450 ("type", "expect"),451 [452 (click.IntRange(1, 32), "1<=x<=32"),453 (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),454 (click.IntRange(1), "x>=1"),455 (click.IntRange(max=32), "x<=32"),456 ],457)458def test_intrange_default_help_text(type, expect):459 option = click.Option(["--num"], type=type, show_default=True, default=2)460 context = click.Context(click.Command("test"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 462–469why, one step back
462 result = option.get_help_record(context)[1]
463 assert expect in result464465466def test_count_default_type_help():467 """A count option with the default type should not show >=0 in help."""468 option = click.Option(["--count"], count=True, help="some words")469 context = click.Context(click.Command("test"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 471–485why, one step back
471 result = option.get_help_record(context)[1]
472 assert result == "some words"473474475def test_file_type_help_default():476 """The default for a File type is a filename string. The string477 should be displayed in help, not an open file object.478479 Type casting is only applied to defaults in processing, not when480 getting the default value.481 """482 option = click.Option(483 ["--in"], type=click.File(), default=__file__, show_default=True484 )485 context = click.Context(click.Command("test"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 487–635why, one step back
487 result = option.get_help_record(context)[1]
488 assert __file__ in result489490491def test_toupper_envvar_prefix(runner):492 @click.command()493 @click.option("--arg")494 def cmd(arg):495 click.echo(arg)496497 result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})498 assert not result.exception499 assert result.output == "foo\n"500501502def test_nargs_envvar(runner):503 @click.command()504 @click.option("--arg", nargs=2)505 def cmd(arg):506 click.echo("|".join(arg))507508 result = runner.invoke(509 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}510 )511 assert not result.exception512 assert result.output == "foo|bar\n"513514 @click.command()515 @click.option("--arg", nargs=2, multiple=True)516 def cmd(arg):517 for item in arg:518 click.echo("|".join(item))519520 result = runner.invoke(521 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}522 )523 assert not result.exception524 assert result.output == "x|1\ny|2\n"525526527def test_show_envvar(runner):528 @click.command()529 @click.option("--arg1", envvar="ARG1", show_envvar=True)530 def cmd(arg):531 pass532533 result = runner.invoke(cmd, ["--help"])534 assert not result.exception535 assert "ARG1" in result.output536537538def test_show_envvar_auto_prefix(runner):539 @click.command()540 @click.option("--arg1", show_envvar=True)541 def cmd(arg):542 pass543544 result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")545 assert not result.exception546 assert "TEST_ARG1" in result.output547548549def test_show_envvar_auto_prefix_dash_in_command(runner):550 @click.group()551 def cli():552 pass553554 @cli.command()555 @click.option("--baz", show_envvar=True)556 def foo_bar(baz):557 pass558559 result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")560 assert not result.exception561 assert "TEST_FOO_BAR_BAZ" in result.output562563564def test_custom_validation(runner):565 def validate_pos_int(ctx, param, value):566 if value < 0:567 raise click.BadParameter("Value needs to be positive")568 return value569570 @click.command()571 @click.option("--foo", callback=validate_pos_int, default=1)572 def cmd(foo):573 click.echo(foo)574575 result = runner.invoke(cmd, ["--foo", "-1"])576 assert "Invalid value for '--foo': Value needs to be positive" in result.output577578 result = runner.invoke(cmd, ["--foo", "42"])579 assert result.output == "42\n"580581582def test_callback_validates_prompt(runner, monkeypatch):583 def validate(ctx, param, value):584 if value < 0:585 raise click.BadParameter("should be positive")586587 return value588589 @click.command()590 @click.option("-a", type=int, callback=validate, prompt=True)591 def cli(a):592 click.echo(a)593594 result = runner.invoke(cli, input="-12\n60\n")595 assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"596597598def test_winstyle_options(runner):599 @click.command()600 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")601 def cmd(debug):602 click.echo(debug)603604 result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])605 assert result.output == "True\n"606 result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])607 assert result.output == "False\n"608 result = runner.invoke(cmd, [], help_option_names=["/?"])609 assert result.output == "False\n"610 result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])611 assert "/debug; /no-debug Enables or disables debug mode." in result.output612 assert "/? Show this message and exit." in result.output613614615def test_legacy_options(runner):616 @click.command()617 @click.option("-whatever")618 def cmd(whatever):619 click.echo(whatever)620621 result = runner.invoke(cmd, ["-whatever", "42"])622 assert result.output == "42\n"623 result = runner.invoke(cmd, ["-whatever=23"])624 assert result.output == "23\n"625626627def test_missing_option_string_cast():628 ctx = click.Context(click.Command(""))629630 with pytest.raises(click.MissingParameter) as excinfo:631 click.Option(["-a"], required=True).process_value(ctx, None)632633 assert str(excinfo.value) == "Missing parameter: a"634635

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

lines 636–644why, one step back
636def test_missing_required_flag(runner):
637 cli = click.Command(638 "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]639 )640 result = runner.invoke(cli)641 assert result.exit_code == 2642 assert "Error: Missing option '--on'." in result.output643644

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 645–659why, one step back
645def test_missing_choice(runner):
646 @click.command()647 @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)648 def cmd(foo):649 click.echo(foo)650651 result = runner.invoke(cmd)652 assert result.exit_code == 2653 error, separator, choices = result.output.partition("Choose from")654 assert "Error: Missing option '--foo'. " in error655 assert "Choose from" in separator656 assert "foo" in choices657 assert "bar" in choices658659

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

lines 660–675why, one step back
660def test_missing_envvar(runner):
661 cli = click.Command(662 "cli", params=[click.Option(["--foo"], envvar="bar", required=True)]663 )664 result = runner.invoke(cli)665 assert result.exit_code == 2666 assert "Error: Missing option '--foo'." in result.output667 cli = click.Command(668 "cli",669 params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)],670 )671 result = runner.invoke(cli)672 assert result.exit_code == 2673 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output674675

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 676–806why, one step back
676def test_case_insensitive_choice(runner):
677 @click.command()678 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))679 def cmd(foo):680 click.echo(foo)681682 result = runner.invoke(cmd, ["--foo", "apple"])683 assert result.exit_code == 0684 assert result.output == "Apple\n"685686 result = runner.invoke(cmd, ["--foo", "oRANGe"])687 assert result.exit_code == 0688 assert result.output == "Orange\n"689690 result = runner.invoke(cmd, ["--foo", "Apple"])691 assert result.exit_code == 0692 assert result.output == "Apple\n"693694 @click.command()695 @click.option("--foo", type=click.Choice(["Orange", "Apple"]))696 def cmd2(foo):697 click.echo(foo)698699 result = runner.invoke(cmd2, ["--foo", "apple"])700 assert result.exit_code == 2701702 result = runner.invoke(cmd2, ["--foo", "oRANGe"])703 assert result.exit_code == 2704705 result = runner.invoke(cmd2, ["--foo", "Apple"])706 assert result.exit_code == 0707708709def test_case_insensitive_choice_returned_exactly(runner):710 @click.command()711 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))712 def cmd(foo):713 click.echo(foo)714715 result = runner.invoke(cmd, ["--foo", "apple"])716 assert result.exit_code == 0717 assert result.output == "Apple\n"718719720def test_option_help_preserve_paragraphs(runner):721 @click.command()722 @click.option(723 "-C",724 "--config",725 type=click.Path(),726 help="""Configuration file to use.727728 If not given, the environment variable CONFIG_FILE is consulted729 and used if set. If neither are given, a default configuration730 file is loaded.""",731 )732 def cmd(config):733 pass734735 result = runner.invoke(cmd, ["--help"])736 assert result.exit_code == 0737 i = " " * 21738 assert (739 " -C, --config PATH Configuration file to use.\n"740 f"{i}\n"741 f"{i}If not given, the environment variable CONFIG_FILE is\n"742 f"{i}consulted and used if set. If neither are given, a default\n"743 f"{i}configuration file is loaded."744 ) in result.output745746747def test_argument_custom_class(runner):748 class CustomArgument(click.Argument):749 def get_default(self, ctx, call=True):750 """a dumb override of a default value for testing"""751 return "I am a default"752753 @click.command()754 @click.argument("testarg", cls=CustomArgument, default="you wont see me")755 def cmd(testarg):756 click.echo(testarg)757758 result = runner.invoke(cmd)759 assert "I am a default" in result.output760 assert "you wont see me" not in result.output761762763def test_option_custom_class(runner):764 class CustomOption(click.Option):765 def get_help_record(self, ctx):766 """a dumb override of a help text for testing"""767 return ("--help", "I am a help text")768769 @click.command()770 @click.option("--testoption", cls=CustomOption, help="you wont see me")771 def cmd(testoption):772 click.echo(testoption)773774 result = runner.invoke(cmd, ["--help"])775 assert "I am a help text" in result.output776 assert "you wont see me" not in result.output777778779def test_option_custom_class_reusable(runner):780 """Ensure we can reuse a custom class option. See Issue #926"""781782 class CustomOption(click.Option):783 def get_help_record(self, ctx):784 """a dumb override of a help text for testing"""785 return ("--help", "I am a help text")786787 # Assign to a variable to re-use the decorator.788 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")789790 @click.command()791 @testoption792 def cmd1(testoption):793 click.echo(testoption)794795 @click.command()796 @testoption797 def cmd2(testoption):798 click.echo(testoption)799800 # Both of the commands should have the --help option now.801 for cmd in (cmd1, cmd2):802 result = runner.invoke(cmd, ["--help"])803 assert "I am a help text" in result.output804 assert "you wont see me" not in result.output805806

Move `--help` option defaults from its class to its decorator (#2840)Rowlando13before adoptionc9f7d9d

lines 807–845why, one step back
807@pytest.mark.parametrize("custom_class", (True, False))
808@pytest.mark.parametrize(809 ("name_specs", "expected"),810 (811 (812 ("-h", "--help"),813 " -h, --help Show this message and exit.\n",814 ),815 (816 ("-h",),817 " -h Show this message and exit.\n"818 " --help Show this message and exit.\n",819 ),820 (821 ("--help",),822 " --help Show this message and exit.\n",823 ),824 ),825)826def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):827 class CustomHelpOption(click.Option):828 pass829830 option_attrs = {}831 if custom_class:832 option_attrs["cls"] = CustomHelpOption833834 @click.command()835 @click.help_option(*name_specs, **option_attrs)836 def cmd():837 pass838839 for arg in name_specs:840 result = runner.invoke(cmd, [arg])841 assert not result.exception842 assert result.exit_code == 0843 assert expected in result.output844845

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 846–928why, one step back
846def test_bool_flag_with_type(runner):
847 @click.command()848 @click.option("--shout/--no-shout", default=False, type=bool)849 def cmd(shout):850 pass851852 result = runner.invoke(cmd)853 assert not result.exception854855856def test_aliases_for_flags(runner):857 @click.command()858 @click.option("--warnings/--no-warnings", " /-W", default=True)859 def cli(warnings):860 click.echo(warnings)861862 result = runner.invoke(cli, ["--warnings"])863 assert result.output == "True\n"864 result = runner.invoke(cli, ["--no-warnings"])865 assert result.output == "False\n"866 result = runner.invoke(cli, ["-W"])867 assert result.output == "False\n"868869 @click.command()870 @click.option("--warnings/--no-warnings", "-w", default=True)871 def cli_alt(warnings):872 click.echo(warnings)873874 result = runner.invoke(cli_alt, ["--warnings"])875 assert result.output == "True\n"876 result = runner.invoke(cli_alt, ["--no-warnings"])877 assert result.output == "False\n"878 result = runner.invoke(cli_alt, ["-w"])879 assert result.output == "True\n"880881882@pytest.mark.parametrize(883 "option_args,expected",884 [885 (["--aggressive", "--all", "-a"], "aggressive"),886 (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),887 (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),888 (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),889 (["-a", "-b", "-c"], "a"),890 (["-c", "-b", "-a"], "c"),891 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),892 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),893 (["--from", "-f", "_from"], "_from"),894 (["--return", "-r", "_ret"], "_ret"),895 ],896)897def test_option_names(runner, option_args, expected):898 @click.command()899 @click.option(*option_args, is_flag=True)900 def cmd(**kwargs):901 click.echo(str(kwargs[expected]))902903 assert cmd.params[0].name == expected904905 for form in option_args:906 if form.startswith("-"):907 result = runner.invoke(cmd, [form])908 assert result.output == "True\n"909910911def test_flag_duplicate_names(runner):912 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):913 click.Option(["--foo/--foo"], default=False)914915916@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])917def test_show_default_boolean_flag_name(runner, default, expect):918 """When a boolean flag has distinct True/False opts, it should show919 the default opt name instead of the default value. It should only920 show one name even if multiple are declared.921 """922 opt = click.Option(923 ("--cache/--no-cache", "--c/--nc"),924 default=default,925 show_default=True,926 help="Enable/Disable the cache.",927 )928 ctx = click.Context(click.Command("test"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 930–945why, one step back
930 message = opt.get_help_record(ctx)[1]
931 assert f"[default: {expect}]" in message932933934def test_show_true_default_boolean_flag_value(runner):935 """When a boolean flag only has one opt and its default is True,936 it will show the default value, not the opt name.937 """938 opt = click.Option(939 ("--cache",),940 is_flag=True,941 show_default=True,942 default=True,943 help="Enable the cache.",944 )945 ctx = click.Context(click.Command("test"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 947–963why, one step back
947 message = opt.get_help_record(ctx)[1]
948 assert "[default: True]" in message949950951@pytest.mark.parametrize("default", [False, None])952def test_hide_false_default_boolean_flag_value(runner, default):953 """When a boolean flag only has one opt and its default is False or954 None, it will not show the default955 """956 opt = click.Option(957 ("--cache",),958 is_flag=True,959 show_default=True,960 default=default,961 help="Enable the cache.",962 )963 ctx = click.Context(click.Command("test"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 965–972why, one step back
965 message = opt.get_help_record(ctx)[1]
966 assert "[default: " not in message967968969def test_show_default_string(runner):970 """When show_default is a string show that value as default."""971 opt = click.Option(["--limit"], show_default="unlimited")972 ctx = click.Context(click.Command("cli"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 974–977why, one step back
974 message = opt.get_help_record(ctx)[1]
975 assert "[default: (unlimited)]" in message976977

Merge branch '8.1.x'David Lordbefore adoption99015e1

lines 978–985why, one step back
978def test_show_default_with_empty_string(runner):
979 """When show_default is True and default is set to an empty string."""980 opt = click.Option(["--limit"], default="", show_default=True)981 ctx = click.Context(click.Command("cli"))982 message = opt.get_help_record(ctx)[1]983 assert '[default: ""]' in message984985

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

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

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 991–1000why, one step back
991 message = opt.get_help_record(ctx)[1]
992 assert "[default: None]" not in message993994995def test_do_not_show_default_empty_multiple():996 """When show_default is True and multiple=True is set, it should not997 print empty default value in --help output.998 """999 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)1000 ctx = click.Context(click.Command("cli"))

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

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

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

lines 1004–1006why, one step back
1004
10051006@pytest.mark.parametrize(

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

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

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

line 1008why, one step back
1008 [

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

lines 1009–1018why, one step back
1009 (None, None, {}, False),
1010 (None, False, {}, False),1011 (None, True, {"default": "1"}, True),1012 (False, None, {}, False),1013 (False, False, {}, False),1014 (False, True, {"default": "1"}, True),1015 (True, None, {"default": "1"}, True),1016 (True, False, {}, False),1017 (True, True, {"default": "1"}, True),1018 (False, "one", {"default": "(one)"}, True),

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

lines 1019–1020why, one step back
1019 ],
1020)

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

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

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

lines 1022–1023why, one step back
1022 ctx = click.Context(click.Command("test"), show_default=ctx_value)
1023 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 1024why, one step back
1024 assert opt.get_help_extra(ctx) == extra_value

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

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

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 1027–1090why, one step back
1027
10281029@pytest.mark.parametrize(1030 ("args", "expect"),1031 [1032 (None, (None, None, ())),1033 (["--opt"], ("flag", None, ())),1034 (["--opt", "-a", 42], ("flag", "42", ())),1035 (["--opt", "test", "-a", 42], ("test", "42", ())),1036 (["--opt=test", "-a", 42], ("test", "42", ())),1037 (["-o"], ("flag", None, ())),1038 (["-o", "-a", 42], ("flag", "42", ())),1039 (["-o", "test", "-a", 42], ("test", "42", ())),1040 (["-otest", "-a", 42], ("test", "42", ())),1041 (["a", "b", "c"], (None, None, ("a", "b", "c"))),1042 (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),1043 (["--opt", "test"], ("test", None, ())),1044 (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1045 (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),1046 ],1047)1048def test_option_with_optional_value(runner, args, expect):1049 @click.command()1050 @click.option("-o", "--opt", is_flag=False, flag_value="flag")1051 @click.option("-a")1052 @click.argument("b", nargs=-1)1053 def cli(opt, a, b):1054 return opt, a, b10551056 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)1057 assert result.return_value == expect105810591060def test_multiple_option_with_optional_value(runner):1061 cli = click.Command(1062 "cli",1063 params=[1064 click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),1065 click.Option(["-a"]),1066 click.Argument(["b"], nargs=-1),1067 ],1068 callback=lambda **kwargs: kwargs,1069 )1070 result = runner.invoke(1071 cli,1072 ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],1073 standalone_mode=False,1074 catch_exceptions=False,1075 )1076 assert result.return_value == {1077 "f": ("flag", "other", "flag"),1078 "a": "1",1079 "b": ("a", "b"),1080 }108110821083def test_type_from_flag_value():1084 param = click.Option(["-a", "x"], default=True, flag_value=4)1085 assert param.type is click.INT1086 param = click.Option(["-b", "x"], flag_value=8)1087 assert param.type is click.INT108810891090@pytest.mark.parametrize(

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 1091why, one step back
1091 ("opt_params", "pass_flag", "expected"),

Fix flag value set when is_flag=True and type is provided (#2930)David Lordbefore adoption884af5c

line 1092why, one step back
1092 [

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 1093–1175why, one step back
1093 # Effect of the presence/absence of flag depending on type
1094 ({"type": bool}, False, False),1095 ({"type": bool}, True, True),1096 ({"type": click.BOOL}, False, False),1097 ({"type": click.BOOL}, True, True),1098 ({"type": str}, False, "False"),1099 ({"type": str}, True, "True"),1100 # Effects of default value1101 ({"type": bool, "default": True}, False, True),1102 ({"type": bool, "default": True}, True, True),1103 ({"type": bool, "default": False}, False, False),1104 ({"type": bool, "default": False}, True, True),1105 ({"type": bool, "default": None}, False, False),1106 ({"type": bool, "default": None}, True, True),1107 ({"type": click.BOOL, "default": True}, False, True),1108 ({"type": click.BOOL, "default": True}, True, True),1109 ({"type": click.BOOL, "default": False}, False, False),1110 ({"type": click.BOOL, "default": False}, True, True),1111 ({"type": click.BOOL, "default": None}, False, False),1112 ({"type": click.BOOL, "default": None}, True, True),1113 ({"type": str, "default": True}, False, "True"),1114 ({"type": str, "default": True}, True, "True"),1115 ({"type": str, "default": False}, False, "False"),1116 ({"type": str, "default": False}, True, "True"),1117 ({"type": str, "default": "foo"}, False, "foo"),1118 ({"type": str, "default": "foo"}, True, "foo"),1119 ({"type": str, "default": None}, False, "False"),1120 ({"type": str, "default": None}, True, "True"),1121 # Effects of flag_value1122 ({"type": bool, "flag_value": True}, False, False),1123 ({"type": bool, "flag_value": True}, True, True),1124 ({"type": bool, "flag_value": False}, False, False),1125 ({"type": bool, "flag_value": False}, True, False),1126 ({"type": bool, "flag_value": None}, False, False),1127 ({"type": bool, "flag_value": None}, True, True),1128 ({"type": click.BOOL, "flag_value": True}, False, False),1129 ({"type": click.BOOL, "flag_value": True}, True, True),1130 ({"type": click.BOOL, "flag_value": False}, False, False),1131 ({"type": click.BOOL, "flag_value": False}, True, False),1132 ({"type": click.BOOL, "flag_value": None}, False, False),1133 ({"type": click.BOOL, "flag_value": None}, True, True),1134 ({"type": str, "flag_value": True}, False, "False"),1135 ({"type": str, "flag_value": True}, True, "True"),1136 ({"type": str, "flag_value": False}, False, "False"),1137 ({"type": str, "flag_value": False}, True, "False"),1138 ({"type": str, "flag_value": "foo"}, False, "False"),1139 ({"type": str, "flag_value": "foo"}, True, "foo"),1140 ({"type": str, "flag_value": None}, False, "False"),1141 ({"type": str, "flag_value": None}, True, "True"),1142 # Not passing --foo returns the default value as-is1143 ({"type": bool, "default": True, "flag_value": True}, False, True),1144 ({"type": bool, "default": True, "flag_value": False}, False, True),1145 ({"type": bool, "default": False, "flag_value": True}, False, False),1146 ({"type": bool, "default": False, "flag_value": False}, False, False),1147 ({"type": bool, "default": None, "flag_value": True}, False, False),1148 ({"type": bool, "default": None, "flag_value": False}, False, False),1149 ({"type": str, "default": True, "flag_value": True}, False, "True"),1150 ({"type": str, "default": True, "flag_value": False}, False, "True"),1151 ({"type": str, "default": False, "flag_value": True}, False, "False"),1152 ({"type": str, "default": False, "flag_value": False}, False, "False"),1153 ({"type": str, "default": "foo", "flag_value": True}, False, "foo"),1154 ({"type": str, "default": "foo", "flag_value": False}, False, "foo"),1155 ({"type": str, "default": "foo", "flag_value": "bar"}, False, "foo"),1156 ({"type": str, "default": "foo", "flag_value": None}, False, "foo"),1157 ({"type": str, "default": None, "flag_value": True}, False, "False"),1158 ({"type": str, "default": None, "flag_value": False}, False, "False"),1159 # Passing --foo returns the explicitly set flag_value1160 ({"type": bool, "default": True, "flag_value": True}, True, True),1161 ({"type": bool, "default": True, "flag_value": False}, True, False),1162 ({"type": bool, "default": False, "flag_value": True}, True, True),1163 ({"type": bool, "default": False, "flag_value": False}, True, False),1164 ({"type": bool, "default": None, "flag_value": True}, True, True),1165 ({"type": bool, "default": None, "flag_value": False}, True, False),1166 ({"type": str, "default": True, "flag_value": True}, True, "True"),1167 ({"type": str, "default": True, "flag_value": False}, True, "False"),1168 ({"type": str, "default": False, "flag_value": True}, True, "True"),1169 ({"type": str, "default": False, "flag_value": False}, True, "False"),1170 ({"type": str, "default": "foo", "flag_value": True}, True, "True"),1171 ({"type": str, "default": "foo", "flag_value": False}, True, "False"),1172 ({"type": str, "default": "foo", "flag_value": "bar"}, True, "bar"),1173 ({"type": str, "default": "foo", "flag_value": None}, True, "foo"),1174 ({"type": str, "default": None, "flag_value": True}, True, "True"),1175 ({"type": str, "default": None, "flag_value": False}, True, "False"),

Fix flag value set when is_flag=True and type is provided (#2930)David Lordbefore adoption884af5c

lines 1176–1177why, one step back
1176 ],
1177)

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 1178why, one step back
1178def test_flag_value_and_default(runner, opt_params, pass_flag, expected):

Fix flag value set when is_flag=True and type is provided (#2930)David Lordbefore adoption884af5c

line 1179why, one step back
1179 @click.command()

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 1180–1198why, one step back
1180 @click.option("--foo", is_flag=True, **opt_params)
1181 def cmd(foo):1182 click.echo(repr(foo))11831184 result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1185 assert result.output == f"{expected!r}\n"118611871188@pytest.mark.parametrize(1189 "opts",1190 [1191 {"type": bool, "default": "foo"},1192 {"type": bool, "flag_value": "foo"},1193 {"type": click.BOOL, "default": "foo"},1194 {"type": click.BOOL, "flag_value": "foo"},1195 ],1196)1197def test_invalid_flag_definition(runner, opts):1198 @click.command()

Fix flag value set when is_flag=True and type is provided (#2930)David Lordbefore adoption884af5c

lines 1199–1202why, one step back
1199 @click.option("--foo", is_flag=True, **opts)
1200 def cmd(foo):1201 click.echo(foo)1202

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 1203–1207why, one step back
1203 result = runner.invoke(cmd, ["--foo"])
1204 assert (1205 "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1206 in result.output1207 )

Fix flag value set when is_flag=True and type is provided (#2930)David Lordbefore adoption884af5c

lines 1208–1210why, one step back
1208
12091210@pytest.mark.parametrize(

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

lines 1211–1256why, one step back
1211 ("flag_value", "envvar_value", "expected"),
1212 [1213 # Envvar is set to false, so the flag default value is returned.1214 ("bar", "False", "False"),1215 # Same as above with alternative states and blank values.1216 ("bar", "0", "False"),1217 ("bar", "f", "False"),1218 ("bar", "", "False"),1219 # Envvar is set to true, so the flag_value is returned.1220 ("bar", "True", "bar"),1221 ("bar", "1", "bar"),1222 ("bar", "t", "bar"),1223 # So far we have the same cases as the test_flag_value_and_default1224 # test case. Now instead of passing a boolean-like value, let's use1225 # the flag_value as the envvar value.1226 ("bar", "bar", "bar"),1227 # flag_value is expected to be the exact same in the envvar for the flag to be1228 # activated.1229 ("bar", " bar ", "False"),1230 ("bar", "BAR", "False"),1231 ("bar", "random", "False"),1232 ("bar", "bar random", "False"),1233 ("bar", "random bar", "False"),1234 ("BAR", "BAR", "BAR"),1235 ("BAR", "bar", "False"),1236 (" bar ", " bar ", " bar "),1237 (" bar ", "bar", "False"),1238 (" bar ", "BAR", "False"),1239 ],1240)1241def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1242 """Ensure that flag_value is recognized by the envvar."""12431244 @click.command()1245 @click.option(1246 "--upper", type=str, is_flag=True, flag_value=flag_value, envvar="UPPER"1247 )1248 def cmd(upper):1249 click.echo(repr(upper))12501251 result = runner.invoke(cmd, env={"UPPER": envvar_value})1252 assert result.exit_code == 01253 assert result.output == f"{expected!r}\n"125412551256@pytest.mark.parametrize(

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

lines 1257–1270why, one step back
1257 ("option", "expected"),
1258 [1259 # Not boolean flags1260 pytest.param(Option(["-a"], type=int), False, id="int option"),1261 pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),1262 pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),1263 pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),1264 pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),1265 # Boolean flags1266 pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),1267 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1268 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1269 ],1270)

Fix reconciliation of envvar with `default`, `flag_value` and `type` parameters for flag options (#2956)Kevin Deldyckebefore adoption565f36d

line 1271why, one step back
1271def test_bool_flag_auto_detection(option, expected):

Merge pull request #1863 from bdista/test-args-paramDavid Lordbefore adoption6ef3340

line 1272why, one step back
1272 assert option.is_bool_flag is expected

Merge branch '8.1.x'David Lordbefore adoption0aec116

lines 1273–1286why, one step back
1273
12741275@pytest.mark.parametrize(1276 ("kwargs", "message"),1277 [1278 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),1279 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),1280 ],1281)1282def test_invalid_flag_combinations(runner, kwargs, message):1283 with pytest.raises(TypeError) as e:1284 click.Option(["-a"], **kwargs)12851286 assert message in str(e.value)

Fix flag value set when is_flag=True and type is provided (#2930)David Lordbefore adoption884af5c

lines 1287–1300why, one step back
1287
12881289def test_non_flag_with_non_negatable_default(runner):1290 class NonNegatable:1291 def __bool__(self):1292 raise ValueError("Cannot negate this object")12931294 @click.command()1295 @click.option("--foo", default=NonNegatable())1296 def cmd(foo):1297 pass12981299 result = runner.invoke(cmd)1300 assert result.exit_code == 0

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

lines 1301–1336why, one step back
1301
13021303@pytest.mark.parametrize(1304 ("choices", "metavars"),1305 [1306 pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1307 pytest.param([1, 2], "[INTEGER]", id="int choices"),1308 pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1309 pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1310 pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1311 ],1312)1313def test_usage_show_choices(runner, choices, metavars):1314 """When show_choices=False is set, the --help output1315 should print choice metavars instead of values.1316 """13171318 @click.command()1319 @click.option("-g", type=click.Choice(choices))1320 def cli_with_choices(g):1321 pass13221323 @click.command()1324 @click.option(1325 "-g",1326 type=click.Choice(choices),1327 show_choices=False,1328 )1329 def cli_without_choices(g):1330 pass13311332 result = runner.invoke(cli_with_choices, ["--help"])1333 assert f"[{'|'.join([str(i) for i in choices])}]" in result.output13341335 result = runner.invoke(cli_without_choices, ["--help"])1336 assert metavars in result.output

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

lines 1337–1362why, one step back
1337
13381339@pytest.mark.parametrize(1340 "opts_one,opts_two",1341 [1342 # No duplicate shortnames1343 (1344 ("-a", "--aardvark"),1345 ("-a", "--avocado"),1346 ),1347 # No duplicate long names1348 (1349 ("-a", "--aardvark"),1350 ("-b", "--aardvark"),1351 ),1352 ],1353)1354def test_duplicate_names_warning(runner, opts_one, opts_two):1355 @click.command()1356 @click.option(*opts_one)1357 @click.option(*opts_two)1358 def cli(one, two):1359 pass13601361 with pytest.warns(UserWarning):1362 runner.invoke(cli, [])