Skip to content
Myr

test_options.py

This file

Path

tests/test_options.py

816 lines · 24.7 KiB · Python

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 7b9a72f point at it.

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

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 #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 8–26why, 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):

Merge pull request #1355 from jtrakk/patch-1David Lordbefore adoption0ad4e79

lines 27–28why, one step back
27 with pytest.raises(TypeError, match="name was passed") as exc_info:
28 click.Option(["foo"])

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

line 29why, one step back
29

Merge pull request #1355 from jtrakk/patch-1David Lordbefore adoption0ad4e79

lines 30–33why, one step back
30 message = str(exc_info.value)
31 assert "name was passed (foo)" in message32 assert "declare an argument" in message33 assert "'--foo'" in message

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 34–36why, one step back
34
3536def 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 #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 38–68why, 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.exception

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

line 69why, one step back
69 assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 70–86why, one step back
70
71 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 #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 88–89why, one step back
88
89

Merge pull request #1455 from Na-Ne/masterDavid Lordbefore adoptiona141a2a

lines 90–105why, one step back
90@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.output104105

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 106–120why, one step back
106def 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 #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 156–202why, one step back
156def test_empty_envvar(runner):
157 @click.command()158 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")159 def cli(mypath):160 click.echo(f"mypath: {mypath}")161162 result = runner.invoke(cli, [], env={"MYPATH": ""})163 assert result.exit_code == 0164 assert result.output == "mypath: None\n"165166167def test_multiple_envvar(runner):168 @click.command()169 @click.option("--arg", multiple=True)170 def cmd(arg):171 click.echo("|".join(arg))172173 result = runner.invoke(174 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}175 )176 assert not result.exception177 assert result.output == "foo|bar|baz\n"178179 @click.command()180 @click.option("--arg", multiple=True, envvar="X")181 def cmd(arg):182 click.echo("|".join(arg))183184 result = runner.invoke(cmd, [], env={"X": "foo bar baz"})185 assert not result.exception186 assert result.output == "foo|bar|baz\n"187188 @click.command()189 @click.option("--arg", multiple=True, type=click.Path())190 def cmd(arg):191 click.echo("|".join(arg))192193 result = runner.invoke(194 cmd,195 [],196 auto_envvar_prefix="TEST",197 env={"TEST_ARG": f"foo{os.path.pathsep}bar"},198 )199 assert not result.exception200 assert result.output == "foo|bar\n"201202

Merge pull request #1606 from andy-maier/andy/fix-trailing-blanksDavid Lordbefore adoption25ee366

lines 203–213why, one step back
203def test_trailing_blanks_boolean_envvar(runner):
204 @click.command()205 @click.option("--shout/--no-shout", envvar="SHOUT")206 def cli(shout):207 click.echo(f"shout: {shout!r}")208209 result = runner.invoke(cli, [], env={"SHOUT": " true "})210 assert result.exit_code == 0211 assert result.output == "shout: True\n"212213

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 214–226why, one step back
214def test_multiple_default_help(runner):
215 @click.command()216 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)217 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)218 def cmd(arg, arg2):219 pass220221 result = runner.invoke(cmd, ["--help"])222 assert not result.exception223 assert "foo, bar" in result.output224 assert "1, 2" in result.output225226

Merge pull request #1549 from ewjoachim/default-map-show-default-1548David Lordbefore adoption7332f00

lines 227–238why, one step back
227def test_show_default_default_map(runner):
228 @click.command()229 @click.option("--arg", default="a", show_default=True)230 def cmd(arg):231 click.echo(arg)232233 result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})234235 assert not result.exception236 assert "[default: b]" in result.output237238

Merge pull request #1687 from pallets/multiple-tupleDavid Lordbefore adoptionc067af7

lines 239–245why, one step back
239def test_multiple_default_type():
240 opt = click.Option(["-a"], multiple=True, default=(1, 2))241 assert opt.nargs == 1242 assert opt.multiple243 assert opt.type is click.INT244 ctx = click.Context(click.Command("test"))245 assert opt.get_default(ctx) == (1, 2)

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 246–247why, one step back
246
247

Merge pull request #1687 from pallets/multiple-tupleDavid Lordbefore adoptionc067af7

lines 248–255why, one step back
248def test_multiple_default_composite_type():
249 opt = click.Option(["-a"], multiple=True, default=[(1, "a")])250 assert opt.nargs == 2251 assert opt.multiple252 assert isinstance(opt.type, click.Tuple)253 assert opt.type.types == [click.INT, click.STRING]254 ctx = click.Context(click.Command("test"))255 assert opt.get_default(ctx) == ((1, "a"),)

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 256–257why, one step back
256
257

Merge pull request #1687 from pallets/multiple-tupleDavid Lordbefore adoptionc067af7

lines 258–271why, one step back
258def test_parse_multiple_default_composite_type(runner):
259 @click.command()260 @click.option("-a", multiple=True, default=("a", "b"))261 @click.option("-b", multiple=True, default=[(1, "a")])262 def cmd(a, b):263 click.echo(a)264 click.echo(b)265266 # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())267 # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"268 result = runner.invoke(cmd)269 assert result.output == "('a', 'b')\n((1, 'a'),)\n"270271

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 272–307why, one step back
272def test_dynamic_default_help_unset(runner):
273 @click.command()274 @click.option(275 "--username",276 prompt=True,277 default=lambda: os.environ.get("USER", ""),278 show_default=True,279 )280 def cmd(username):281 print("Hello,", username)282283 result = runner.invoke(cmd, ["--help"])284 assert result.exit_code == 0285 assert "--username" in result.output286 assert "lambda" not in result.output287 assert "(dynamic)" in result.output288289290def test_dynamic_default_help_text(runner):291 @click.command()292 @click.option(293 "--username",294 prompt=True,295 default=lambda: os.environ.get("USER", ""),296 show_default="current user",297 )298 def cmd(username):299 print("Hello,", username)300301 result = runner.invoke(cmd, ["--help"])302 assert result.exit_code == 0303 assert "--username" in result.output304 assert "lambda" not in result.output305 assert "(current user)" in result.output306307

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

lines 308–317why, one step back
308@pytest.mark.parametrize(
309 ("type", "expect"),310 [311 (click.IntRange(1, 32), "1<=x<=32"),312 (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),313 (click.IntRange(1), "x>=1"),314 (click.IntRange(max=32), "x<=32"),315 ],316)317def test_intrange_default_help_text(runner, type, expect):

Merge pull request #1687 from pallets/multiple-tupleDavid Lordbefore adoptionc067af7

line 318why, one step back
318 option = click.Option(["--count"], type=type, show_default=True, default=2)

Merge pull request #1303 from robintully/issue_1110_open_intervalDavid Lordbefore adoptionca75bab

lines 319–321why, one step back
319 context = click.Context(click.Command("test"))
320 result = option.get_help_record(context)[1]321 assert expect in result

Merge pull request #1586 from IamCathal/coc-intrangepreviewDavid Lordbefore adoptione8de91d

lines 322–323why, one step back
322
323

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 324–414why, one step back
324def test_toupper_envvar_prefix(runner):
325 @click.command()326 @click.option("--arg")327 def cmd(arg):328 click.echo(arg)329330 result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})331 assert not result.exception332 assert result.output == "foo\n"333334335def test_nargs_envvar(runner):336 @click.command()337 @click.option("--arg", nargs=2)338 def cmd(arg):339 click.echo("|".join(arg))340341 result = runner.invoke(342 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}343 )344 assert not result.exception345 assert result.output == "foo|bar\n"346347 @click.command()348 @click.option("--arg", nargs=2, multiple=True)349 def cmd(arg):350 for item in arg:351 click.echo("|".join(item))352353 result = runner.invoke(354 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}355 )356 assert not result.exception357 assert result.output == "x|1\ny|2\n"358359360def test_show_envvar(runner):361 @click.command()362 @click.option("--arg1", envvar="ARG1", show_envvar=True)363 def cmd(arg):364 pass365366 result = runner.invoke(cmd, ["--help"])367 assert not result.exception368 assert "ARG1" in result.output369370371def test_show_envvar_auto_prefix(runner):372 @click.command()373 @click.option("--arg1", show_envvar=True)374 def cmd(arg):375 pass376377 result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")378 assert not result.exception379 assert "TEST_ARG1" in result.output380381382def test_show_envvar_auto_prefix_dash_in_command(runner):383 @click.group()384 def cli():385 pass386387 @cli.command()388 @click.option("--baz", show_envvar=True)389 def foo_bar(baz):390 pass391392 result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")393 assert not result.exception394 assert "TEST_FOO_BAR_BAZ" in result.output395396397def test_custom_validation(runner):398 def validate_pos_int(ctx, param, value):399 if value < 0:400 raise click.BadParameter("Value needs to be positive")401 return value402403 @click.command()404 @click.option("--foo", callback=validate_pos_int, default=1)405 def cmd(foo):406 click.echo(foo)407408 result = runner.invoke(cmd, ["--foo", "-1"])409 assert "Invalid value for '--foo': Value needs to be positive" in result.output410411 result = runner.invoke(cmd, ["--foo", "42"])412 assert result.output == "42\n"413414

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

lines 415–430why, one step back
415def test_callback_validates_prompt(runner, monkeypatch):
416 def validate(ctx, param, value):417 if value < 0:418 raise click.BadParameter("should be positive")419420 return value421422 @click.command()423 @click.option("-a", type=int, callback=validate, prompt=True)424 def cli(a):425 click.echo(a)426427 result = runner.invoke(cli, input="-12\n60\n")428 assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"429430

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 431–463why, one step back
431def test_winstyle_options(runner):
432 @click.command()433 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")434 def cmd(debug):435 click.echo(debug)436437 result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])438 assert result.output == "True\n"439 result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])440 assert result.output == "False\n"441 result = runner.invoke(cmd, [], help_option_names=["/?"])442 assert result.output == "False\n"443 result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])444 assert "/debug; /no-debug Enables or disables debug mode." in result.output445 assert "/? Show this message and exit." in result.output446447448def test_legacy_options(runner):449 @click.command()450 @click.option("-whatever")451 def cmd(whatever):452 click.echo(whatever)453454 result = runner.invoke(cmd, ["-whatever", "42"])455 assert result.output == "42\n"456 result = runner.invoke(cmd, ["-whatever=23"])457 assert result.output == "23\n"458459460def test_missing_option_string_cast():461 ctx = click.Context(click.Command(""))462463 with pytest.raises(click.MissingParameter) as excinfo:

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

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

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

line 465why, one step back
465

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

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

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 467–542why, one step back
467
468469def test_missing_choice(runner):470 @click.command()471 @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)472 def cmd(foo):473 click.echo(foo)474475 result = runner.invoke(cmd)476 assert result.exit_code == 2477 error, separator, choices = result.output.partition("Choose from")478 assert "Error: Missing option '--foo'. " in error479 assert "Choose from" in separator480 assert "foo" in choices481 assert "bar" in choices482483484def test_case_insensitive_choice(runner):485 @click.command()486 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))487 def cmd(foo):488 click.echo(foo)489490 result = runner.invoke(cmd, ["--foo", "apple"])491 assert result.exit_code == 0492 assert result.output == "Apple\n"493494 result = runner.invoke(cmd, ["--foo", "oRANGe"])495 assert result.exit_code == 0496 assert result.output == "Orange\n"497498 result = runner.invoke(cmd, ["--foo", "Apple"])499 assert result.exit_code == 0500 assert result.output == "Apple\n"501502 @click.command()503 @click.option("--foo", type=click.Choice(["Orange", "Apple"]))504 def cmd2(foo):505 click.echo(foo)506507 result = runner.invoke(cmd2, ["--foo", "apple"])508 assert result.exit_code == 2509510 result = runner.invoke(cmd2, ["--foo", "oRANGe"])511 assert result.exit_code == 2512513 result = runner.invoke(cmd2, ["--foo", "Apple"])514 assert result.exit_code == 0515516517def test_case_insensitive_choice_returned_exactly(runner):518 @click.command()519 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))520 def cmd(foo):521 click.echo(foo)522523 result = runner.invoke(cmd, ["--foo", "apple"])524 assert result.exit_code == 0525 assert result.output == "Apple\n"526527528def test_option_help_preserve_paragraphs(runner):529 @click.command()530 @click.option(531 "-C",532 "--config",533 type=click.Path(),534 help="""Configuration file to use.535536 If not given, the environment variable CONFIG_FILE is consulted537 and used if set. If neither are given, a default configuration538 file is loaded.""",539 )540 def cmd(config):541 pass542

Merge pull request #1712 from pallets/pre-commit-ci-update-configDavid Lordbefore adoptiona28048f

line 543why, one step back
543 result = runner.invoke(cmd, ["--help"])

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 544–556why, one step back
544 assert result.exit_code == 0
545 i = " " * 21546 assert (547 " -C, --config PATH Configuration file to use.\n"548 f"{i}\n"549 f"{i}If not given, the environment variable CONFIG_FILE is\n"550 f"{i}consulted and used if set. If neither are given, a default\n"551 f"{i}configuration file is loaded."552 ) in result.output553554555def test_argument_custom_class(runner):556 class CustomArgument(click.Argument):

Merge branch '8.0.x'David Lordbefore adoption29df879

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

Merge pull request #1575 from pallets/dependabot/pip/tox-3.15.2dependabot-preview[bot]before adoption7b9a72f

lines 558–678why, one step back
558 """a dumb override of a default value for testing"""
559 return "I am a default"560561 @click.command()562 @click.argument("testarg", cls=CustomArgument, default="you wont see me")563 def cmd(testarg):564 click.echo(testarg)565566 result = runner.invoke(cmd)567 assert "I am a default" in result.output568 assert "you wont see me" not in result.output569570571def test_option_custom_class(runner):572 class CustomOption(click.Option):573 def get_help_record(self, ctx):574 """a dumb override of a help text for testing"""575 return ("--help", "I am a help text")576577 @click.command()578 @click.option("--testoption", cls=CustomOption, help="you wont see me")579 def cmd(testoption):580 click.echo(testoption)581582 result = runner.invoke(cmd, ["--help"])583 assert "I am a help text" in result.output584 assert "you wont see me" not in result.output585586587def test_option_custom_class_reusable(runner):588 """Ensure we can reuse a custom class option. See Issue #926"""589590 class CustomOption(click.Option):591 def get_help_record(self, ctx):592 """a dumb override of a help text for testing"""593 return ("--help", "I am a help text")594595 # Assign to a variable to re-use the decorator.596 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")597598 @click.command()599 @testoption600 def cmd1(testoption):601 click.echo(testoption)602603 @click.command()604 @testoption605 def cmd2(testoption):606 click.echo(testoption)607608 # Both of the commands should have the --help option now.609 for cmd in (cmd1, cmd2):610611 result = runner.invoke(cmd, ["--help"])612 assert "I am a help text" in result.output613 assert "you wont see me" not in result.output614615616def test_bool_flag_with_type(runner):617 @click.command()618 @click.option("--shout/--no-shout", default=False, type=bool)619 def cmd(shout):620 pass621622 result = runner.invoke(cmd)623 assert not result.exception624625626def test_aliases_for_flags(runner):627 @click.command()628 @click.option("--warnings/--no-warnings", " /-W", default=True)629 def cli(warnings):630 click.echo(warnings)631632 result = runner.invoke(cli, ["--warnings"])633 assert result.output == "True\n"634 result = runner.invoke(cli, ["--no-warnings"])635 assert result.output == "False\n"636 result = runner.invoke(cli, ["-W"])637 assert result.output == "False\n"638639 @click.command()640 @click.option("--warnings/--no-warnings", "-w", default=True)641 def cli_alt(warnings):642 click.echo(warnings)643644 result = runner.invoke(cli_alt, ["--warnings"])645 assert result.output == "True\n"646 result = runner.invoke(cli_alt, ["--no-warnings"])647 assert result.output == "False\n"648 result = runner.invoke(cli_alt, ["-w"])649 assert result.output == "True\n"650651652@pytest.mark.parametrize(653 "option_args,expected",654 [655 (["--aggressive", "--all", "-a"], "aggressive"),656 (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),657 (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),658 (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),659 (["-a", "-b", "-c"], "a"),660 (["-c", "-b", "-a"], "c"),661 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),662 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),663 (["--from", "-f", "_from"], "_from"),664 (["--return", "-r", "_ret"], "_ret"),665 ],666)667def test_option_names(runner, option_args, expected):668 @click.command()669 @click.option(*option_args, is_flag=True)670 def cmd(**kwargs):671 click.echo(str(kwargs[expected]))672673 assert cmd.params[0].name == expected674675 for form in option_args:676 if form.startswith("-"):677 result = runner.invoke(cmd, [form])678 assert result.output == "True\n"

Merge pull request #1594 from MLH-Fellowship/duplicate-boolean-flagsDavid Lordbefore adoptiondfb842d

lines 679–683why, one step back
679
680681def test_flag_duplicate_names(runner):682 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):683 click.Option(["--foo/--foo"], default=False)

Merge pull request #1617 from MLH-Fellowship/issue1538David Lordbefore adoption66172ef

lines 684–702why, one step back
684
685686@pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])687def test_show_default_boolean_flag_name(runner, default, expect):688 """When a boolean flag has distinct True/False opts, it should show689 the default opt name instead of the default value. It should only690 show one name even if multiple are declared.691 """692 opt = click.Option(693 ("--cache/--no-cache", "--c/--nc"),694 default=default,695 show_default=True,696 help="Enable/Disable the cache.",697 )698 ctx = click.Context(click.Command("test"))699 message = opt.get_help_record(ctx)[1]700 assert f"[default: {expect}]" in message701702

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

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

Merge pull request #1617 from MLH-Fellowship/issue1538David Lordbefore adoption66172ef

lines 706–707why, one step back
706 """
707 opt = click.Option(

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

lines 708–712why, one step back
708 ("--cache",),
709 is_flag=True,710 show_default=True,711 default=True,712 help="Enable the cache.",

Merge pull request #1617 from MLH-Fellowship/issue1538David Lordbefore adoption66172ef

lines 713–715why, one step back
713 )
714 ctx = click.Context(click.Command("test"))715 message = opt.get_help_record(ctx)[1]

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

lines 716–733why, one step back
716 assert "[default: True]" in message
717718719@pytest.mark.parametrize("default", [False, None])720def test_hide_false_default_boolean_flag_value(runner, default):721 """When a boolean flag only has one opt and its default is False or722 None, it will not show the default723 """724 opt = click.Option(725 ("--cache",),726 is_flag=True,727 show_default=True,728 default=default,729 help="Enable the cache.",730 )731 ctx = click.Context(click.Command("test"))732 message = opt.get_help_record(ctx)[1]733 assert "[default: " not in message

Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348

lines 734–735why, one step back
734
735

Merge pull request #1755 from b3n4kh/show_defaults_string_valueDavid Lordbefore adoptionb28bc4c

lines 736–743why, one step back
736def test_show_default_string(runner):
737 """When show_default is a string show that value as default."""738 opt = click.Option(["--limit"], show_default="unlimited")739 ctx = click.Context(click.Command("cli"))740 message = opt.get_help_record(ctx)[1]741 assert "[default: (unlimited)]" in message742743

Merge pull request #1779 from b3n4kh/masterDavid Lordbefore adoption90a6c78

lines 744–751why, one step back
744def test_do_not_show_no_default(runner):
745 """When show_default is True and no default is set do not show None."""746 opt = click.Option(["--limit"], show_default=True)747 ctx = click.Context(click.Command("cli"))748 message = opt.get_help_record(ctx)[1]749 assert "[default: None]" not in message750751

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

lines 752–761why, one step back
752def test_do_not_show_default_empty_multiple():
753 """When show_default is True and multiple=True is set, it should not754 print empty default value in --help output.755 """756 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)757 ctx = click.Context(click.Command("cli"))758 message = opt.get_help_record(ctx)[1]759 assert message == "values"760761

Merge pull request #1618 from MLH-Fellowship/prompt-requiredDavid Lordbefore adoption8efb348

lines 762–790why, one step back
762@pytest.mark.parametrize(
763 ("args", "expect"),764 [765 (None, (None, None, ())),766 (["--opt"], ("flag", None, ())),767 (["--opt", "-a", 42], ("flag", "42", ())),768 (["--opt", "test", "-a", 42], ("test", "42", ())),769 (["--opt=test", "-a", 42], ("test", "42", ())),770 (["-o"], ("flag", None, ())),771 (["-o", "-a", 42], ("flag", "42", ())),772 (["-o", "test", "-a", 42], ("test", "42", ())),773 (["-otest", "-a", 42], ("test", "42", ())),774 (["a", "b", "c"], (None, None, ("a", "b", "c"))),775 (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),776 (["--opt", "test"], ("test", None, ())),777 (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),778 (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),779 ],780)781def test_option_with_optional_value(runner, args, expect):782 @click.command()783 @click.option("-o", "--opt", is_flag=False, flag_value="flag")784 @click.option("-a")785 @click.argument("b", nargs=-1)786 def cli(opt, a, b):787 return opt, a, b788789 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)790 assert result.return_value == expect

Merge branch '8.0.x'David Lordbefore adoption29df879

lines 791–797why, one step back
791
792793def test_type_from_flag_value():794 param = click.Option(["-a", "x"], default=True, flag_value=4)795 assert param.type is click.INT796 param = click.Option(["-b", "x"], flag_value=8)797 assert param.type is click.INT

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

lines 798–816why, one step back
798
799800@pytest.mark.parametrize(801 ("option", "expected"),802 [803 # Not boolean flags804 pytest.param(Option(["-a"], type=int), False, id="int option"),805 pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),806 pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),807 pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),808 pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),809 # Boolean flags810 pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),811 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),812 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),813 ],814)815def test_is_bool_flag_is_correctly_set(option, expected):816 assert option.is_bool_flag is expected