test_termui.py
This file
Path
tests/test_termui.py
1,612 lines · 54.6 KiB · Python
Last changed by
Strip ANSI from `confirm()` and `prompt()` (#3653)Rowlando13before adoptionfe3ad76
History of this fileTake it
The walk stopped after 200 commits: lines older than ab21233 point at it.
`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
line 1why, one step back1import contextlibMerge `stable` into `main` after `CHANGES` rST to Markdown conversion (#3563)Kevin Deldyckebefore adoption8a1b1a3
line 2why, one step back2import gc`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
line 3why, one step back3import ioRewrite second half of options docs (#2848)Rowlando13before adoptionab21233
line 4why, one step back4import platformPath normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 5why, one step back5import shlex`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
lines 6–7why, one step back6import shutil7import sysRewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 8–9why, one step back8import tempfile9import timeDocument and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
line 10why, one step back10from unittest.mock import patchRewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 11–13why, one step back1112import pytest13`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
line 14why, one step back14import clickRewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 15–16why, one step back15import click._termui_impl16from click._compat import WINDocument and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
line 17why, one step back17from click._termui_impl import EditorShow default string in prompt (#3328)Rowlando13before adoption76552ff
line 18why, one step back18from click._utils import UNSETMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 19–20why, one step back19from click.exceptions import BadParameter20from click.exceptions import MissingParameterRewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 21–256why, one step back212223class FakeClock:24 def __init__(self):25 self.now = time.time()2627 def advance_time(self, seconds=1):28 self.now += seconds2930 def time(self):31 return self.now323334def _create_progress(length=10, **kwargs):35 progress = click.progressbar(tuple(range(length)))36 for key, value in kwargs.items():37 setattr(progress, key, value)38 return progress394041def test_progressbar_strip_regression(runner, monkeypatch):42 label = " padded line"4344 @click.command()45 def cli():46 with _create_progress(label=label) as progress:47 for _ in progress:48 pass4950 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)51 assert (52 label53 in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output54 )555657def test_progressbar_length_hint(runner, monkeypatch):58 class Hinted:59 def __init__(self, n):60 self.items = list(range(n))6162 def __length_hint__(self):63 return len(self.items)6465 def __iter__(self):66 return self6768 def __next__(self):69 if self.items:70 return self.items.pop()71 else:72 raise StopIteration7374 next = __next__7576 @click.command()77 def cli():78 with click.progressbar(Hinted(10), label="test") as progress:79 for _ in progress:80 pass8182 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)83 result = runner.invoke(cli, [])84 assert result.exception is None858687def test_progressbar_no_tty(runner, monkeypatch):88 @click.command()89 def cli():90 with _create_progress(label="working") as progress:91 for _ in progress:92 pass9394 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)95 assert runner.invoke(cli, []).output == "working\n"969798def test_progressbar_hidden_manual(runner, monkeypatch):99 @click.command()100 def cli():101 with _create_progress(label="see nothing", hidden=True) as progress:102 for _ in progress:103 pass104105 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)106 assert runner.invoke(cli, []).output == ""107108109@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])110def test_progressbar_time_per_iteration(runner, avg, expected):111 with _create_progress(2, avg=avg) as progress:112 assert progress.time_per_iteration == expected113114115@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])116def test_progressbar_eta(runner, finished, expected):117 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:118 assert progress.eta == expected119120121@pytest.mark.parametrize(122 "eta, expected",123 [124 (0, "00:00:00"),125 (30, "00:00:30"),126 (90, "00:01:30"),127 (900, "00:15:00"),128 (9000, "02:30:00"),129 (99999999999, "1157407d 09:46:39"),130 (None, ""),131 ],132)133def test_progressbar_format_eta(runner, eta, expected):134 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:135 assert progress.format_eta() == expected136137138@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])139def test_progressbar_format_pos(runner, pos, length):140 with _create_progress(length, pos=pos) as progress:141 result = progress.format_pos()142 assert result == f"{pos}/{length}"143144145@pytest.mark.parametrize(146 "length, finished, pos, avg, expected",147 [148 (8, False, 7, 0, "#######-"),149 (0, True, 8, 0, "########"),150 ],151)152def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):153 with _create_progress(154 length, width=8, pos=pos, finished=finished, avg=[avg]155 ) as progress:156 assert progress.format_bar() == expected157158159@pytest.mark.parametrize(160 "length, show_percent, show_pos, pos, expected",161 [162 (0, True, True, 0, " [--------] 0/0 0%"),163 (0, False, True, 0, " [--------] 0/0"),164 (0, False, False, 0, " [--------]"),165 (0, False, False, 0, " [--------]"),166 (8, True, True, 8, " [########] 8/8 100%"),167 ],168)169def test_progressbar_format_progress_line(170 runner, length, show_percent, show_pos, pos, expected171):172 with _create_progress(173 length,174 width=8,175 show_percent=show_percent,176 pos=pos,177 show_pos=show_pos,178 ) as progress:179 assert progress.format_progress_line() == expected180181182@pytest.mark.parametrize("test_item", ["test", None])183def test_progressbar_format_progress_line_with_show_func(runner, test_item):184 def item_show_func(item):185 return item186187 with _create_progress(188 item_show_func=item_show_func, current_item=test_item189 ) as progress:190 if test_item:191 assert progress.format_progress_line().endswith(test_item)192 else:193 assert progress.format_progress_line().endswith(progress.format_pct())194195196def test_progressbar_init_exceptions(runner):197 with pytest.raises(TypeError, match="iterable or length is required"):198 click.progressbar()199200201def test_progressbar_iter_outside_with_exceptions(runner):202 progress = click.progressbar(length=2)203204 with pytest.raises(RuntimeError, match="with block"):205 iter(progress)206207208def test_progressbar_is_iterator(runner, monkeypatch):209 @click.command()210 def cli():211 with click.progressbar(range(10), label="test") as progress:212 while True:213 try:214 next(progress)215 except StopIteration:216 break217218 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)219 result = runner.invoke(cli, [])220 assert result.exception is None221222223def test_choices_list_in_prompt(runner, monkeypatch):224 @click.command()225 @click.option(226 "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True227 )228 def cli_with_choices(g):229 pass230231 @click.command()232 @click.option(233 "-g",234 type=click.Choice(["none", "day", "week", "month"]),235 prompt=True,236 show_choices=False,237 )238 def cli_without_choices(g):239 pass240241 result = runner.invoke(cli_with_choices, [], input="none")242 assert "(none, day, week, month)" in result.output243244 result = runner.invoke(cli_without_choices, [], input="none")245 assert "(none, day, week, month)" not in result.output246247248@pytest.mark.parametrize(249 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]250)251def test_file_prompt_default_format(runner, file_kwargs):252 @click.command()253 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))254 def cli(f):255 click.echo(f.name)256Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0
line 257why, one step back257 result = runner.invoke(cli, input="\n")Rewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 258–398why, one step back258 assert result.output == f"file [{__file__}]: \n{__file__}\n"259260261def test_secho(runner):262 with runner.isolation() as outstreams:263 click.secho(None, nl=False)264 bytes = outstreams[0].getvalue()265 assert bytes == b""266267268@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")269@pytest.mark.parametrize(270 ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]271)272def test_secho_non_text(runner, value, expect):273 with runner.isolation() as (out, _, _):274 click.secho(value, nl=False, color=True, bg="magenta")275 result = out.getvalue()276 assert result == expect277278279def test_progressbar_yields_all_items(runner):280 with click.progressbar(range(3)) as progress:281 assert len(list(progress)) == 3282283284def test_progressbar_update(runner, monkeypatch):285 fake_clock = FakeClock()286287 @click.command()288 def cli():289 with click.progressbar(range(4)) as progress:290 for _ in progress:291 fake_clock.advance_time()292 print("")293294 monkeypatch.setattr(time, "time", fake_clock.time)295 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)296 output = runner.invoke(cli, []).output297298 lines = [line for line in output.split("\n") if "[" in line]299300 assert " 0%" in lines[0]301 assert " 25% 00:00:03" in lines[1]302 assert " 50% 00:00:02" in lines[2]303 assert " 75% 00:00:01" in lines[3]304 assert "100% " in lines[4]305306307def test_progressbar_item_show_func(runner, monkeypatch):308 """item_show_func should show the current item being yielded."""309310 @click.command()311 def cli():312 with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress:313 for item in progress:314 click.echo(f" item {item}")315316 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)317 lines = runner.invoke(cli).output.splitlines()318319 for i, line in enumerate(x for x in lines if "item" in x):320 assert f"{i} item {i}" in line321322323def test_progressbar_update_with_item_show_func(runner, monkeypatch):324 @click.command()325 def cli():326 with click.progressbar(327 length=6, item_show_func=lambda x: f"Custom {x}"328 ) as progress:329 while not progress.finished:330 progress.update(2, progress.pos)331 click.echo()332333 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)334 output = runner.invoke(cli, []).output335336 lines = [line for line in output.split("\n") if "[" in line]337338 assert "Custom 0" in lines[0]339 assert "Custom 2" in lines[1]340 assert "Custom 4" in lines[2]341342343def test_progress_bar_update_min_steps(runner):344 bar = _create_progress(update_min_steps=5)345 bar.update(3)346 assert bar._completed_intervals == 3347 assert bar.pos == 0348 bar.update(2)349 assert bar._completed_intervals == 0350 assert bar.pos == 5351352353@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))354@pytest.mark.parametrize("echo", [True, False])355@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")356def test_getchar_windows(runner, monkeypatch, key_char, echo):357 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)358 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)359 monkeypatch.setattr(click.termui, "_getchar", None)360 assert click.getchar(echo) == key_char361362363@pytest.mark.parametrize(364 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]365)366@pytest.mark.skipif(367 not WIN, reason="Tests special character inputs using the msvcrt module."368)369def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):370 ordered_inputs = [key_char, special_key_char]371 monkeypatch.setattr(372 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()373 )374 monkeypatch.setattr(click.termui, "_getchar", None)375 assert click.getchar() == f"{special_key_char}{key_char}"376377378@pytest.mark.parametrize(379 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]380)381@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")382def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):383 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)384 monkeypatch.setattr(click.termui, "_getchar", None)385386 with pytest.raises(exc):387 click.getchar()388389390@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")391def test_fast_edit(runner):392 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")393 assert result == "aTest\nbTest\n"394395396@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")397def test_edit(runner):398 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:Fix test_edit to work with BSD sed (#3129)Rowlando13before adoptiona92c573
line 399why, one step back399 named_tempfile.write("a\nb\n")Rewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 400–404why, one step back400 named_tempfile.flush()401402 result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")403 assert result is None404add codespell pre-commit hook (#3373)David Lordbefore adoption8bd8b4a
line 405why, one step back405 # We need to reopen the file as it becomes unreadable after the edit.Rewrite second half of options docs (#2848)Rowlando13before adoptionab21233
line 406why, one step back406 with open(named_tempfile.name) as reopened_file:Fix test_edit to work with BSD sed (#3129)Rowlando13before adoptiona92c573
lines 407–414why, one step back407 # POSIX says that when sed writes a pattern space to output then it408 # is immediately followed by a newline and so the expected result409 # should contain the newline. However, some sed implementations410 # (e.g. GNU sed) does not terminate the last line in the output411 # with the newline in a case the input data missed newline at the412 # end of last line. Hence the input data (see above) should be413 # terminated by newline too.414 assert reopened_file.read() == "aTest\nbTest\n"Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 415–436why, one step back415416417@pytest.mark.parametrize(418 ("editor_cmd", "filenames", "expected_args"),419 [420 pytest.param(421 "myeditor --wait --flag",422 ["file1.txt", "file2.txt"],423 ["myeditor", "--wait", "--flag", "file1.txt", "file2.txt"],424 id="editor with args",425 ),426 pytest.param(427 "vi",428 ['file"; rm -rf / ; echo "'],429 ["vi", 'file"; rm -rf / ; echo "'],430 id="shell metacharacters in filename",431 ),432 # Issue #1026: editor path with spaces must be quoted.433 pytest.param(434 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"',435 ["f.txt"],436 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 437why, one step back437 id="quoted windows path with spaces",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 438–443why, one step back438 ),439 # PR #1477: pager/editor command with flags, like ``less -FRSX``.440 pytest.param(441 "less -FRSX",442 ["f.txt"],443 ["less", "-FRSX", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 444why, one step back444 id="command with flags",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 445–450why, one step back445 ),446 # Issue #1026: quoted command with ``--wait`` flag.447 pytest.param(448 '"my command" --option value arg',449 ["f.txt"],450 ["my command", "--option", "value", "arg", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 451why, one step back451 id="quoted command with args",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 452–464why, one step back452 ),453 # PR #1477: unquoted unix path.454 pytest.param(455 "/usr/bin/vim",456 ["f.txt"],457 ["/usr/bin/vim", "f.txt"],458 id="unix absolute path",459 ),460 # Issue #1026: macOS path with escaped space.461 pytest.param(462 "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl",463 ["f.txt"],464 ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 465why, one step back465 id="escaped space in unix path",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
line 466why, one step back466 ),Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
lines 467–508why, one step back467 pytest.param(468 " vim ",469 ["f.txt"],470 ["vim", "f.txt"],471 id="leading and trailing whitespace",472 ),473 pytest.param(474 "vim\tf.txt",475 [],476 ["vim", "f.txt"],477 id="tab-separated tokens",478 ),479 pytest.param(480 "'/Applications/My Editor.app/Contents/MacOS/editor'",481 ["f.txt"],482 ["/Applications/My Editor.app/Contents/MacOS/editor", "f.txt"],483 id="single-quoted path with spaces",484 ),485 pytest.param(486 '"my editor" --wait --new-window',487 ["file 1.txt", "file 2.txt"],488 ["my editor", "--wait", "--new-window", "file 1.txt", "file 2.txt"],489 id="quoted editor with multiple flags and filenames with spaces",490 ),491 pytest.param(492 "vim -u NONE -N",493 ["f.txt"],494 ["vim", "-u", "NONE", "-N", "f.txt"],495 id="multiple short flags",496 ),497 pytest.param(498 "editor",499 ['file"name.txt'],500 ["editor", 'file"name.txt'],501 id="filename with double quote",502 ),503 pytest.param(504 "editor",505 ["file'name.txt"],506 ["editor", "file'name.txt"],507 id="filename with single quote",508 ),Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 509–570why, one step back509 ],510)511def test_editor_path_normalization(editor_cmd, filenames, expected_args):512 with patch("subprocess.Popen") as mock_popen:513 mock_popen.return_value.wait.return_value = 0514 Editor(editor=editor_cmd).edit_files(filenames)515516 mock_popen.assert_called_once()517 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]518 assert args == expected_args519 assert mock_popen.call_args[1].get("shell") is None520521522@pytest.mark.skipif(not WIN, reason="Windows-specific editor paths")523@pytest.mark.parametrize(524 ("editor_cmd", "expected_cmd"),525 [526 pytest.param(527 "notepad",528 ["notepad"],529 id="plain notepad",530 ),531 pytest.param(532 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe" --wait',533 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "--wait"],534 id="quoted path with flag",535 ),536 ],537)538def test_editor_windows_path_normalization(editor_cmd, expected_cmd):539 """Windows-specific tests: verify ``Popen`` receives unquoted paths that540 ``subprocess.list2cmdline`` can re-quote for ``CreateProcess``."""541 with patch("subprocess.Popen") as mock_popen:542 mock_popen.return_value.wait.return_value = 0543 Editor(editor=editor_cmd).edit_files(["f.txt"])544545 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]546 assert args == expected_cmd + ["f.txt"]547 assert mock_popen.call_args[1].get("shell") is None548549550def test_editor_env_passed_through():551 with patch("subprocess.Popen") as mock_popen:552 mock_popen.return_value.wait.return_value = 0553 Editor(editor="vi", env={"MY_VAR": "1"}).edit_files(["f.txt"])554555 env = mock_popen.call_args[1].get("env")556 assert env is not None557 assert env["MY_VAR"] == "1"558559560def test_editor_failure_exception():561 with patch("subprocess.Popen") as mock_popen:562 mock_popen.return_value.wait.return_value = 1563 with pytest.raises(click.ClickException, match="Editing failed"):564 Editor(editor="vi").edit_files(["f.txt"])565566567def test_editor_nonexistent_exception():568 with patch("subprocess.Popen", side_effect=OSError("not found")):569 with pytest.raises(click.ClickException, match="not found"):570 Editor(editor="nonexistent").edit_files(["f.txt"])Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
lines 571–626why, one step back571572573@pytest.mark.parametrize(574 ("pager_env", "expected_parts"),575 [576 # Simple commands.577 pytest.param("cat", ["cat"], id="simple command"),578 pytest.param("less", ["less"], id="less"),579 pytest.param("less -FRSX", ["less", "-FRSX"], id="command with flags"),580 # Whitespace handling.581 pytest.param("", [], id="empty string"),582 pytest.param(" ", [], id="whitespace only"),583 pytest.param(" less ", ["less"], id="leading and trailing spaces"),584 pytest.param("less\t-R", ["less", "-R"], id="tab as separator"),585 # Quoted Windows paths: quotes are stripped in POSIX mode (the586 # default), preserving backslashes inside quoted tokens (issue #1026).587 pytest.param(588 '"C:\\Program Files\\Git\\usr\\bin\\less.exe"',589 ["C:\\Program Files\\Git\\usr\\bin\\less.exe"],590 id="quoted windows path with spaces",591 ),592 pytest.param(593 '"C:\\Program Files\\Git\\usr\\bin\\less.exe" -R',594 ["C:\\Program Files\\Git\\usr\\bin\\less.exe", "-R"],595 id="quoted windows path with flag",596 ),597 # Single-quoted path.598 pytest.param(599 "'/usr/local/bin/my pager'",600 ["/usr/local/bin/my pager"],601 id="single-quoted path with spaces",602 ),603 # Unix paths.604 pytest.param("/usr/bin/less", ["/usr/bin/less"], id="unix absolute path"),605 pytest.param(606 "/usr/bin/my\\ pager",607 ["/usr/bin/my pager"],608 id="escaped space in unix path",609 ),610 # PR #1477: POSIX mode (the default) eats unquoted backslashes.611 # On Windows, users must quote paths that contain backslashes.612 pytest.param(613 "C:\\path\\to\\exe /test other\\path",614 ["C:pathtoexe", "/test", "otherpath"],615 id="unquoted backslashes eaten in POSIX mode",616 ),617 ],618)619def test_pager_shlex_split(pager_env, expected_parts):620 """Verify shlex.split produces the expected argv for PAGER values.621622 Tests the splitting logic used by :func:`click._termui_impl.pager` to623 turn the ``PAGER`` environment variable into an ``argv`` list. See624 issue #1026, PR #1477, PR #1543, PR #2775.625 """626 assert shlex.split(pager_env) == expected_parts`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
lines 627–729why, one step back627628629def _get_real_pager_command() -> str:630 """Return a real pager binary path used to exercise the pipe pager branch.631632 ..warning::633 Unix-only for now: ``more.com`` on Windows is interactive and goes634 through ``_tempfilepager`` rather than ``_pipepager``.635 """636 pager_path = shutil.which("cat")637 assert pager_path is not None, "cat not available"638 return pager_path639640641def _run_get_pager_file_with_real_pager(monkeypatch, capfd, writer, color=False):642 """Run through the pipe pager backend selected by ``PAGER``."""643 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)644 monkeypatch.setitem(645 click._termui_impl.os.environ, "PAGER", _get_real_pager_command()646 )647648 with click.get_pager_file(color=color) as pager:649 writer(pager)650651 # The real pager writes to the process stdout; stderr should stay quiet.652 out, err = capfd.readouterr()653 assert err == ""654 return out655656657def _write_pager_from_multiple_sites(pager):658 pager.write("prefix\n")659 click.echo("middle", file=pager)660 pager.write("suffix\n")661662663@pytest.mark.skipif(664 WIN,665 reason="Exercises the pipe pager path; Windows uses _tempfilepager.",666)667@pytest.mark.parametrize(668 ("writer", "color", "expected"),669 [670 pytest.param(671 _write_pager_from_multiple_sites,672 False,673 "prefix\nmiddle\nsuffix\n",674 id="multiple write sites",675 ),676 pytest.param(677 lambda pager: pager.write("hello\n"), False, "hello\n", id="plain text"678 ),679 pytest.param(680 lambda pager: pager.write(click.style("hello", fg="red") + "\n"),681 False,682 "hello\n",683 id="strip ansi",684 ),685 pytest.param(686 lambda pager: pager.write(click.style("hello", fg="red") + "\n"),687 True,688 click.style("hello", fg="red") + "\n",689 id="preserve ansi",690 ),691 pytest.param(lambda pager: pager.write(""), False, "", id="empty string"),692 ],693)694def test_get_pager_file_with_real_pager_binary_stream(695 monkeypatch, capfd, writer, color, expected696):697 """A real pager should exercise the BinaryIO branch."""698 output = _run_get_pager_file_with_real_pager(699 monkeypatch, capfd, writer, color=color700 )701702 assert output == expected703704705@pytest.mark.skipif(706 WIN,707 reason="Exercises the pipe pager path; Windows uses _tempfilepager.",708)709@pytest.mark.parametrize(710 ("color", "expected"),711 [712 pytest.param(False, "hello\n", id="strip ansi"),713 pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),714 ],715)716def test_echo_via_pager_real_pager_handles_ansi(monkeypatch, capfd, color, expected):717 """``echo_via_pager`` should honor ``color`` like ``get_pager_file``."""718 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)719 monkeypatch.setitem(720 click._termui_impl.os.environ, "PAGER", _get_real_pager_command()721 )722723 click.echo_via_pager(click.style("hello", fg="red"), color=color)724725 out, err = capfd.readouterr()726 assert err == ""727 assert out == expected728729Merge `stable` into `main` after `CHANGES` rST to Markdown conversion (#3563)Kevin Deldyckebefore adoption8a1b1a3
lines 730–767why, one step back730def test_echo_via_pager_streams_each_write(monkeypatch):731 """Each write is flushed so a slow generator streams to the pager732 incrementally instead of buffering until the end (issues #3242, #2542).733 """734 calls = []735736 class RecordingStream(io.StringIO):737 def __init__(self):738 super().__init__()739 self.color = None740741 def write(self, s):742 calls.append("write")743 return super().write(s)744745 def flush(self):746 calls.append("flush")747748 stream = RecordingStream()749 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)750 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)751752 def generate():753 yield "a\n"754 yield "b\n"755 yield "c\n"756757 click.echo_via_pager(generate())758759 # No two writes are adjacent: every chunk is flushed before the next one,760 # so the pager sees output as it is produced.761 assert not any(762 calls[i] == "write" and calls[i + 1] == "write" for i in range(len(calls) - 1)763 )764 assert calls.count("write") == 4 # three chunks plus the trailing newline765 assert stream.getvalue() == "a\nb\nc\n\n"766767`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
lines 768–807why, one step back768def test_get_pager_file_pager_missing_binary_falls_back(monkeypatch, tmp_path):769 """``PAGER`` pointing to a nonexistent binary falls back to the text stdout."""770 pager_out = tmp_path / "pager_out.txt"771772 monkeypatch.setitem(773 click._termui_impl.os.environ,774 "PAGER",775 "click-tests-nonexistent-pager-9b3f2",776 )777 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)778779 with pager_out.open("w", encoding="utf-8") as text_stream:780 monkeypatch.setattr(781 click._termui_impl, "_default_text_stdout", lambda: text_stream782 )783784 with click.get_pager_file() as pager:785 pager.write("hello\n")786787 assert pager_out.read_text(encoding="utf-8") == "hello\n"788789790def test_get_pager_file_pager_unset_falls_back_when_no_default(monkeypatch, tmp_path):791 """``PAGER`` unset still works when the platform default isn't installed."""792 pager_out = tmp_path / "pager_out.txt"793794 monkeypatch.delitem(click._termui_impl.os.environ, "PAGER", raising=False)795 monkeypatch.delitem(click._termui_impl.os.environ, "TERM", raising=False)796 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)797 monkeypatch.setattr(shutil, "which", lambda _name: None)798799 with pager_out.open("w", encoding="utf-8") as text_stream:800 monkeypatch.setattr(801 click._termui_impl, "_default_text_stdout", lambda: text_stream802 )803804 with click.get_pager_file() as pager:805 pager.write("hello\n")806807 assert pager_out.read_text(encoding="utf-8") == "hello\n"Merge `stable` into `main` after `CHANGES` rST to Markdown conversion (#3563)Kevin Deldyckebefore adoption8a1b1a3
lines 808–862why, one step back808809810def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch):811 """A missing ``PAGER`` must not close the borrowed stdout (issue #3449).812813 The ``8.4.0`` regression was only fixed for the no-tty ``_nullpager`` path;814 the ``_pipepager``/``_tempfilepager`` fallbacks (reached in a tty when815 ``PAGER`` resolves to nothing) used to close the borrowed stream too.816 """817 buffer = io.BytesIO()818 stream = io.TextIOWrapper(buffer, encoding="utf-8")819820 monkeypatch.setitem(821 click._termui_impl.os.environ,822 "PAGER",823 "click-tests-nonexistent-pager-9b3f2",824 )825 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)826 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)827828 with click.get_pager_file() as pager:829 pager.write("hello\n")830831 # Drop the wrapper reference and force finalization: the old bug closed the832 # borrowed buffer when the TextIOWrapper built by get_pager_file was833 # garbage-collected.834 del pager835 gc.collect()836837 assert not buffer.closed838 assert not stream.closed839 assert buffer.getvalue().replace(b"\r\n", b"\n") == b"hello\n"840841842def test_echo_via_pager_tty_pager_missing(runner, monkeypatch):843 """``echo_via_pager`` through the tty fallback keeps ``CliRunner`` working.844845 Regression for issue #3449 via the pager fallback: a tty with ``PAGER``846 pointing at a missing binary used to close the runner's stdout, breaking847 ``CliRunner.invoke``.848 """849 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)850 monkeypatch.setitem(851 click._termui_impl.os.environ,852 "PAGER",853 "click-tests-nonexistent-pager-9b3f2",854 )855856 @click.command()857 def cli():858 click.echo_via_pager("Hello, Click!")859860 result = runner.invoke(cli)861 assert not result.exception862 assert result.output == "Hello, Click!\n"`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
lines 863–894why, one step back863864865@pytest.mark.parametrize(866 ("color", "expected"),867 [868 pytest.param(False, "hello\n", id="strip ansi"),869 pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),870 ],871)872def test_get_pager_file_nullpager_wraps_textio_stream(873 monkeypatch, tmp_path, color, expected874):875 """When paging falls back to a real TextIO stream, ``.buffer`` is wrapped."""876 pager_out = tmp_path / "pager_out.txt"877878 with pager_out.open("w", encoding="utf-8") as text_stream:879 monkeypatch.setattr(880 click._termui_impl, "_default_text_stdout", lambda: text_stream881 )882 monkeypatch.setattr(883 click._termui_impl, "isatty", lambda stream: stream is not sys.stdin884 )885886 with click.get_pager_file(color=color) as pager:887 pager.write(click.style("hello", fg="red") + "\n")888889 assert pager_out.read_text(encoding="utf-8") == expected890891892def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):893 """The no-stdout fallback should keep a text-only stream and set ``.color``."""894Merge branch 'stable'David Lordbefore adoptionbc36cd1
line 895why, one step back895 stream = io.StringIO()`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
line 896why, one step back896 monkeypatch.setattr(sys, "stdout", None)Merge branch 'stable'David Lordbefore adoptionbc36cd1
line 897why, one step back897 monkeypatch.setattr(click._termui_impl, "StringIO", lambda: stream)`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
lines 898–904why, one step back898 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)899900 styled_text = click.style("hello", fg="red")901902 with click.get_pager_file(color=False) as pager:903 pager.write(styled_text)904Merge branch 'stable'David Lordbefore adoptionbc36cd1
lines 905–906why, one step back905 assert not stream.closed906 assert stream.getvalue() == styled_text`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7
lines 907–936why, one step back907908909def test_get_pager_file_flushes_stream_on_exception(monkeypatch):910 """Exceptions should still flush the yielded stream in ``finally``."""911912 class FlushableTextStream(io.StringIO):913 def __init__(self):914 super().__init__()915 self.color = None916 self.flush_calls = 0917918 def flush(self):919 self.flush_calls += 1920921 stream = FlushableTextStream()922923 @contextlib.contextmanager924 def pager_contextmanager(color=None):925 yield stream, "utf-8", color926927 monkeypatch.setattr(928 click._termui_impl, "_pager_contextmanager", pager_contextmanager929 )930931 with pytest.raises(RuntimeError, match="boom"):932 with click.get_pager_file() as pager:933 assert pager is stream934 raise RuntimeError("boom")935936 assert stream.flush_calls == 1Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
lines 937–942why, one step back937938939def test_editor_unclosed_quote():940 """An unclosed quote in the editor command raises ValueError."""941 with pytest.raises(ValueError, match="No closing quotation"):942 Editor(editor='"unclosed').edit_files(["f.txt"])Rewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 943–1000why, one step back943944945@pytest.mark.parametrize(946 ("prompt_required", "required", "args", "expect"),947 [948 (True, False, None, "prompt"),949 (True, False, ["-v"], "Option '-v' requires an argument."),950 (False, True, None, "prompt"),951 (False, True, ["-v"], "prompt"),952 ],953)954def test_prompt_required_with_required(runner, prompt_required, required, args, expect):955 @click.command()956 @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)957 def cli(v):958 click.echo(str(v))959960 result = runner.invoke(cli, args, input="prompt")961 assert expect in result.output962963964@pytest.mark.parametrize(965 ("args", "expect"),966 [967 # Flag not passed, don't prompt.968 pytest.param(None, None, id="no flag"),969 # Flag and value passed, don't prompt.970 pytest.param(["-v", "value"], "value", id="short sep value"),971 pytest.param(["--value", "value"], "value", id="long sep value"),972 pytest.param(["-vvalue"], "value", id="short join value"),973 pytest.param(["--value=value"], "value", id="long join value"),974 # Flag without value passed, prompt.975 pytest.param(["-v"], "prompt", id="short no value"),976 pytest.param(["--value"], "prompt", id="long no value"),977 # Don't use next option flag as value.978 pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),979 ],980)981def test_prompt_required_false(runner, args, expect):982 @click.command()983 @click.option("-v", "--value", prompt=True, prompt_required=False)984 @click.option("-o")985 def cli(value, o):986 if o is not None:987 return value, o988989 return value990991 result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)992 assert result.exception is None993 assert result.return_value == expect994995996@pytest.mark.parametrize(997 ("prompt", "input", "default", "expect"),998 [999 (True, "password\npassword", None, "password"),1000 ("Confirm Password", "password\npassword\n", None, "password"),Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0
line 1001why, one step back1001 (True, "\n\n", "", ""),Rewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 1002–1024why, one step back1002 (False, None, None, None),1003 ],1004)1005def test_confirmation_prompt(runner, prompt, input, default, expect):1006 @click.command()1007 @click.option(1008 "--password",1009 prompt=prompt,1010 hide_input=True,1011 default=default,1012 confirmation_prompt=prompt,1013 )1014 def cli(password):1015 return password10161017 result = runner.invoke(cli, input=input, standalone_mode=False)1018 assert result.exception is None1019 assert result.return_value == expect10201021 if prompt == "Confirm Password":1022 assert "Confirm Password: " in result.output10231024Strip ANSI from `confirm()` and `prompt()` (#3653)Rowlando13before adoptionfe3ad76
lines 1025–1074why, one step back1025@pytest.mark.parametrize(1026 ("call", "user_input", "color", "expect"),1027 [1028 pytest.param(1029 lambda: click.confirm(click.style("Hello World!", fg="green")),1030 "y",1031 False,1032 "Hello World! [y/N]: y\n",1033 id="confirm-no-color",1034 ),1035 pytest.param(1036 lambda: click.confirm(click.style("Hello World!", fg="green")),1037 "y",1038 True,1039 "\x1b[32mHello World!\x1b[0m [y/N]: y\n",1040 id="confirm-color",1041 ),1042 pytest.param(1043 lambda: click.prompt(click.style("Name", fg="green")),1044 "Bob",1045 False,1046 "Name: Bob\n",1047 id="prompt-no-color",1048 ),1049 pytest.param(1050 lambda: click.prompt(click.style("Name", fg="green")),1051 "Bob",1052 True,1053 "\x1b[32mName\x1b[0m: Bob\n",1054 id="prompt-color",1055 ),1056 ],1057)1058def test_prompt_and_confirm_ansi_respects_color(1059 runner, call, user_input, color, expect1060):1061 """``confirm`` and ``prompt`` strip ANSI color and style codes from the1062 prompt when color is disabled and keep them when it is enabled, like1063 ``echo``. The prompt is written by ``input`` rather than ``echo``, so it1064 used to keep the codes regardless (issue 3572).1065 """10661067 @click.command()1068 def cli():1069 call()10701071 result = runner.invoke(cli, input=user_input, color=color)1072 assert result.output == expect10731074Rewrite second half of options docs (#2848)Rowlando13before adoptionab21233
lines 1075–1084why, one step back1075def test_false_show_default_cause_no_default_display_in_prompt(runner):1076 @click.command()1077 @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")1078 def cmd(arg1):1079 pass10801081 # Confirm that the default value is not included in the output when `show_default`1082 # is False1083 result = runner.invoke(cmd, input="my-input", standalone_mode=False)1084 assert "my-default-value" not in result.outputShow default string in prompt (#3328)Rowlando13before adoption76552ff
lines 1085–1136why, one step back108510861087@pytest.mark.parametrize(1088 ("show_default", "default", "user_input", "in_prompt", "not_in_prompt"),1089 [1090 # Regular string replaces the actual default in the prompt.1091 ("custom", "actual", "\n", "(custom)", "actual"),1092 # String with spaces.1093 ("custom label", "actual", "\n", "(custom label)", "actual"),1094 # Unicode characters.1095 ("∞", "0", "\n", "(∞)", None),1096 # Numeric default: custom string hides the number.1097 ("unlimited", 42, "\n", "(unlimited)", "42"),1098 # Explicit default=None: custom string still appears, must provide input.1099 ("computed at runtime", None, "value\n", "(computed at runtime)", None),1100 # No default kwarg at all (internal UNSET sentinel): same as None.1101 ("computed at runtime", UNSET, "value\n", "(computed at runtime)", None),1102 # Empty string is falsy: suppresses any default display.1103 ("", "actual", "\n", None, "actual"),1104 ],1105 ids=[1106 "simple-string",1107 "string-with-spaces",1108 "unicode",1109 "numeric-default",1110 "default-is-none",1111 "default-is-unset",1112 "empty-string-is-falsy",1113 ],1114)1115def test_string_show_default_in_prompt(1116 runner, show_default, default, user_input, in_prompt, not_in_prompt1117):1118 """When show_default is a string, the prompt should display that1119 string in parentheses instead of the actual default value,1120 matching the help text behavior. See pallets/click#2836."""11211122 option_kwargs = {"show_default": show_default, "prompt": True}1123 if default is not UNSET:1124 option_kwargs["default"] = default11251126 @click.command()1127 @click.option("--arg1", **option_kwargs)1128 def cmd(arg1):1129 click.echo(arg1)11301131 result = runner.invoke(cmd, input=user_input, standalone_mode=False)1132 prompt_line = result.output.split("\n")[0]1133 if in_prompt is not None:1134 assert in_prompt in prompt_line1135 if not_in_prompt is not None:1136 assert not_in_prompt not in prompt_lineMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 1137–1246why, one step back113711381139REPEAT = object()1140"""Sentinel value to indicate that the prompt is expected to be repeated.11411142I.e. the value provided by the user is not satisfactory and need to be re-prompted.1143"""11441145INVALID = object()1146"""Sentinel value to indicate that the prompt is expected to be invalid.11471148On invalid input, Click will output an error message and re-prompt the user.1149"""11501151BOOLEAN_FLAG_PROMPT_CASES = [1152 ###1153 ### Test cases with prompt=True explicitly enabled for the flag.1154 ###1155 # Prompt is allowed and the flag has no default, so it prompts.1156 ({"prompt": True}, [], "[y/N]", "y", True),1157 ({"prompt": True}, [], "[y/N]", "n", False),1158 # Empty input default to False.1159 ({"prompt": True}, [], "[y/N]", "", False),1160 # Changing the default to True, makes the prompt change to [Y/n].1161 ({"prompt": True, "default": True}, [], "[Y/n]", "", True),1162 ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),1163 ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),1164 # False is the default's default, so it prompts with [y/N].1165 ({"prompt": True, "default": False}, [], "[y/N]", "", False),1166 ({"prompt": True, "default": False}, [], "[y/N]", "y", True),1167 ({"prompt": True, "default": False}, [], "[y/N]", "n", False),1168 # Defaulting to None, prompts with [y/n], which makes the user explicitly choose1169 # between True or False.1170 ({"prompt": True, "default": None}, [], "[y/n]", "y", True),1171 ({"prompt": True, "default": None}, [], "[y/n]", "n", False),1172 # Random string default is treated as a truthy value, so it prompts with [Y/n].1173 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),1174 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),1175 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),1176 ###1177 ### Test cases with required=True explicitly enabled for the flag.1178 ###1179 # A required flag just raises an error unless a default is set.1180 ({"required": True}, [], None, None, MissingParameter),1181 ({"required": True, "default": True}, [], None, None, True),1182 ({"required": True, "default": False}, [], None, None, False),1183 ({"required": True, "default": None}, [], None, None, None),1184 ({"required": True, "default": "on"}, [], None, None, True),1185 ({"required": True, "default": "off"}, [], None, None, False),1186 ({"required": True, "default": "foo"}, [], None, None, BadParameter),1187 ###1188 ### Explicitly passing the flag to the CLI bypass any prompt, whatever the1189 ### configuration of the flag.1190 ###1191 # Flag allowing a prompt.1192 ({"prompt": True}, ["--flag"], None, None, True),1193 ({"prompt": True}, ["--no-flag"], None, None, False),1194 ({"prompt": True, "default": None}, ["--flag"], None, None, True),1195 ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),1196 ({"prompt": True, "default": True}, ["--flag"], None, None, True),1197 ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),1198 ({"prompt": True, "default": False}, ["--flag"], None, None, True),1199 ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),1200 ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),1201 ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),1202 # Required flag.1203 ({"required": True}, ["--flag"], None, None, True),1204 ({"required": True}, ["--no-flag"], None, None, False),1205 ({"required": True, "default": None}, ["--flag"], None, None, True),1206 ({"required": True, "default": None}, ["--no-flag"], None, None, False),1207 ({"required": True, "default": True}, ["--flag"], None, None, True),1208 ({"required": True, "default": True}, ["--no-flag"], None, None, False),1209 ({"required": True, "default": False}, ["--flag"], None, None, True),1210 ({"required": True, "default": False}, ["--no-flag"], None, None, False),1211 ({"required": True, "default": "foo"}, ["--flag"], None, None, True),1212 ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),1213]12141215FLAG_VALUE_PROMPT_CASES = [1216 ###1217 ### Test cases with prompt=True explicitly enabled for the flag.1218 ###1219 # Prompt is allowed and the flag has no default, so it prompts.1220 # But the flag_value is not set, so it defaults to a string.1221 ({"prompt": True}, [], "", "", REPEAT),1222 ({"prompt": True}, [], "", "y", "y"),1223 ({"prompt": True}, [], "", "n", "n"),1224 ({"prompt": True}, [], "", "foo", "foo"),1225 # This time we provide a boolean flag_value, which makes the flag behave like a1226 # boolean flag, and use the appropriate variation of [y/n].1227 ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),1228 ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),1229 ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),1230 ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),1231 ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),1232 ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),1233 # Other flag values changes the auto-detection of the flag type.1234 ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),1235 ({"prompt": True, "flag_value": None}, [], "", "y", "y"),1236 ({"prompt": True, "flag_value": None}, [], "", "n", "n"),1237 ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),1238 ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),1239 ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),1240 ###1241 ### Test cases with a flag_value and a default.1242 ###1243 # default=True1244 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),1245 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),1246 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73
lines 1247–1253why, one step back1247 # For boolean flags, default=True is a literal value, not a sentinel meaning1248 # "activate flag", so the prompt shows [Y/n] with default=True. See:1249 # https://github.com/pallets/click/issues/31111250 # https://github.com/pallets/click/pull/32391251 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),1252 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),1253 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 1254–1356why, one step back1254 # default=False1255 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),1256 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),1257 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),1258 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),1259 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),1260 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),1261 # default=None1262 (1263 {"prompt": True, "default": None, "flag_value": True},1264 [],1265 "[y/n]",1266 "",1267 INVALID,1268 ),1269 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),1270 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),1271 (1272 {"prompt": True, "default": None, "flag_value": False},1273 [],1274 "[y/n]",1275 "",1276 INVALID,1277 ),1278 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),1279 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),1280 # If the flag_value is None, the flag behave like a string flag, whatever the1281 # default is.1282 ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),1283 ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),1284 ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),1285 (1286 {"prompt": True, "default": False, "flag_value": None},1287 [],1288 "[False]",1289 "",1290 "False",1291 ),1292 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),1293 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),1294 ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),1295 ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),1296 ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),1297]129812991300@pytest.mark.parametrize(1301 ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),1302 # Boolean flag prompt cases.1303 [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]1304 # Non-boolean flag prompt cases.1305 + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],1306)1307def test_flag_value_prompt(1308 runner, opt_decls, opt_params, args, prompt, input, expected1309):1310 """Check how flag value are prompted and handled by all combinations of1311 ``prompt``, ``default``, and ``flag_value`` parameters.13121313 Covers concerns raised in issue https://github.com/pallets/click/issues/1992.1314 """13151316 @click.command()1317 @click.option(opt_decls, **opt_params)1318 def cli(flag):1319 click.echo(repr(flag))13201321 invoke_options = {"standalone_mode": False}1322 if input is not None:1323 assert isinstance(input, str)1324 invoke_options["input"] = f"{input}\n"13251326 result = runner.invoke(cli, args, **invoke_options)13271328 if expected in (MissingParameter, BadParameter):1329 assert isinstance(result.exception, expected)1330 assert not result.output1331 assert result.exit_code == 113321333 else:1334 expected_output = ""1335 if prompt is not None:1336 # Build the expected prompt.1337 assert isinstance(prompt, str)1338 expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "13391340 # Add the user input to the expected output.1341 assert isinstance(input, str)1342 expected_output += f"{expected_prompt}{input}\n"13431344 if expected is INVALID:1345 expected_output += "Error: invalid input\n"13461347 # The prompt is expected to be repeated.1348 if expected in (REPEAT, INVALID):1349 expected_output += expected_prompt13501351 if expected not in (REPEAT, INVALID):1352 expected_output += f"{expected!r}\n"13531354 assert result.output == expected_output1355 assert not result.stderr1356 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1Show custom error message in prompt with `hide_input=True` (#3256)Rowlando13before adoptionc943271
lines 1357–1612why, one step back135713581359class _CustomTypeNoValue(click.ParamType):1360 name = "custom"13611362 def convert(self, value, param, ctx):1363 if len(value) < 4:1364 self.fail("Password must be at least 4 characters", param, ctx)1365 return value136613671368class _CustomTypeWithRawValue(click.ParamType):1369 name = "custom_raw"13701371 def convert(self, value, param, ctx):1372 if value == "bad":1373 self.fail(f"rejected: {value}", param, ctx)1374 return value137513761377class _PasswordLengthType(click.ParamType):1378 """Mirrors the issue's original use case: a password validator1379 that references the user-typed value in its error message without1380 quoting it.1381 """13821383 name = "password"13841385 def convert(self, value, param, ctx):1386 if len(value) < 10:1387 self.fail(f"{value} is too short", param, ctx)1388 return value138913901391class _MixedQuotedAndRawType(click.ParamType):1392 """Custom type that mentions the user input both quoted (built-in1393 pattern) and raw within the same message.1394 """13951396 name = "mixed"13971398 def convert(self, value, param, ctx):1399 self.fail(f"got {value!r} which is the same as {value}", param, ctx)140014011402class _StaticMessageType(click.ParamType):1403 """Custom type whose error message never references the value."""14041405 name = "static"14061407 def convert(self, value, param, ctx):1408 self.fail("Authentication failed for this account", param, ctx)140914101411class _RejectAllRawType(click.ParamType):1412 """Always rejects, with the raw value (unquoted) in the message."""14131414 name = "reject_all_raw"14151416 def convert(self, value, param, ctx):1417 self.fail(f"rejected: {value}", param, ctx)141814191420class _MultiRawType(click.ParamType):1421 """Mentions the raw value multiple times in the same message."""14221423 name = "multi_raw"14241425 def convert(self, value, param, ctx):1426 self.fail(f"got {value} but {value} is bad", param, ctx)142714281429class _MultiReprType(click.ParamType):1430 """Mentions ``repr(value)`` multiple times in the same message."""14311432 name = "multi_repr"14331434 def convert(self, value, param, ctx):1435 self.fail(f"got {value!r} and {value!r}", param, ctx)143614371438class _ApostropheReprType(click.ParamType):1439 """Custom type whose ``repr(value)`` switches to double quotes when1440 the value itself contains a single quote.1441 """14421443 name = "apostrophe_repr"14441445 def convert(self, value, param, ctx):1446 self.fail(f"rejected {value!r}", param, ctx)144714481449@pytest.mark.parametrize(1450 ("type", "user_input", "expected_fragment", "unexpected_fragment"),1451 [1452 pytest.param(1453 click.INT,1454 "bad",1455 "'***' is not a valid integer",1456 "bad",1457 id="builtin-int-masks-repr-value",1458 ),1459 pytest.param(1460 _CustomTypeNoValue(),1461 "bad",1462 "Password must be at least 4 characters",1463 None,1464 id="custom-no-value-shows-message",1465 ),1466 pytest.param(1467 _CustomTypeWithRawValue(),1468 "bad",1469 "rejected: '***'",1470 "bad",1471 id="custom-raw-value-masked",1472 ),1473 pytest.param(1474 _PasswordLengthType(),1475 "PASSWORD",1476 "'***' is too short",1477 "PASSWORD",1478 id="unquoted-custom-message-should-mask-not-fallback",1479 ),1480 pytest.param(1481 _MixedQuotedAndRawType(),1482 "leakybits",1483 "got '***' which is the same as '***'",1484 "leakybits",1485 id="mixed-quoted-and-raw-both-masked-at-source",1486 ),1487 pytest.param(1488 click.IntRange(min=10, max=99),1489 "1",1490 "is not in the range",1491 None,1492 id="intrange-numeric-substring-falls-back-to-generic",1493 ),1494 pytest.param(1495 _StaticMessageType(),1496 "ent",1497 "Authentication failed for this account",1498 None,1499 id="partial-word-match-falls-back-to-generic",1500 ),1501 # When the raw (unquoted) value appears in the message, mask it instead1502 # of replacing the whole message with a generic fallback that throws1503 # useful information away.1504 pytest.param(1505 _RejectAllRawType(),1506 "secret",1507 "rejected: '***'",1508 "secret",1509 id="raw-value-should-be-masked-not-fallback",1510 ),1511 # When the raw value occurs more than1512 # once unquoted, every occurrence must be masked.1513 pytest.param(1514 _MultiRawType(),1515 "secret",1516 "got '***' but '***' is bad",1517 "secret",1518 id="multi-occurrence-raw-mask-all",1519 ),1520 pytest.param(1521 _MultiReprType(),1522 "secret",1523 "got '***' and '***'",1524 "secret",1525 id="multi-occurrence-repr-mask-all",1526 ),1527 pytest.param(1528 _PasswordLengthType(),1529 "a.b*c+",1530 "'***' is too short",1531 "a.b*c+",1532 id="regex-special-chars-must-be-escaped",1533 ),1534 pytest.param(1535 _PasswordLengthType(),1536 "пароль",1537 "'***' is too short",1538 "пароль",1539 id="unicode-value-masked",1540 ),1541 pytest.param(1542 _ApostropheReprType(),1543 "it's",1544 "rejected '***'",1545 "it's",1546 id="apostrophe-in-value-uses-double-quote-repr",1547 ),1548 pytest.param(1549 _MixedQuotedAndRawType(),1550 "leakybits",1551 "got '***' which is the same as '***'",1552 "leakybits",1553 id="mixed-quoted-and-raw-mask-both",1554 ),1555 ],1556)1557def test_hide_input_error_message(1558 runner, type, user_input, expected_fragment, unexpected_fragment1559):1560 """https://github.com/pallets/click/issues/2809"""15611562 @click.command()1563 @click.option("--password", prompt=True, hide_input=True, type=type)1564 def cli(password):1565 click.echo(password)15661567 result = runner.invoke(cli, input=user_input)1568 assert expected_fragment in result.output1569 if unexpected_fragment is not None:1570 assert unexpected_fragment not in result.output157115721573def test_hide_input_confirmation_prompt_mismatch_unaffected(runner):1574 """The ``hide_input`` mask logic only applies to ``value_proc``1575 failures. The separate ``confirmation_prompt`` mismatch path must1576 keep emitting its own message, with no value leak from either entry.1577 """15781579 @click.command()1580 @click.option("--password", prompt=True, confirmation_prompt=True, hide_input=True)1581 def cli(password):1582 click.echo(f"got: {password}")15831584 # First pair mismatches, second pair matches.1585 result = runner.invoke(cli, input="firstone\nsecondone\nfinalone\nfinalone\n")1586 assert "Error: The two entered values do not match." in result.output1587 assert "firstone" not in result.output1588 assert "secondone" not in result.output1589 # Successful prompt echoes the final value back via the command body.1590 assert "got: finalone" in result.output1591 assert result.exit_code == 0159215931594def test_hide_input_value_never_leaks_when_err_true(runner):1595 """``click.prompt(..., err=True)`` routes its error message to1596 stderr. The masking logic must apply on that path too: the raw1597 input must not appear on either stream.1598 """15991600 @click.command()1601 def cli():1602 value = click.prompt(1603 "Password",1604 hide_input=True,1605 type=_PasswordLengthType(),1606 err=True,1607 )1608 click.echo(value)16091610 result = runner.invoke(cli, input="leaky\n", mix_stderr=False)1611 assert "leaky" not in result.stdout1612 assert "leaky" not in result.stderr