Skip to content
Myr

test_termui.py

This file

Path

tests/test_termui.py

712 lines · 25.4 KiB · Python

Last changed by

Fix test_edit to work with BSD sed (#3129)Rowlando13before adoptiona92c573

History of this file

Take it

The walk stopped after 200 commits: lines older than 5e75fe7 point at it.

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

line 1why, one step back
1import platform

Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c

line 2why, one step back
2import tempfile

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 3–8why, one step back
3import time
45import pytest67import click._termui_impl8from click._compat import WIN

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 9–10why, one step back
9from click.exceptions import BadParameter
10from click.exceptions import MissingParameter

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 11–76why, one step back
11
1213class FakeClock:14 def __init__(self):15 self.now = time.time()1617 def advance_time(self, seconds=1):18 self.now += seconds1920 def time(self):21 return self.now222324def _create_progress(length=10, **kwargs):25 progress = click.progressbar(tuple(range(length)))26 for key, value in kwargs.items():27 setattr(progress, key, value)28 return progress293031def test_progressbar_strip_regression(runner, monkeypatch):32 label = " padded line"3334 @click.command()35 def cli():36 with _create_progress(label=label) as progress:37 for _ in progress:38 pass3940 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)41 assert (42 label43 in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output44 )454647def test_progressbar_length_hint(runner, monkeypatch):48 class Hinted:49 def __init__(self, n):50 self.items = list(range(n))5152 def __length_hint__(self):53 return len(self.items)5455 def __iter__(self):56 return self5758 def __next__(self):59 if self.items:60 return self.items.pop()61 else:62 raise StopIteration6364 next = __next__6566 @click.command()67 def cli():68 with click.progressbar(Hinted(10), label="test") as progress:69 for _ in progress:70 pass7172 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)73 result = runner.invoke(cli, [])74 assert result.exception is None7576

Add functionality to hide the progress bar #2609 (#2727)bhuffman-usgsbefore adoptionfcd8503

line 77why, one step back
77def test_progressbar_no_tty(runner, monkeypatch):

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 78–85why, one step back
78 @click.command()
79 def cli():80 with _create_progress(label="working") as progress:81 for _ in progress:82 pass8384 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)85 assert runner.invoke(cli, []).output == "working\n"

Add functionality to hide the progress bar #2609 (#2727)bhuffman-usgsbefore adoptionfcd8503

lines 86–96why, one step back
86
8788def test_progressbar_hidden_manual(runner, monkeypatch):89 @click.command()90 def cli():91 with _create_progress(label="see nothing", hidden=True) as progress:92 for _ in progress:93 pass9495 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)96 assert runner.invoke(cli, []).output == ""

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 97–191why, one step back
97
9899@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])100def test_progressbar_time_per_iteration(runner, avg, expected):101 with _create_progress(2, avg=avg) as progress:102 assert progress.time_per_iteration == expected103104105@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])106def test_progressbar_eta(runner, finished, expected):107 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:108 assert progress.eta == expected109110111@pytest.mark.parametrize(112 "eta, expected",113 [114 (0, "00:00:00"),115 (30, "00:00:30"),116 (90, "00:01:30"),117 (900, "00:15:00"),118 (9000, "02:30:00"),119 (99999999999, "1157407d 09:46:39"),120 (None, ""),121 ],122)123def test_progressbar_format_eta(runner, eta, expected):124 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:125 assert progress.format_eta() == expected126127128@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])129def test_progressbar_format_pos(runner, pos, length):130 with _create_progress(length, pos=pos) as progress:131 result = progress.format_pos()132 assert result == f"{pos}/{length}"133134135@pytest.mark.parametrize(136 "length, finished, pos, avg, expected",137 [138 (8, False, 7, 0, "#######-"),139 (0, True, 8, 0, "########"),140 ],141)142def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):143 with _create_progress(144 length, width=8, pos=pos, finished=finished, avg=[avg]145 ) as progress:146 assert progress.format_bar() == expected147148149@pytest.mark.parametrize(150 "length, show_percent, show_pos, pos, expected",151 [152 (0, True, True, 0, " [--------] 0/0 0%"),153 (0, False, True, 0, " [--------] 0/0"),154 (0, False, False, 0, " [--------]"),155 (0, False, False, 0, " [--------]"),156 (8, True, True, 8, " [########] 8/8 100%"),157 ],158)159def test_progressbar_format_progress_line(160 runner, length, show_percent, show_pos, pos, expected161):162 with _create_progress(163 length,164 width=8,165 show_percent=show_percent,166 pos=pos,167 show_pos=show_pos,168 ) as progress:169 assert progress.format_progress_line() == expected170171172@pytest.mark.parametrize("test_item", ["test", None])173def test_progressbar_format_progress_line_with_show_func(runner, test_item):174 def item_show_func(item):175 return item176177 with _create_progress(178 item_show_func=item_show_func, current_item=test_item179 ) as progress:180 if test_item:181 assert progress.format_progress_line().endswith(test_item)182 else:183 assert progress.format_progress_line().endswith(progress.format_pct())184185186def test_progressbar_init_exceptions(runner):187 with pytest.raises(TypeError, match="iterable or length is required"):188 click.progressbar()189190191def test_progressbar_iter_outside_with_exceptions(runner):

Merge branch '8.1.x'David Lordbefore adoption7271763

lines 192–193why, one step back
192 progress = click.progressbar(length=2)
193

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 194–246why, one step back
194 with pytest.raises(RuntimeError, match="with block"):
195 iter(progress)196197198def test_progressbar_is_iterator(runner, monkeypatch):199 @click.command()200 def cli():201 with click.progressbar(range(10), label="test") as progress:202 while True:203 try:204 next(progress)205 except StopIteration:206 break207208 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)209 result = runner.invoke(cli, [])210 assert result.exception is None211212213def test_choices_list_in_prompt(runner, monkeypatch):214 @click.command()215 @click.option(216 "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True217 )218 def cli_with_choices(g):219 pass220221 @click.command()222 @click.option(223 "-g",224 type=click.Choice(["none", "day", "week", "month"]),225 prompt=True,226 show_choices=False,227 )228 def cli_without_choices(g):229 pass230231 result = runner.invoke(cli_with_choices, [], input="none")232 assert "(none, day, week, month)" in result.output233234 result = runner.invoke(cli_without_choices, [], input="none")235 assert "(none, day, week, month)" not in result.output236237238@pytest.mark.parametrize(239 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]240)241def test_file_prompt_default_format(runner, file_kwargs):242 @click.command()243 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))244 def cli(f):245 click.echo(f.name)246

Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0

line 247why, one step back
247 result = runner.invoke(cli, input="\n")

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 248–262why, one step back
248 assert result.output == f"file [{__file__}]: \n{__file__}\n"
249250251def test_secho(runner):252 with runner.isolation() as outstreams:253 click.secho(None, nl=False)254 bytes = outstreams[0].getvalue()255 assert bytes == b""256257258@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")259@pytest.mark.parametrize(260 ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]261)262def test_secho_non_text(runner, value, expect):

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

line 263why, one step back
263 with runner.isolation() as (out, _, _):

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 264–383why, one step back
264 click.secho(value, nl=False, color=True, bg="magenta")
265 result = out.getvalue()266 assert result == expect267268269def test_progressbar_yields_all_items(runner):270 with click.progressbar(range(3)) as progress:271 assert len(list(progress)) == 3272273274def test_progressbar_update(runner, monkeypatch):275 fake_clock = FakeClock()276277 @click.command()278 def cli():279 with click.progressbar(range(4)) as progress:280 for _ in progress:281 fake_clock.advance_time()282 print("")283284 monkeypatch.setattr(time, "time", fake_clock.time)285 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)286 output = runner.invoke(cli, []).output287288 lines = [line for line in output.split("\n") if "[" in line]289290 assert " 0%" in lines[0]291 assert " 25% 00:00:03" in lines[1]292 assert " 50% 00:00:02" in lines[2]293 assert " 75% 00:00:01" in lines[3]294 assert "100% " in lines[4]295296297def test_progressbar_item_show_func(runner, monkeypatch):298 """item_show_func should show the current item being yielded."""299300 @click.command()301 def cli():302 with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress:303 for item in progress:304 click.echo(f" item {item}")305306 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)307 lines = runner.invoke(cli).output.splitlines()308309 for i, line in enumerate(x for x in lines if "item" in x):310 assert f"{i} item {i}" in line311312313def test_progressbar_update_with_item_show_func(runner, monkeypatch):314 @click.command()315 def cli():316 with click.progressbar(317 length=6, item_show_func=lambda x: f"Custom {x}"318 ) as progress:319 while not progress.finished:320 progress.update(2, progress.pos)321 click.echo()322323 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)324 output = runner.invoke(cli, []).output325326 lines = [line for line in output.split("\n") if "[" in line]327328 assert "Custom 0" in lines[0]329 assert "Custom 2" in lines[1]330 assert "Custom 4" in lines[2]331332333def test_progress_bar_update_min_steps(runner):334 bar = _create_progress(update_min_steps=5)335 bar.update(3)336 assert bar._completed_intervals == 3337 assert bar.pos == 0338 bar.update(2)339 assert bar._completed_intervals == 0340 assert bar.pos == 5341342343@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))344@pytest.mark.parametrize("echo", [True, False])345@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")346def test_getchar_windows(runner, monkeypatch, key_char, echo):347 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)348 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)349 monkeypatch.setattr(click.termui, "_getchar", None)350 assert click.getchar(echo) == key_char351352353@pytest.mark.parametrize(354 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]355)356@pytest.mark.skipif(357 not WIN, reason="Tests special character inputs using the msvcrt module."358)359def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):360 ordered_inputs = [key_char, special_key_char]361 monkeypatch.setattr(362 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()363 )364 monkeypatch.setattr(click.termui, "_getchar", None)365 assert click.getchar() == f"{special_key_char}{key_char}"366367368@pytest.mark.parametrize(369 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]370)371@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")372def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):373 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)374 monkeypatch.setattr(click.termui, "_getchar", None)375376 with pytest.raises(exc):377 click.getchar()378379380@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")381def test_fast_edit(runner):382 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")383 assert result == "aTest\nbTest\n"

Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c

lines 384–388why, one step back
384
385386@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")387def test_edit(runner):388 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:

Fix test_edit to work with BSD sed (#3129)Rowlando13before adoptiona92c573

line 389why, one step back
389 named_tempfile.write("a\nb\n")

Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c

lines 390–396why, one step back
390 named_tempfile.flush()
391392 result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")393 assert result is None394395 # We need ot reopen the file as it becomes unreadable after the edit.396 with open(named_tempfile.name) as reopened_file:

Fix test_edit to work with BSD sed (#3129)Rowlando13before adoptiona92c573

lines 397–404why, one step back
397 # POSIX says that when sed writes a pattern space to output then it
398 # is immediately followed by a newline and so the expected result399 # should contain the newline. However, some sed implementations400 # (e.g. GNU sed) does not terminate the last line in the output401 # with the newline in a case the input data missed newline at the402 # end of last line. Hence the input data (see above) should be403 # terminated by newline too.404 assert reopened_file.read() == "aTest\nbTest\n"

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 405–462why, one step back
405
406407@pytest.mark.parametrize(408 ("prompt_required", "required", "args", "expect"),409 [410 (True, False, None, "prompt"),411 (True, False, ["-v"], "Option '-v' requires an argument."),412 (False, True, None, "prompt"),413 (False, True, ["-v"], "prompt"),414 ],415)416def test_prompt_required_with_required(runner, prompt_required, required, args, expect):417 @click.command()418 @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)419 def cli(v):420 click.echo(str(v))421422 result = runner.invoke(cli, args, input="prompt")423 assert expect in result.output424425426@pytest.mark.parametrize(427 ("args", "expect"),428 [429 # Flag not passed, don't prompt.430 pytest.param(None, None, id="no flag"),431 # Flag and value passed, don't prompt.432 pytest.param(["-v", "value"], "value", id="short sep value"),433 pytest.param(["--value", "value"], "value", id="long sep value"),434 pytest.param(["-vvalue"], "value", id="short join value"),435 pytest.param(["--value=value"], "value", id="long join value"),436 # Flag without value passed, prompt.437 pytest.param(["-v"], "prompt", id="short no value"),438 pytest.param(["--value"], "prompt", id="long no value"),439 # Don't use next option flag as value.440 pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),441 ],442)443def test_prompt_required_false(runner, args, expect):444 @click.command()445 @click.option("-v", "--value", prompt=True, prompt_required=False)446 @click.option("-o")447 def cli(value, o):448 if o is not None:449 return value, o450451 return value452453 result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)454 assert result.exception is None455 assert result.return_value == expect456457458@pytest.mark.parametrize(459 ("prompt", "input", "default", "expect"),460 [461 (True, "password\npassword", None, "password"),462 ("Confirm Password", "password\npassword\n", None, "password"),

Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0

line 463why, one step back
463 (True, "\n\n", "", ""),

Merge branch '8.1.x'David Lordbefore adoption5e75fe7

lines 464–484why, one step back
464 (False, None, None, None),
465 ],466)467def test_confirmation_prompt(runner, prompt, input, default, expect):468 @click.command()469 @click.option(470 "--password",471 prompt=prompt,472 hide_input=True,473 default=default,474 confirmation_prompt=prompt,475 )476 def cli(password):477 return password478479 result = runner.invoke(cli, input=input, standalone_mode=False)480 assert result.exception is None481 assert result.return_value == expect482483 if prompt == "Confirm Password":484 assert "Confirm Password: " in result.output

Hide default value when show_default is False (#2509)Patrick Hayesbefore adoptiona6e0d29

lines 485–496why, one step back
485
486487def test_false_show_default_cause_no_default_display_in_prompt(runner):488 @click.command()489 @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")490 def cmd(arg1):491 pass492493 # Confirm that the default value is not included in the output when `show_default`494 # is False495 result = runner.invoke(cmd, input="my-input", standalone_mode=False)496 assert "my-default-value" not in result.output

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 497–712why, one step back
497
498499REPEAT = object()500"""Sentinel value to indicate that the prompt is expected to be repeated.501502I.e. the value provided by the user is not satisfactory and need to be re-prompted.503"""504505INVALID = object()506"""Sentinel value to indicate that the prompt is expected to be invalid.507508On invalid input, Click will output an error message and re-prompt the user.509"""510511BOOLEAN_FLAG_PROMPT_CASES = [512 ###513 ### Test cases with prompt=True explicitly enabled for the flag.514 ###515 # Prompt is allowed and the flag has no default, so it prompts.516 ({"prompt": True}, [], "[y/N]", "y", True),517 ({"prompt": True}, [], "[y/N]", "n", False),518 # Empty input default to False.519 ({"prompt": True}, [], "[y/N]", "", False),520 # Changing the default to True, makes the prompt change to [Y/n].521 ({"prompt": True, "default": True}, [], "[Y/n]", "", True),522 ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),523 ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),524 # False is the default's default, so it prompts with [y/N].525 ({"prompt": True, "default": False}, [], "[y/N]", "", False),526 ({"prompt": True, "default": False}, [], "[y/N]", "y", True),527 ({"prompt": True, "default": False}, [], "[y/N]", "n", False),528 # Defaulting to None, prompts with [y/n], which makes the user explicitly choose529 # between True or False.530 ({"prompt": True, "default": None}, [], "[y/n]", "y", True),531 ({"prompt": True, "default": None}, [], "[y/n]", "n", False),532 # Random string default is treated as a truthy value, so it prompts with [Y/n].533 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),534 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),535 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),536 ###537 ### Test cases with required=True explicitly enabled for the flag.538 ###539 # A required flag just raises an error unless a default is set.540 ({"required": True}, [], None, None, MissingParameter),541 ({"required": True, "default": True}, [], None, None, True),542 ({"required": True, "default": False}, [], None, None, False),543 ({"required": True, "default": None}, [], None, None, None),544 ({"required": True, "default": "on"}, [], None, None, True),545 ({"required": True, "default": "off"}, [], None, None, False),546 ({"required": True, "default": "foo"}, [], None, None, BadParameter),547 ###548 ### Explicitly passing the flag to the CLI bypass any prompt, whatever the549 ### configuration of the flag.550 ###551 # Flag allowing a prompt.552 ({"prompt": True}, ["--flag"], None, None, True),553 ({"prompt": True}, ["--no-flag"], None, None, False),554 ({"prompt": True, "default": None}, ["--flag"], None, None, True),555 ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),556 ({"prompt": True, "default": True}, ["--flag"], None, None, True),557 ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),558 ({"prompt": True, "default": False}, ["--flag"], None, None, True),559 ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),560 ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),561 ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),562 # Required flag.563 ({"required": True}, ["--flag"], None, None, True),564 ({"required": True}, ["--no-flag"], None, None, False),565 ({"required": True, "default": None}, ["--flag"], None, None, True),566 ({"required": True, "default": None}, ["--no-flag"], None, None, False),567 ({"required": True, "default": True}, ["--flag"], None, None, True),568 ({"required": True, "default": True}, ["--no-flag"], None, None, False),569 ({"required": True, "default": False}, ["--flag"], None, None, True),570 ({"required": True, "default": False}, ["--no-flag"], None, None, False),571 ({"required": True, "default": "foo"}, ["--flag"], None, None, True),572 ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),573]574575FLAG_VALUE_PROMPT_CASES = [576 ###577 ### Test cases with prompt=True explicitly enabled for the flag.578 ###579 # Prompt is allowed and the flag has no default, so it prompts.580 # But the flag_value is not set, so it defaults to a string.581 ({"prompt": True}, [], "", "", REPEAT),582 ({"prompt": True}, [], "", "y", "y"),583 ({"prompt": True}, [], "", "n", "n"),584 ({"prompt": True}, [], "", "foo", "foo"),585 # This time we provide a boolean flag_value, which makes the flag behave like a586 # boolean flag, and use the appropriate variation of [y/n].587 ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),588 ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),589 ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),590 ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),591 ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),592 ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),593 # Other flag values changes the auto-detection of the flag type.594 ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),595 ({"prompt": True, "flag_value": None}, [], "", "y", "y"),596 ({"prompt": True, "flag_value": None}, [], "", "n", "n"),597 ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),598 ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),599 ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),600 ###601 ### Test cases with a flag_value and a default.602 ###603 # default=True604 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),605 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),606 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),607 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),608 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),609 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),610 # default=False611 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),612 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),613 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),614 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),615 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),616 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),617 # default=None618 (619 {"prompt": True, "default": None, "flag_value": True},620 [],621 "[y/n]",622 "",623 INVALID,624 ),625 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),626 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),627 (628 {"prompt": True, "default": None, "flag_value": False},629 [],630 "[y/n]",631 "",632 INVALID,633 ),634 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),635 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),636 # If the flag_value is None, the flag behave like a string flag, whatever the637 # default is.638 ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),639 ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),640 ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),641 (642 {"prompt": True, "default": False, "flag_value": None},643 [],644 "[False]",645 "",646 "False",647 ),648 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),649 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),650 ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),651 ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),652 ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),653]654655656@pytest.mark.parametrize(657 ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),658 # Boolean flag prompt cases.659 [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]660 # Non-boolean flag prompt cases.661 + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],662)663def test_flag_value_prompt(664 runner, opt_decls, opt_params, args, prompt, input, expected665):666 """Check how flag value are prompted and handled by all combinations of667 ``prompt``, ``default``, and ``flag_value`` parameters.668669 Covers concerns raised in issue https://github.com/pallets/click/issues/1992.670 """671672 @click.command()673 @click.option(opt_decls, **opt_params)674 def cli(flag):675 click.echo(repr(flag))676677 invoke_options = {"standalone_mode": False}678 if input is not None:679 assert isinstance(input, str)680 invoke_options["input"] = f"{input}\n"681682 result = runner.invoke(cli, args, **invoke_options)683684 if expected in (MissingParameter, BadParameter):685 assert isinstance(result.exception, expected)686 assert not result.output687 assert result.exit_code == 1688689 else:690 expected_output = ""691 if prompt is not None:692 # Build the expected prompt.693 assert isinstance(prompt, str)694 expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "695696 # Add the user input to the expected output.697 assert isinstance(input, str)698 expected_output += f"{expected_prompt}{input}\n"699700 if expected is INVALID:701 expected_output += "Error: invalid input\n"702703 # The prompt is expected to be repeated.704 if expected in (REPEAT, INVALID):705 expected_output += expected_prompt706707 if expected not in (REPEAT, INVALID):708 expected_output += f"{expected!r}\n"709710 assert result.output == expected_output711 assert not result.stderr712 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1