Skip to content
Myr

test_termui.py

This file

Path

tests/test_termui.py

1,984 lines · 68.1 KiB · Python

Last changed by

Add support of `pathlib.Path` to `edit` (#3781)Rowlando13before adoptione1fd594

History of this file

Take it

The walk stopped after 200 commits: lines older than 9ce34f2 point at it.

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 1why, one step back
1import contextlib

Merge `stable` into `main` after `CHANGES` rST to Markdown conversion (#3563)Kevin Deldyckebefore adoption8a1b1a3

line 2why, one step back
2import gc

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 3why, one step back
3import io

Fix error reporting on Windows when an error is raised in the pager (#3764)Rowlando13before adoptionfc5c7f4

line 4why, one step back
4import os

Forward all user's parameters set in `PAGER` and improve flag detection (#3777)Rowlando13before adoption2103e15

line 5why, one step back
5import pathlib

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

line 6why, one step back
6import platform

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

line 7why, one step back
7import shlex

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 8why, one step back
8import shutil

Forward all user's parameters set in `PAGER` and improve flag detection (#3777)Rowlando13before adoption2103e15

line 9why, one step back
9import subprocess

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 10why, one step back
10import sys

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 11–12why, one step back
11import tempfile
12import time

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

line 13why, one step back
13from unittest.mock import patch

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 14–16why, one step back
14
15import pytest16

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 17why, one step back
17import click

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 18–19why, one step back
18import click._termui_impl
19from click._compat import WIN

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

line 20why, one step back
20from click._termui_impl import Editor

Show default string in prompt (#3328)Rowlando13before adoption76552ff

line 21why, one step back
21from click._utils import UNSET

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 22–23why, one step back
22from click.exceptions import BadParameter
23from click.exceptions import MissingParameter

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 24–111why, one step back
24
2526class FakeClock:27 def __init__(self):28 self.now = time.time()2930 def advance_time(self, seconds=1):31 self.now += seconds3233 def time(self):34 return self.now353637def _create_progress(length=10, **kwargs):38 progress = click.progressbar(tuple(range(length)))39 for key, value in kwargs.items():40 setattr(progress, key, value)41 return progress424344def test_progressbar_strip_regression(runner, monkeypatch):45 label = " padded line"4647 @click.command()48 def cli():49 with _create_progress(label=label) as progress:50 for _ in progress:51 pass5253 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)54 assert (55 label56 in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output57 )585960def test_progressbar_length_hint(runner, monkeypatch):61 class Hinted:62 def __init__(self, n):63 self.items = list(range(n))6465 def __length_hint__(self):66 return len(self.items)6768 def __iter__(self):69 return self7071 def __next__(self):72 if self.items:73 return self.items.pop()74 else:75 raise StopIteration7677 next = __next__7879 @click.command()80 def cli():81 with click.progressbar(Hinted(10), label="test") as progress:82 for _ in progress:83 pass8485 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)86 result = runner.invoke(cli, [])87 assert result.exception is None888990def test_progressbar_no_tty(runner, monkeypatch):91 @click.command()92 def cli():93 with _create_progress(label="working") as progress:94 for _ in progress:95 pass9697 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)98 assert runner.invoke(cli, []).output == "working\n"99100101def test_progressbar_hidden_manual(runner, monkeypatch):102 @click.command()103 def cli():104 with _create_progress(label="see nothing", hidden=True) as progress:105 for _ in progress:106 pass107108 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)109 assert runner.invoke(cli, []).output == ""110111

Settles progress bar on its final position (#3769)Rowlando13before adoption150d107

lines 112–142why, one step back
112@pytest.mark.parametrize("update_min_steps", [1, 2, 3, 7, 20, 25])
113@pytest.mark.parametrize("drive", ["iterate", "update"])114def test_progressbar_lands_on_final_position(monkeypatch, update_min_steps, drive):115 """The bar reaches its total whatever the ``update_min_steps`` threshold.116117 Regression for issue #3571: a threshold that does not divide the length118 left a remainder pending, so `show_pos` froze below completion, reporting119 `14/20` for a length of 20 and a threshold of 7. Thresholds of 1 and 2 do120 divide 20, and 25 exceeds it, so nothing is ever rendered until the end.121 """122 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)123 stream = io.StringIO()124125 if drive == "iterate":126 with click.progressbar(127 range(20), show_pos=True, update_min_steps=update_min_steps, file=stream128 ) as bar:129 for _ in bar:130 pass131 else:132 with click.progressbar(133 length=20, show_pos=True, update_min_steps=update_min_steps, file=stream134 ) as bar:135 for _ in range(20):136 bar.update(1)137138 assert bar.pos == 20139 assert bar.finished140 assert "20/20" in stream.getvalue()141142

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 143–290why, one step back
143@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])
144def test_progressbar_time_per_iteration(runner, avg, expected):145 with _create_progress(2, avg=avg) as progress:146 assert progress.time_per_iteration == expected147148149@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])150def test_progressbar_eta(runner, finished, expected):151 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:152 assert progress.eta == expected153154155@pytest.mark.parametrize(156 "eta, expected",157 [158 (0, "00:00:00"),159 (30, "00:00:30"),160 (90, "00:01:30"),161 (900, "00:15:00"),162 (9000, "02:30:00"),163 (99999999999, "1157407d 09:46:39"),164 (None, ""),165 ],166)167def test_progressbar_format_eta(runner, eta, expected):168 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:169 assert progress.format_eta() == expected170171172@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])173def test_progressbar_format_pos(runner, pos, length):174 with _create_progress(length, pos=pos) as progress:175 result = progress.format_pos()176 assert result == f"{pos}/{length}"177178179@pytest.mark.parametrize(180 "length, finished, pos, avg, expected",181 [182 (8, False, 7, 0, "#######-"),183 (0, True, 8, 0, "########"),184 ],185)186def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):187 with _create_progress(188 length, width=8, pos=pos, finished=finished, avg=[avg]189 ) as progress:190 assert progress.format_bar() == expected191192193@pytest.mark.parametrize(194 "length, show_percent, show_pos, pos, expected",195 [196 (0, True, True, 0, " [--------] 0/0 0%"),197 (0, False, True, 0, " [--------] 0/0"),198 (0, False, False, 0, " [--------]"),199 (0, False, False, 0, " [--------]"),200 (8, True, True, 8, " [########] 8/8 100%"),201 ],202)203def test_progressbar_format_progress_line(204 runner, length, show_percent, show_pos, pos, expected205):206 with _create_progress(207 length,208 width=8,209 show_percent=show_percent,210 pos=pos,211 show_pos=show_pos,212 ) as progress:213 assert progress.format_progress_line() == expected214215216@pytest.mark.parametrize("test_item", ["test", None])217def test_progressbar_format_progress_line_with_show_func(runner, test_item):218 def item_show_func(item):219 return item220221 with _create_progress(222 item_show_func=item_show_func, current_item=test_item223 ) as progress:224 if test_item:225 assert progress.format_progress_line().endswith(test_item)226 else:227 assert progress.format_progress_line().endswith(progress.format_pct())228229230def test_progressbar_init_exceptions(runner):231 with pytest.raises(TypeError, match="iterable or length is required"):232 click.progressbar()233234235def test_progressbar_iter_outside_with_exceptions(runner):236 progress = click.progressbar(length=2)237238 with pytest.raises(RuntimeError, match="with block"):239 iter(progress)240241242def test_progressbar_is_iterator(runner, monkeypatch):243 @click.command()244 def cli():245 with click.progressbar(range(10), label="test") as progress:246 while True:247 try:248 next(progress)249 except StopIteration:250 break251252 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)253 result = runner.invoke(cli, [])254 assert result.exception is None255256257def test_choices_list_in_prompt(runner, monkeypatch):258 @click.command()259 @click.option(260 "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True261 )262 def cli_with_choices(g):263 pass264265 @click.command()266 @click.option(267 "-g",268 type=click.Choice(["none", "day", "week", "month"]),269 prompt=True,270 show_choices=False,271 )272 def cli_without_choices(g):273 pass274275 result = runner.invoke(cli_with_choices, [], input="none")276 assert "(none, day, week, month)" in result.output277278 result = runner.invoke(cli_without_choices, [], input="none")279 assert "(none, day, week, month)" not in result.output280281282@pytest.mark.parametrize(283 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]284)285def test_file_prompt_default_format(runner, file_kwargs):286 @click.command()287 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))288 def cli(f):289 click.echo(f.name)290

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

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

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 292–423why, one step back
292 assert result.output == f"file [{__file__}]: \n{__file__}\n"
293294295def test_secho(runner):296 with runner.isolation() as outstreams:297 click.secho(None, nl=False)298 bytes = outstreams[0].getvalue()299 assert bytes == b""300301302@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")303@pytest.mark.parametrize(304 ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]305)306def test_secho_non_text(runner, value, expect):307 with runner.isolation() as (out, _, _):308 click.secho(value, nl=False, color=True, bg="magenta")309 result = out.getvalue()310 assert result == expect311312313def test_progressbar_yields_all_items(runner):314 with click.progressbar(range(3)) as progress:315 assert len(list(progress)) == 3316317318def test_progressbar_update(runner, monkeypatch):319 fake_clock = FakeClock()320321 @click.command()322 def cli():323 with click.progressbar(range(4)) as progress:324 for _ in progress:325 fake_clock.advance_time()326 print("")327328 monkeypatch.setattr(time, "time", fake_clock.time)329 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)330 output = runner.invoke(cli, []).output331332 lines = [line for line in output.split("\n") if "[" in line]333334 assert " 0%" in lines[0]335 assert " 25% 00:00:03" in lines[1]336 assert " 50% 00:00:02" in lines[2]337 assert " 75% 00:00:01" in lines[3]338 assert "100% " in lines[4]339340341def test_progressbar_item_show_func(runner, monkeypatch):342 """item_show_func should show the current item being yielded."""343344 @click.command()345 def cli():346 with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress:347 for item in progress:348 click.echo(f" item {item}")349350 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)351 lines = runner.invoke(cli).output.splitlines()352353 for i, line in enumerate(x for x in lines if "item" in x):354 assert f"{i} item {i}" in line355356357def test_progressbar_update_with_item_show_func(runner, monkeypatch):358 @click.command()359 def cli():360 with click.progressbar(361 length=6, item_show_func=lambda x: f"Custom {x}"362 ) as progress:363 while not progress.finished:364 progress.update(2, progress.pos)365 click.echo()366367 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)368 output = runner.invoke(cli, []).output369370 lines = [line for line in output.split("\n") if "[" in line]371372 assert "Custom 0" in lines[0]373 assert "Custom 2" in lines[1]374 assert "Custom 4" in lines[2]375376377def test_progress_bar_update_min_steps(runner):378 bar = _create_progress(update_min_steps=5)379 bar.update(3)380 assert bar._completed_intervals == 3381 assert bar.pos == 0382 bar.update(2)383 assert bar._completed_intervals == 0384 assert bar.pos == 5385386387@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))388@pytest.mark.parametrize("echo", [True, False])389@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")390def test_getchar_windows(runner, monkeypatch, key_char, echo):391 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)392 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)393 monkeypatch.setattr(click.termui, "_getchar", None)394 assert click.getchar(echo) == key_char395396397@pytest.mark.parametrize(398 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]399)400@pytest.mark.skipif(401 not WIN, reason="Tests special character inputs using the msvcrt module."402)403def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):404 ordered_inputs = [key_char, special_key_char]405 monkeypatch.setattr(406 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()407 )408 monkeypatch.setattr(click.termui, "_getchar", None)409 assert click.getchar() == f"{special_key_char}{key_char}"410411412@pytest.mark.parametrize(413 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]414)415@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")416def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):417 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)418 monkeypatch.setattr(click.termui, "_getchar", None)419420 with pytest.raises(exc):421 click.getchar()422423

Add support of `pathlib.Path` to `edit` (#3781)Rowlando13before adoptione1fd594

line 424why, one step back
424@pytest.mark.skipif(WIN, reason="No sed on Windows.")

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 425–429why, one step back
425def test_fast_edit(runner):
426 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")427 assert result == "aTest\nbTest\n"428429

Add support of `pathlib.Path` to `edit` (#3781)Rowlando13before adoptione1fd594

line 430why, one step back
430@pytest.mark.skipif(WIN, reason="No sed on Windows.")

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 431–432why, one step back
431def test_edit(runner):
432 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:

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

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

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 434–438why, one step back
434 named_tempfile.flush()
435436 result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")437 assert result is None438

add codespell pre-commit hook (#3373)David Lordbefore adoption8bd8b4a

line 439why, one step back
439 # We need to reopen the file as it becomes unreadable after the edit.

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

line 440why, one step back
440 with open(named_tempfile.name) as reopened_file:

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

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

Add support of `pathlib.Path` to `edit` (#3781)Rowlando13before adoptione1fd594

lines 449–461why, one step back
449
450451@pytest.mark.skipif(WIN, reason="No sed on Windows.")452@pytest.mark.parametrize("use_iterable", [False, True], ids=["single", "iterable"])453def test_edit_pathlib(runner, tmp_path, use_iterable):454 """Issue #2869: ``filename`` accepts ``os.PathLike`` values."""455 file_path = tmp_path / "file.txt"456 file_path.write_text("a\nb\n", encoding="UTF-8")457 filename = [file_path] if use_iterable else file_path458459 result = click.edit(filename=filename, editor="sed -i~ 's/$/Test/'")460 assert result is None461 assert file_path.read_text(encoding="UTF-8") == "aTest\nbTest\n"

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

lines 462–483why, one step back
462
463464@pytest.mark.parametrize(465 ("editor_cmd", "filenames", "expected_args"),466 [467 pytest.param(468 "myeditor --wait --flag",469 ["file1.txt", "file2.txt"],470 ["myeditor", "--wait", "--flag", "file1.txt", "file2.txt"],471 id="editor with args",472 ),473 pytest.param(474 "vi",475 ['file"; rm -rf / ; echo "'],476 ["vi", 'file"; rm -rf / ; echo "'],477 id="shell metacharacters in filename",478 ),479 # Issue #1026: editor path with spaces must be quoted.480 pytest.param(481 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"',482 ["f.txt"],483 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"],

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

line 484why, one step back
484 id="quoted windows path with spaces",

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

lines 485–490why, one step back
485 ),
486 # PR #1477: pager/editor command with flags, like ``less -FRSX``.487 pytest.param(488 "less -FRSX",489 ["f.txt"],490 ["less", "-FRSX", "f.txt"],

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

line 491why, one step back
491 id="command with flags",

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

lines 492–497why, one step back
492 ),
493 # Issue #1026: quoted command with ``--wait`` flag.494 pytest.param(495 '"my command" --option value arg',496 ["f.txt"],497 ["my command", "--option", "value", "arg", "f.txt"],

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

line 498why, one step back
498 id="quoted command with args",

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

lines 499–511why, one step back
499 ),
500 # PR #1477: unquoted unix path.501 pytest.param(502 "/usr/bin/vim",503 ["f.txt"],504 ["/usr/bin/vim", "f.txt"],505 id="unix absolute path",506 ),507 # Issue #1026: macOS path with escaped space.508 pytest.param(509 "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl",510 ["f.txt"],511 ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "f.txt"],

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

line 512why, one step back
512 id="escaped space in unix path",

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

line 513why, one step back
513 ),

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

lines 514–555why, one step back
514 pytest.param(
515 " vim ",516 ["f.txt"],517 ["vim", "f.txt"],518 id="leading and trailing whitespace",519 ),520 pytest.param(521 "vim\tf.txt",522 [],523 ["vim", "f.txt"],524 id="tab-separated tokens",525 ),526 pytest.param(527 "'/Applications/My Editor.app/Contents/MacOS/editor'",528 ["f.txt"],529 ["/Applications/My Editor.app/Contents/MacOS/editor", "f.txt"],530 id="single-quoted path with spaces",531 ),532 pytest.param(533 '"my editor" --wait --new-window',534 ["file 1.txt", "file 2.txt"],535 ["my editor", "--wait", "--new-window", "file 1.txt", "file 2.txt"],536 id="quoted editor with multiple flags and filenames with spaces",537 ),538 pytest.param(539 "vim -u NONE -N",540 ["f.txt"],541 ["vim", "-u", "NONE", "-N", "f.txt"],542 id="multiple short flags",543 ),544 pytest.param(545 "editor",546 ['file"name.txt'],547 ["editor", 'file"name.txt'],548 id="filename with double quote",549 ),550 pytest.param(551 "editor",552 ["file'name.txt"],553 ["editor", "file'name.txt"],554 id="filename with single quote",555 ),

Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f

lines 556–617why, one step back
556 ],
557)558def test_editor_path_normalization(editor_cmd, filenames, expected_args):559 with patch("subprocess.Popen") as mock_popen:560 mock_popen.return_value.wait.return_value = 0561 Editor(editor=editor_cmd).edit_files(filenames)562563 mock_popen.assert_called_once()564 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]565 assert args == expected_args566 assert mock_popen.call_args[1].get("shell") is None567568569@pytest.mark.skipif(not WIN, reason="Windows-specific editor paths")570@pytest.mark.parametrize(571 ("editor_cmd", "expected_cmd"),572 [573 pytest.param(574 "notepad",575 ["notepad"],576 id="plain notepad",577 ),578 pytest.param(579 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe" --wait',580 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "--wait"],581 id="quoted path with flag",582 ),583 ],584)585def test_editor_windows_path_normalization(editor_cmd, expected_cmd):586 """Windows-specific tests: verify ``Popen`` receives unquoted paths that587 ``subprocess.list2cmdline`` can re-quote for ``CreateProcess``."""588 with patch("subprocess.Popen") as mock_popen:589 mock_popen.return_value.wait.return_value = 0590 Editor(editor=editor_cmd).edit_files(["f.txt"])591592 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]593 assert args == expected_cmd + ["f.txt"]594 assert mock_popen.call_args[1].get("shell") is None595596597def test_editor_env_passed_through():598 with patch("subprocess.Popen") as mock_popen:599 mock_popen.return_value.wait.return_value = 0600 Editor(editor="vi", env={"MY_VAR": "1"}).edit_files(["f.txt"])601602 env = mock_popen.call_args[1].get("env")603 assert env is not None604 assert env["MY_VAR"] == "1"605606607def test_editor_failure_exception():608 with patch("subprocess.Popen") as mock_popen:609 mock_popen.return_value.wait.return_value = 1610 with pytest.raises(click.ClickException, match="Editing failed"):611 Editor(editor="vi").edit_files(["f.txt"])612613614def test_editor_nonexistent_exception():615 with patch("subprocess.Popen", side_effect=OSError("not found")):616 with pytest.raises(click.ClickException, match="not found"):617 Editor(editor="nonexistent").edit_files(["f.txt"])

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

lines 618–673why, one step back
618
619620@pytest.mark.parametrize(621 ("pager_env", "expected_parts"),622 [623 # Simple commands.624 pytest.param("cat", ["cat"], id="simple command"),625 pytest.param("less", ["less"], id="less"),626 pytest.param("less -FRSX", ["less", "-FRSX"], id="command with flags"),627 # Whitespace handling.628 pytest.param("", [], id="empty string"),629 pytest.param(" ", [], id="whitespace only"),630 pytest.param(" less ", ["less"], id="leading and trailing spaces"),631 pytest.param("less\t-R", ["less", "-R"], id="tab as separator"),632 # Quoted Windows paths: quotes are stripped in POSIX mode (the633 # default), preserving backslashes inside quoted tokens (issue #1026).634 pytest.param(635 '"C:\\Program Files\\Git\\usr\\bin\\less.exe"',636 ["C:\\Program Files\\Git\\usr\\bin\\less.exe"],637 id="quoted windows path with spaces",638 ),639 pytest.param(640 '"C:\\Program Files\\Git\\usr\\bin\\less.exe" -R',641 ["C:\\Program Files\\Git\\usr\\bin\\less.exe", "-R"],642 id="quoted windows path with flag",643 ),644 # Single-quoted path.645 pytest.param(646 "'/usr/local/bin/my pager'",647 ["/usr/local/bin/my pager"],648 id="single-quoted path with spaces",649 ),650 # Unix paths.651 pytest.param("/usr/bin/less", ["/usr/bin/less"], id="unix absolute path"),652 pytest.param(653 "/usr/bin/my\\ pager",654 ["/usr/bin/my pager"],655 id="escaped space in unix path",656 ),657 # PR #1477: POSIX mode (the default) eats unquoted backslashes.658 # On Windows, users must quote paths that contain backslashes.659 pytest.param(660 "C:\\path\\to\\exe /test other\\path",661 ["C:pathtoexe", "/test", "otherpath"],662 id="unquoted backslashes eaten in POSIX mode",663 ),664 ],665)666def test_pager_shlex_split(pager_env, expected_parts):667 """Verify shlex.split produces the expected argv for PAGER values.668669 Tests the splitting logic used by :func:`click._termui_impl.pager` to670 turn the ``PAGER`` environment variable into an ``argv`` list. See671 issue #1026, PR #1477, PR #1543, PR #2775.672 """673 assert shlex.split(pager_env) == expected_parts

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 674–776why, one step back
674
675676def _get_real_pager_command() -> str:677 """Return a real pager binary path used to exercise the pipe pager branch.678679 ..warning::680 Unix-only for now: ``more.com`` on Windows is interactive and goes681 through ``_tempfilepager`` rather than ``_pipepager``.682 """683 pager_path = shutil.which("cat")684 assert pager_path is not None, "cat not available"685 return pager_path686687688def _run_get_pager_file_with_real_pager(monkeypatch, capfd, writer, color=False):689 """Run through the pipe pager backend selected by ``PAGER``."""690 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)691 monkeypatch.setitem(692 click._termui_impl.os.environ, "PAGER", _get_real_pager_command()693 )694695 with click.get_pager_file(color=color) as pager:696 writer(pager)697698 # The real pager writes to the process stdout; stderr should stay quiet.699 out, err = capfd.readouterr()700 assert err == ""701 return out702703704def _write_pager_from_multiple_sites(pager):705 pager.write("prefix\n")706 click.echo("middle", file=pager)707 pager.write("suffix\n")708709710@pytest.mark.skipif(711 WIN,712 reason="Exercises the pipe pager path; Windows uses _tempfilepager.",713)714@pytest.mark.parametrize(715 ("writer", "color", "expected"),716 [717 pytest.param(718 _write_pager_from_multiple_sites,719 False,720 "prefix\nmiddle\nsuffix\n",721 id="multiple write sites",722 ),723 pytest.param(724 lambda pager: pager.write("hello\n"), False, "hello\n", id="plain text"725 ),726 pytest.param(727 lambda pager: pager.write(click.style("hello", fg="red") + "\n"),728 False,729 "hello\n",730 id="strip ansi",731 ),732 pytest.param(733 lambda pager: pager.write(click.style("hello", fg="red") + "\n"),734 True,735 click.style("hello", fg="red") + "\n",736 id="preserve ansi",737 ),738 pytest.param(lambda pager: pager.write(""), False, "", id="empty string"),739 ],740)741def test_get_pager_file_with_real_pager_binary_stream(742 monkeypatch, capfd, writer, color, expected743):744 """A real pager should exercise the BinaryIO branch."""745 output = _run_get_pager_file_with_real_pager(746 monkeypatch, capfd, writer, color=color747 )748749 assert output == expected750751752@pytest.mark.skipif(753 WIN,754 reason="Exercises the pipe pager path; Windows uses _tempfilepager.",755)756@pytest.mark.parametrize(757 ("color", "expected"),758 [759 pytest.param(False, "hello\n", id="strip ansi"),760 pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),761 ],762)763def test_echo_via_pager_real_pager_handles_ansi(monkeypatch, capfd, color, expected):764 """``echo_via_pager`` should honor ``color`` like ``get_pager_file``."""765 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)766 monkeypatch.setitem(767 click._termui_impl.os.environ, "PAGER", _get_real_pager_command()768 )769770 click.echo_via_pager(click.style("hello", fg="red"), color=color)771772 out, err = capfd.readouterr()773 assert err == ""774 assert out == expected775776

Forward all user's parameters set in `PAGER` and improve flag detection (#3777)Rowlando13before adoption2103e15

lines 777–927why, one step back
777@pytest.mark.skipif(WIN, reason="The fake pager is a shell script.")
778@pytest.mark.parametrize(779 ("pager_name", "expected_color"),780 [781 pytest.param("less", True, id="less"),782 pytest.param("less.exe", True, id="less.exe"),783 pytest.param("LESS.EXE", False, id="upper case stays unmatched on POSIX"),784 pytest.param("cat", False, id="not less"),785 ],786)787def test_pipepager_less_detection_matches_stem(788 monkeypatch, tmp_path, pager_name, expected_color789):790 """The ``less`` detection behind the ``LESS=-R`` auto-enable matches the791 command stem, so a ``less.exe`` resolved on Windows is recognized the same792 as a bare ``less``. POSIX keeps an exact, case-sensitive match.793 """794 fake_pager = tmp_path / pager_name795 fake_pager.write_text("#!/bin/sh\ncat\n", encoding="UTF-8")796 fake_pager.chmod(0o755)797798 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)799 monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", str(fake_pager))800 monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)801802 with click.get_pager_file() as pager:803 assert pager.color is expected_color804805806@pytest.mark.skipif(WIN, reason="The fake pager is a shell script.")807def test_pipepager_less_detection_case_insensitive_on_windows(monkeypatch, tmp_path):808 """Windows filesystems are case-insensitive, so ``which`` resolves809 whatever case the file carries: the ``less`` match casefolds there.810811 Runs ``_pipepager`` directly: faking ``WIN`` makes812 ``_pager_contextmanager`` route to the temp file strategy instead.813 """814 fake_pager = tmp_path / "LESS.EXE"815 fake_pager.write_text("#!/bin/sh\ncat\n", encoding="UTF-8")816 fake_pager.chmod(0o755)817818 monkeypatch.setattr(click._termui_impl, "WIN", True)819 monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)820821 with click._termui_impl._pipepager(fake_pager, []) as (_, color):822 assert color is True823824825class _FakePagerProcess:826 """Stand-in for :class:`subprocess.Popen` recording argv and env without827 launching a process."""828829 def __init__(self, argv, *, env=None, **kwargs):830 self.argv = argv831 self.env = env832 self.returncode = 0833 self.stdin = io.StringIO()834835 def terminate(self):836 pass837838 def wait(self):839 return 0840841842@pytest.mark.parametrize(843 ("cmd_parts", "less_env", "expected_color", "expected_less"),844 [845 pytest.param(["less"], None, True, "-R", id="no flags: inject LESS=-R"),846 pytest.param(["less", "-R"], None, True, None, id="explicit -R"),847 pytest.param(["less", "-rX"], None, True, None, id="bundled short flags"),848 pytest.param(["less"], "-R", True, "-R", id="LESS env var"),849 pytest.param(850 ["less", "--RAW-CONTROL-CHARS"], None, True, None, id="long option"851 ),852 pytest.param(["less", "-X"], None, None, None, id="unrelated flag"),853 pytest.param(854 ["less"],855 "--prompt=resume",856 None,857 "--prompt=resume",858 id="long option with r substring",859 ),860 pytest.param(["less", "README.md"], None, None, None, id="filename with R"),861 pytest.param(862 ["less", "requirements.txt"], None, None, None, id="filename with r"863 ),864 pytest.param(865 ["less", "--", "README.md"],866 None,867 None,868 None,869 id="option terminator shields filenames",870 ),871 pytest.param(872 # The detection matches the bare long option: an ``r`` inside an873 # option value does not request raw mode.874 ["less", "--raw-control-chars=x"],875 None,876 None,877 None,878 id="long option with value",879 ),880 pytest.param(881 # Unbalanced quotes make shlex.split raise: the detection falls882 # back to whitespace splitting, which still finds the -R.883 ["less"],884 '-R "',885 True,886 '-R "',887 id="unparsable LESS",888 ),889 ],890)891def test_pipepager_less_raw_mode_detection(892 monkeypatch, cmd_parts, less_env, expected_color, expected_less893):894 """Raw-mode detection parses the option tokens from ``LESS`` and the895 command line. Filenames and unrelated options carrying the letter ``r``896 or ``R`` do not request raw mode, and ``_pipepager`` then reports no897 opinion (``None``) that :func:`get_pager_file` settles to off.898 {issue}`3416`899 """900 if less_env is None:901 monkeypatch.delitem(click._termui_impl.os.environ, "LESS", raising=False)902 else:903 monkeypatch.setitem(click._termui_impl.os.environ, "LESS", less_env)904905 processes: list[_FakePagerProcess] = []906907 def fake_popen(*args, **kwargs):908 process = _FakePagerProcess(*args, **kwargs)909 processes.append(process)910 return process911912 monkeypatch.setattr(subprocess, "Popen", fake_popen)913 # Popen is faked, so no real binary needs to exist behind the resolved914 # path: the stem is all the less detection reads from it.915 cmd_path = pathlib.Path("/tests/less")916917 with click._termui_impl._pipepager(cmd_path, cmd_parts[1:]) as (_, color):918 pass919920 assert color is expected_color921 (process,) = processes922 if expected_less is None:923 assert "LESS" not in process.env924 else:925 assert process.env["LESS"] == expected_less926927

Merge `stable` into `main` after `CHANGES` rST to Markdown conversion (#3563)Kevin Deldyckebefore adoption8a1b1a3

lines 928–965why, one step back
928def test_echo_via_pager_streams_each_write(monkeypatch):
929 """Each write is flushed so a slow generator streams to the pager930 incrementally instead of buffering until the end (issues #3242, #2542).931 """932 calls = []933934 class RecordingStream(io.StringIO):935 def __init__(self):936 super().__init__()937 self.color = None938939 def write(self, s):940 calls.append("write")941 return super().write(s)942943 def flush(self):944 calls.append("flush")945946 stream = RecordingStream()947 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)948 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)949950 def generate():951 yield "a\n"952 yield "b\n"953 yield "c\n"954955 click.echo_via_pager(generate())956957 # No two writes are adjacent: every chunk is flushed before the next one,958 # so the pager sees output as it is produced.959 assert not any(960 calls[i] == "write" and calls[i + 1] == "write" for i in range(len(calls) - 1)961 )962 assert calls.count("write") == 4 # three chunks plus the trailing newline963 assert stream.getvalue() == "a\nb\nc\n\n"964965

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 966–1005why, one step back
966def test_get_pager_file_pager_missing_binary_falls_back(monkeypatch, tmp_path):
967 """``PAGER`` pointing to a nonexistent binary falls back to the text stdout."""968 pager_out = tmp_path / "pager_out.txt"969970 monkeypatch.setitem(971 click._termui_impl.os.environ,972 "PAGER",973 "click-tests-nonexistent-pager-9b3f2",974 )975 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)976977 with pager_out.open("w", encoding="utf-8") as text_stream:978 monkeypatch.setattr(979 click._termui_impl, "_default_text_stdout", lambda: text_stream980 )981982 with click.get_pager_file() as pager:983 pager.write("hello\n")984985 assert pager_out.read_text(encoding="utf-8") == "hello\n"986987988def test_get_pager_file_pager_unset_falls_back_when_no_default(monkeypatch, tmp_path):989 """``PAGER`` unset still works when the platform default isn't installed."""990 pager_out = tmp_path / "pager_out.txt"991992 monkeypatch.delitem(click._termui_impl.os.environ, "PAGER", raising=False)993 monkeypatch.delitem(click._termui_impl.os.environ, "TERM", raising=False)994 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)995 monkeypatch.setattr(shutil, "which", lambda _name: None)996997 with pager_out.open("w", encoding="utf-8") as text_stream:998 monkeypatch.setattr(999 click._termui_impl, "_default_text_stdout", lambda: text_stream1000 )10011002 with click.get_pager_file() as pager:1003 pager.write("hello\n")10041005 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 1006–1060why, one step back
1006
10071008def test_get_pager_file_missing_pager_keeps_borrowed_stream_open(monkeypatch):1009 """A missing ``PAGER`` must not close the borrowed stdout (issue #3449).10101011 The ``8.4.0`` regression was only fixed for the no-tty ``_nullpager`` path;1012 the ``_pipepager``/``_tempfilepager`` fallbacks (reached in a tty when1013 ``PAGER`` resolves to nothing) used to close the borrowed stream too.1014 """1015 buffer = io.BytesIO()1016 stream = io.TextIOWrapper(buffer, encoding="utf-8")10171018 monkeypatch.setitem(1019 click._termui_impl.os.environ,1020 "PAGER",1021 "click-tests-nonexistent-pager-9b3f2",1022 )1023 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)1024 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)10251026 with click.get_pager_file() as pager:1027 pager.write("hello\n")10281029 # Drop the wrapper reference and force finalization: the old bug closed the1030 # borrowed buffer when the TextIOWrapper built by get_pager_file was1031 # garbage-collected.1032 del pager1033 gc.collect()10341035 assert not buffer.closed1036 assert not stream.closed1037 assert buffer.getvalue().replace(b"\r\n", b"\n") == b"hello\n"103810391040def test_echo_via_pager_tty_pager_missing(runner, monkeypatch):1041 """``echo_via_pager`` through the tty fallback keeps ``CliRunner`` working.10421043 Regression for issue #3449 via the pager fallback: a tty with ``PAGER``1044 pointing at a missing binary used to close the runner's stdout, breaking1045 ``CliRunner.invoke``.1046 """1047 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)1048 monkeypatch.setitem(1049 click._termui_impl.os.environ,1050 "PAGER",1051 "click-tests-nonexistent-pager-9b3f2",1052 )10531054 @click.command()1055 def cli():1056 click.echo_via_pager("Hello, Click!")10571058 result = runner.invoke(cli)1059 assert not result.exception1060 assert result.output == "Hello, Click!\n"

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 1061–1072why, one step back
1061
10621063@pytest.mark.parametrize(1064 ("color", "expected"),1065 [1066 pytest.param(False, "hello\n", id="strip ansi"),1067 pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),1068 ],1069)1070def test_get_pager_file_nullpager_wraps_textio_stream(1071 monkeypatch, tmp_path, color, expected1072):

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

lines 1073–1074why, one step back
1073 """When paging falls back to a real text stream, ANSI styling is stripped or
1074 preserved according to ``color``."""

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 1075–1091why, one step back
1075 pager_out = tmp_path / "pager_out.txt"
10761077 with pager_out.open("w", encoding="utf-8") as text_stream:1078 monkeypatch.setattr(1079 click._termui_impl, "_default_text_stdout", lambda: text_stream1080 )1081 monkeypatch.setattr(1082 click._termui_impl, "isatty", lambda stream: stream is not sys.stdin1083 )10841085 with click.get_pager_file(color=color) as pager:1086 pager.write(click.style("hello", fg="red") + "\n")10871088 assert pager_out.read_text(encoding="utf-8") == expected108910901091def test_get_pager_file_nullpager_keeps_stringio_stream(monkeypatch):

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

line 1092why, one step back
1092 """The no-stdout fallback keeps the text stream open and strips ANSI."""

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 1093why, one step back
1093

Merge branch 'stable'David Lordbefore adoptionbc36cd1

line 1094why, one step back
1094 stream = io.StringIO()

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 1095why, one step back
1095 monkeypatch.setattr(sys, "stdout", None)

Merge branch 'stable'David Lordbefore adoptionbc36cd1

line 1096why, one step back
1096 monkeypatch.setattr(click._termui_impl, "StringIO", lambda: stream)

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 1097–1099why, one step back
1097 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)
10981099 with click.get_pager_file(color=False) as pager:

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

line 1100why, one step back
1100 pager.write(click.style("hello", fg="red"))

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

line 1101why, one step back
1101

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

line 1102why, one step back
1102 # The wrapper must not close a stream it does not own.

Merge branch 'stable'David Lordbefore adoptionbc36cd1

line 1103why, one step back
1103 assert not stream.closed

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

lines 1104–1105why, one step back
1104 # With colors disabled, ANSI styling is stripped.
1105 assert stream.getvalue() == "hello"

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 1106–1122why, one step back
1106
11071108def test_get_pager_file_flushes_stream_on_exception(monkeypatch):1109 """Exceptions should still flush the yielded stream in ``finally``."""11101111 class FlushableTextStream(io.StringIO):1112 def __init__(self):1113 super().__init__()1114 self.flush_calls = 011151116 def flush(self):1117 self.flush_calls += 111181119 stream = FlushableTextStream()11201121 @contextlib.contextmanager1122 def pager_contextmanager(color=None):

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

line 1123why, one step back
1123 yield stream, False

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 1124–1130why, one step back
1124
1125 monkeypatch.setattr(1126 click._termui_impl, "_pager_contextmanager", pager_contextmanager1127 )11281129 with pytest.raises(RuntimeError, match="boom"):1130 with click.get_pager_file() as pager:

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

line 1131why, one step back
1131 pager.write("partial")

`click.get_pager_file`: add tests (#1572 followup) (#3405)Rowlando13before adoption63274a7

lines 1132–1134why, one step back
1132 raise RuntimeError("boom")
11331134 assert stream.flush_calls == 1

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

line 1135why, one step back
1135 assert stream.getvalue() == "partial"

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

lines 1136–1137why, one step back
1136
1137

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

lines 1138–1169why, one step back
1138def test_get_pager_file_close_does_not_close_borrowed_stream(monkeypatch):
1139 """Closing the yielded pager must not close a stream the caller owns.11401141 ``_PagerWriter.close()`` flushes but deliberately stops there: each pager1142 strategy owns its stream's lifecycle. This is the caller-driven half of1143 ``test_get_pager_file_missing_pager_keeps_borrowed_stream_open``, which1144 covers the same fallback but never calls ``close`` itself.11451146 Wrapping the borrowed stream in :class:`~click.utils._KeepOpenFile` does not1147 satisfy this: that proxy only covers a ``with`` block and passes an explicit1148 ``close`` straight through. Only the writer's own ``close`` stops it.1149 """1150 stream = io.StringIO()1151 monkeypatch.setattr(click._termui_impl, "_default_text_stdout", lambda: stream)1152 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)1153 # A tty plus a ``PAGER`` that doesn't resolve sends us through the1154 # ``_pipepager`` (or ``_tempfilepager``) missing-binary fallback branch.1155 monkeypatch.setitem(1156 click._termui_impl.os.environ,1157 "PAGER",1158 "click-tests-nonexistent-pager-9b3f2",1159 )11601161 with click.get_pager_file() as pager:1162 pager.write("hello\n")1163 pager.close()1164 assert not stream.closed11651166 assert not stream.closed1167 assert stream.getvalue() == "hello\n"11681169

Changed `tempfile.NamedTemporaryFile` mode to `w` (#3739)Rowlando13before adoption8b44edf

lines 1170–1174why, one step back
1170def _force_tempfile_pager(monkeypatch, pager_cmd="cat"):
1171 """Route ``get_pager_file`` through the ``_tempfilepager`` backend.11721173 That backend is only reachable on Windows, so the platform flag and the tty1174 probes are faked to exercise it from any runner.

Fix error reporting on Windows when an error is raised in the pager (#3764)Rowlando13before adoptionfc5c7f4

lines 1175–1180why, one step back
1175
1176 ``PAGER`` is set to the bare command name, not to the path1177 :func:`shutil.which` resolves it to. ``pager()`` splits ``PAGER`` with1178 :func:`shlex.split` in POSIX mode, where a Windows path loses its1179 backslashes and splits on the space in ``C:\\Program Files``, leaving a1180 command that resolves to nothing. Click resolves the bare name itself.

Changed `tempfile.NamedTemporaryFile` mode to `w` (#3739)Rowlando13before adoption8b44edf

line 1181why, one step back
1181 """

Forward all user's parameters set in `PAGER` and improve flag detection (#3777)Rowlando13before adoption2103e15

lines 1182–1183why, one step back
1182 cmd = shlex.split(pager_cmd)[0]
1183 assert shutil.which(cmd) is not None, f"{cmd} not available"

Changed `tempfile.NamedTemporaryFile` mode to `w` (#3739)Rowlando13before adoption8b44edf

lines 1184–1185why, one step back
1184 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
1185 monkeypatch.setattr(click._termui_impl, "WIN", True)

Fix error reporting on Windows when an error is raised in the pager (#3764)Rowlando13before adoptionfc5c7f4

line 1186why, one step back
1186 monkeypatch.setitem(click._termui_impl.os.environ, "PAGER", pager_cmd)

Changed `tempfile.NamedTemporaryFile` mode to `w` (#3739)Rowlando13before adoption8b44edf

lines 1187–1208why, one step back
1187
11881189def _page_with_get_pager_file():1190 with click.get_pager_file() as pager:1191 pager.write("hello\n")119211931194def _page_with_echo_via_pager():1195 click.echo_via_pager("hello")119611971198@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1199@pytest.mark.parametrize(1200 "page",1201 [1202 pytest.param(_page_with_get_pager_file, id="get_pager_file"),1203 pytest.param(_page_with_echo_via_pager, id="echo_via_pager"),1204 ],1205)1206def test_tempfile_pager_accepts_text(monkeypatch, capfd, page):1207 """The temp file backend must yield a text stream (issues #3731, #3740).1208

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

lines 1209–1211why, one step back
1209 Regression: a binary-mode temp file handed straight to ``get_pager_file``
1210 left the caller writing ``str`` to a binary handle, which raises1211 ``TypeError: a bytes-like object is required``.

Changed `tempfile.NamedTemporaryFile` mode to `w` (#3739)Rowlando13before adoption8b44edf

lines 1212–1232why, one step back
1212 """
1213 _force_tempfile_pager(monkeypatch)12141215 page()12161217 out, err = capfd.readouterr()1218 assert err == ""1219 assert out.replace("\r\n", "\n") == "hello\n"122012211222@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1223@pytest.mark.parametrize(1224 ("color", "expected"),1225 [1226 pytest.param(False, "hello\n", id="strip ansi"),1227 pytest.param(True, click.style("hello", fg="red") + "\n", id="preserve ansi"),1228 ],1229)1230def test_tempfile_pager_handles_ansi(monkeypatch, capfd, color, expected):1231 """The temp file backend honors ``color`` like the pipe backend does.1232

Refactor pager stream handling (#3767)Rowlando13before adoptionf36d58b

lines 1233–1234why, one step back
1233 Regression: a binary temp file got no ANSI-stripping wrapper, so ``color``
1234 was silently ignored on this path.

Changed `tempfile.NamedTemporaryFile` mode to `w` (#3739)Rowlando13before adoption8b44edf

lines 1235–1242why, one step back
1235 """
1236 _force_tempfile_pager(monkeypatch)12371238 click.echo_via_pager(click.style("hello", fg="red"), color=color)12391240 out, err = capfd.readouterr()1241 assert err == ""1242 assert out.replace("\r\n", "\n") == expected

Forward all user's parameters set in `PAGER` and improve flag detection (#3777)Rowlando13before adoption2103e15

lines 1243–1258why, one step back
1243
12441245@pytest.mark.skipif(shutil.which("head") is None, reason="head not available")1246def test_tempfile_pager_passes_pager_params(monkeypatch, capfd):1247 """The temp file backend forwards ``PAGER`` parameters to the command.12481249 ``head -n 1`` renders one line out of two when the ``-n 1`` reaches the1250 command.1251 """1252 _force_tempfile_pager(monkeypatch, pager_cmd="head -n 1")12531254 click.echo_via_pager("line one\nline two\n")12551256 out, err = capfd.readouterr()1257 assert err == ""1258 assert out.replace("\r\n", "\n") == "line one\n"

Fix error reporting on Windows when an error is raised in the pager (#3764)Rowlando13before adoptionfc5c7f4

lines 1259–1308why, one step back
1259
12601261@pytest.mark.skipif(shutil.which("cat") is None, reason="cat not available")1262def test_tempfile_pager_closes_file_before_unlink(monkeypatch):1263 """An error while paging must not leave the temp file open at unlink time.12641265 The ``f.close()`` on the success path sits after the ``yield``, so an1266 exception raised while the pager is open used to skip it and reach1267 ``finally: os.unlink(f.name)`` with the handle still open. Windows refuses1268 to unlink an open file, so ``PermissionError: [WinError 32]`` replaced the1269 original error and hid it (issue #3731).1270 """1271 _force_tempfile_pager(monkeypatch)12721273 temp_files = []1274 real_named_temporary_file = tempfile.NamedTemporaryFile12751276 def record(*args, **kwargs):1277 f = real_named_temporary_file(*args, **kwargs)1278 temp_files.append(f)1279 return f12801281 monkeypatch.setattr(tempfile, "NamedTemporaryFile", record)12821283 closed_at_unlink = []1284 real_unlink = os.unlink12851286 def spy_unlink(path, **kwargs):1287 closed_at_unlink.append([f.closed for f in temp_files])1288 return real_unlink(path, **kwargs)12891290 monkeypatch.setattr(os, "unlink", spy_unlink)12911292 try:1293 with pytest.raises(RuntimeError, match="boom"):1294 with click.get_pager_file():1295 raise RuntimeError("boom")1296 finally:1297 # Should this invariant regress, the assertion below reports it. Close1298 # the handle anyway so the leak does not also resurface as a1299 # ResourceWarning charged to an unrelated test.1300 for f in temp_files:1301 if not f.closed:1302 f.close()13031304 assert temp_files, "the temp file pager backend was not used"1305 assert closed_at_unlink == [[True]], (1306 "temp file still open when unlink ran; on Windows this raises "1307 "PermissionError [WinError 32] and masks the real error"1308 )

Changed `tempfile.NamedTemporaryFile` mode to `w` (#3739)Rowlando13before adoption8b44edf

lines 1309–1310why, one step back
1309
1310

Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351

lines 1311–1314why, one step back
1311def test_editor_unclosed_quote():
1312 """An unclosed quote in the editor command raises ValueError."""1313 with pytest.raises(ValueError, match="No closing quotation"):1314 Editor(editor='"unclosed').edit_files(["f.txt"])

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 1315–1372why, one step back
1315
13161317@pytest.mark.parametrize(1318 ("prompt_required", "required", "args", "expect"),1319 [1320 (True, False, None, "prompt"),1321 (True, False, ["-v"], "Option '-v' requires an argument."),1322 (False, True, None, "prompt"),1323 (False, True, ["-v"], "prompt"),1324 ],1325)1326def test_prompt_required_with_required(runner, prompt_required, required, args, expect):1327 @click.command()1328 @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)1329 def cli(v):1330 click.echo(str(v))13311332 result = runner.invoke(cli, args, input="prompt")1333 assert expect in result.output133413351336@pytest.mark.parametrize(1337 ("args", "expect"),1338 [1339 # Flag not passed, don't prompt.1340 pytest.param(None, None, id="no flag"),1341 # Flag and value passed, don't prompt.1342 pytest.param(["-v", "value"], "value", id="short sep value"),1343 pytest.param(["--value", "value"], "value", id="long sep value"),1344 pytest.param(["-vvalue"], "value", id="short join value"),1345 pytest.param(["--value=value"], "value", id="long join value"),1346 # Flag without value passed, prompt.1347 pytest.param(["-v"], "prompt", id="short no value"),1348 pytest.param(["--value"], "prompt", id="long no value"),1349 # Don't use next option flag as value.1350 pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),1351 ],1352)1353def test_prompt_required_false(runner, args, expect):1354 @click.command()1355 @click.option("-v", "--value", prompt=True, prompt_required=False)1356 @click.option("-o")1357 def cli(value, o):1358 if o is not None:1359 return value, o13601361 return value13621363 result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)1364 assert result.exception is None1365 assert result.return_value == expect136613671368@pytest.mark.parametrize(1369 ("prompt", "input", "default", "expect"),1370 [1371 (True, "password\npassword", None, "password"),1372 ("Confirm Password", "password\npassword\n", None, "password"),

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

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

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 1374–1396why, one step back
1374 (False, None, None, None),
1375 ],1376)1377def test_confirmation_prompt(runner, prompt, input, default, expect):1378 @click.command()1379 @click.option(1380 "--password",1381 prompt=prompt,1382 hide_input=True,1383 default=default,1384 confirmation_prompt=prompt,1385 )1386 def cli(password):1387 return password13881389 result = runner.invoke(cli, input=input, standalone_mode=False)1390 assert result.exception is None1391 assert result.return_value == expect13921393 if prompt == "Confirm Password":1394 assert "Confirm Password: " in result.output13951396

Strip ANSI from `confirm()` and `prompt()` (#3653)Rowlando13before adoptionfe3ad76

lines 1397–1446why, one step back
1397@pytest.mark.parametrize(
1398 ("call", "user_input", "color", "expect"),1399 [1400 pytest.param(1401 lambda: click.confirm(click.style("Hello World!", fg="green")),1402 "y",1403 False,1404 "Hello World! [y/N]: y\n",1405 id="confirm-no-color",1406 ),1407 pytest.param(1408 lambda: click.confirm(click.style("Hello World!", fg="green")),1409 "y",1410 True,1411 "\x1b[32mHello World!\x1b[0m [y/N]: y\n",1412 id="confirm-color",1413 ),1414 pytest.param(1415 lambda: click.prompt(click.style("Name", fg="green")),1416 "Bob",1417 False,1418 "Name: Bob\n",1419 id="prompt-no-color",1420 ),1421 pytest.param(1422 lambda: click.prompt(click.style("Name", fg="green")),1423 "Bob",1424 True,1425 "\x1b[32mName\x1b[0m: Bob\n",1426 id="prompt-color",1427 ),1428 ],1429)1430def test_prompt_and_confirm_ansi_respects_color(1431 runner, call, user_input, color, expect1432):1433 """``confirm`` and ``prompt`` strip ANSI color and style codes from the1434 prompt when color is disabled and keep them when it is enabled, like1435 ``echo``. The prompt is written by ``input`` rather than ``echo``, so it1436 used to keep the codes regardless (issue 3572).1437 """14381439 @click.command()1440 def cli():1441 call()14421443 result = runner.invoke(cli, input=user_input, color=color)1444 assert result.output == expect14451446

Make faqs section. Add the first question about windows shell expansion. (#2927)Rowlando13before adoption9ce34f2

lines 1447–1456why, one step back
1447def test_false_show_default_cause_no_default_display_in_prompt(runner):
1448 @click.command()1449 @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")1450 def cmd(arg1):1451 pass14521453 # Confirm that the default value is not included in the output when `show_default`1454 # is False1455 result = runner.invoke(cmd, input="my-input", standalone_mode=False)1456 assert "my-default-value" not in result.output

Show default string in prompt (#3328)Rowlando13before adoption76552ff

lines 1457–1508why, one step back
1457
14581459@pytest.mark.parametrize(1460 ("show_default", "default", "user_input", "in_prompt", "not_in_prompt"),1461 [1462 # Regular string replaces the actual default in the prompt.1463 ("custom", "actual", "\n", "(custom)", "actual"),1464 # String with spaces.1465 ("custom label", "actual", "\n", "(custom label)", "actual"),1466 # Unicode characters.1467 ("∞", "0", "\n", "(∞)", None),1468 # Numeric default: custom string hides the number.1469 ("unlimited", 42, "\n", "(unlimited)", "42"),1470 # Explicit default=None: custom string still appears, must provide input.1471 ("computed at runtime", None, "value\n", "(computed at runtime)", None),1472 # No default kwarg at all (internal UNSET sentinel): same as None.1473 ("computed at runtime", UNSET, "value\n", "(computed at runtime)", None),1474 # Empty string is falsy: suppresses any default display.1475 ("", "actual", "\n", None, "actual"),1476 ],1477 ids=[1478 "simple-string",1479 "string-with-spaces",1480 "unicode",1481 "numeric-default",1482 "default-is-none",1483 "default-is-unset",1484 "empty-string-is-falsy",1485 ],1486)1487def test_string_show_default_in_prompt(1488 runner, show_default, default, user_input, in_prompt, not_in_prompt1489):1490 """When show_default is a string, the prompt should display that1491 string in parentheses instead of the actual default value,1492 matching the help text behavior. See pallets/click#2836."""14931494 option_kwargs = {"show_default": show_default, "prompt": True}1495 if default is not UNSET:1496 option_kwargs["default"] = default14971498 @click.command()1499 @click.option("--arg1", **option_kwargs)1500 def cmd(arg1):1501 click.echo(arg1)15021503 result = runner.invoke(cmd, input=user_input, standalone_mode=False)1504 prompt_line = result.output.split("\n")[0]1505 if in_prompt is not None:1506 assert in_prompt in prompt_line1507 if not_in_prompt is not None:1508 assert not_in_prompt not in prompt_line

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 1509–1618why, one step back
1509
15101511REPEAT = object()1512"""Sentinel value to indicate that the prompt is expected to be repeated.15131514I.e. the value provided by the user is not satisfactory and need to be re-prompted.1515"""15161517INVALID = object()1518"""Sentinel value to indicate that the prompt is expected to be invalid.15191520On invalid input, Click will output an error message and re-prompt the user.1521"""15221523BOOLEAN_FLAG_PROMPT_CASES = [1524 ###1525 ### Test cases with prompt=True explicitly enabled for the flag.1526 ###1527 # Prompt is allowed and the flag has no default, so it prompts.1528 ({"prompt": True}, [], "[y/N]", "y", True),1529 ({"prompt": True}, [], "[y/N]", "n", False),1530 # Empty input default to False.1531 ({"prompt": True}, [], "[y/N]", "", False),1532 # Changing the default to True, makes the prompt change to [Y/n].1533 ({"prompt": True, "default": True}, [], "[Y/n]", "", True),1534 ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),1535 ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),1536 # False is the default's default, so it prompts with [y/N].1537 ({"prompt": True, "default": False}, [], "[y/N]", "", False),1538 ({"prompt": True, "default": False}, [], "[y/N]", "y", True),1539 ({"prompt": True, "default": False}, [], "[y/N]", "n", False),1540 # Defaulting to None, prompts with [y/n], which makes the user explicitly choose1541 # between True or False.1542 ({"prompt": True, "default": None}, [], "[y/n]", "y", True),1543 ({"prompt": True, "default": None}, [], "[y/n]", "n", False),1544 # Random string default is treated as a truthy value, so it prompts with [Y/n].1545 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),1546 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),1547 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),1548 ###1549 ### Test cases with required=True explicitly enabled for the flag.1550 ###1551 # A required flag just raises an error unless a default is set.1552 ({"required": True}, [], None, None, MissingParameter),1553 ({"required": True, "default": True}, [], None, None, True),1554 ({"required": True, "default": False}, [], None, None, False),1555 ({"required": True, "default": None}, [], None, None, None),1556 ({"required": True, "default": "on"}, [], None, None, True),1557 ({"required": True, "default": "off"}, [], None, None, False),1558 ({"required": True, "default": "foo"}, [], None, None, BadParameter),1559 ###1560 ### Explicitly passing the flag to the CLI bypass any prompt, whatever the1561 ### configuration of the flag.1562 ###1563 # Flag allowing a prompt.1564 ({"prompt": True}, ["--flag"], None, None, True),1565 ({"prompt": True}, ["--no-flag"], None, None, False),1566 ({"prompt": True, "default": None}, ["--flag"], None, None, True),1567 ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),1568 ({"prompt": True, "default": True}, ["--flag"], None, None, True),1569 ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),1570 ({"prompt": True, "default": False}, ["--flag"], None, None, True),1571 ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),1572 ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),1573 ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),1574 # Required flag.1575 ({"required": True}, ["--flag"], None, None, True),1576 ({"required": True}, ["--no-flag"], None, None, False),1577 ({"required": True, "default": None}, ["--flag"], None, None, True),1578 ({"required": True, "default": None}, ["--no-flag"], None, None, False),1579 ({"required": True, "default": True}, ["--flag"], None, None, True),1580 ({"required": True, "default": True}, ["--no-flag"], None, None, False),1581 ({"required": True, "default": False}, ["--flag"], None, None, True),1582 ({"required": True, "default": False}, ["--no-flag"], None, None, False),1583 ({"required": True, "default": "foo"}, ["--flag"], None, None, True),1584 ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),1585]15861587FLAG_VALUE_PROMPT_CASES = [1588 ###1589 ### Test cases with prompt=True explicitly enabled for the flag.1590 ###1591 # Prompt is allowed and the flag has no default, so it prompts.1592 # But the flag_value is not set, so it defaults to a string.1593 ({"prompt": True}, [], "", "", REPEAT),1594 ({"prompt": True}, [], "", "y", "y"),1595 ({"prompt": True}, [], "", "n", "n"),1596 ({"prompt": True}, [], "", "foo", "foo"),1597 # This time we provide a boolean flag_value, which makes the flag behave like a1598 # boolean flag, and use the appropriate variation of [y/n].1599 ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),1600 ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),1601 ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),1602 ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),1603 ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),1604 ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),1605 # Other flag values changes the auto-detection of the flag type.1606 ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),1607 ({"prompt": True, "flag_value": None}, [], "", "y", "y"),1608 ({"prompt": True, "flag_value": None}, [], "", "n", "n"),1609 ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),1610 ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),1611 ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),1612 ###1613 ### Test cases with a flag_value and a default.1614 ###1615 # default=True1616 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),1617 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),1618 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),

Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73

lines 1619–1625why, one step back
1619 # For boolean flags, default=True is a literal value, not a sentinel meaning
1620 # "activate flag", so the prompt shows [Y/n] with default=True. See:1621 # https://github.com/pallets/click/issues/31111622 # https://github.com/pallets/click/pull/32391623 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),1624 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),1625 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),

Merge branch 'main' into stableDavid Lordbefore adoption81a482f

lines 1626–1728why, one step back
1626 # default=False
1627 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),1628 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),1629 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),1630 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),1631 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),1632 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),1633 # default=None1634 (1635 {"prompt": True, "default": None, "flag_value": True},1636 [],1637 "[y/n]",1638 "",1639 INVALID,1640 ),1641 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),1642 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),1643 (1644 {"prompt": True, "default": None, "flag_value": False},1645 [],1646 "[y/n]",1647 "",1648 INVALID,1649 ),1650 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),1651 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),1652 # If the flag_value is None, the flag behave like a string flag, whatever the1653 # default is.1654 ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),1655 ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),1656 ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),1657 (1658 {"prompt": True, "default": False, "flag_value": None},1659 [],1660 "[False]",1661 "",1662 "False",1663 ),1664 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),1665 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),1666 ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),1667 ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),1668 ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),1669]167016711672@pytest.mark.parametrize(1673 ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),1674 # Boolean flag prompt cases.1675 [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]1676 # Non-boolean flag prompt cases.1677 + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],1678)1679def test_flag_value_prompt(1680 runner, opt_decls, opt_params, args, prompt, input, expected1681):1682 """Check how flag value are prompted and handled by all combinations of1683 ``prompt``, ``default``, and ``flag_value`` parameters.16841685 Covers concerns raised in issue https://github.com/pallets/click/issues/1992.1686 """16871688 @click.command()1689 @click.option(opt_decls, **opt_params)1690 def cli(flag):1691 click.echo(repr(flag))16921693 invoke_options = {"standalone_mode": False}1694 if input is not None:1695 assert isinstance(input, str)1696 invoke_options["input"] = f"{input}\n"16971698 result = runner.invoke(cli, args, **invoke_options)16991700 if expected in (MissingParameter, BadParameter):1701 assert isinstance(result.exception, expected)1702 assert not result.output1703 assert result.exit_code == 117041705 else:1706 expected_output = ""1707 if prompt is not None:1708 # Build the expected prompt.1709 assert isinstance(prompt, str)1710 expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "17111712 # Add the user input to the expected output.1713 assert isinstance(input, str)1714 expected_output += f"{expected_prompt}{input}\n"17151716 if expected is INVALID:1717 expected_output += "Error: invalid input\n"17181719 # The prompt is expected to be repeated.1720 if expected in (REPEAT, INVALID):1721 expected_output += expected_prompt17221723 if expected not in (REPEAT, INVALID):1724 expected_output += f"{expected!r}\n"17251726 assert result.output == expected_output1727 assert not result.stderr1728 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1

Show custom error message in prompt with `hide_input=True` (#3256)Rowlando13before adoptionc943271

lines 1729–1984why, one step back
1729
17301731class _CustomTypeNoValue(click.ParamType):1732 name = "custom"17331734 def convert(self, value, param, ctx):1735 if len(value) < 4:1736 self.fail("Password must be at least 4 characters", param, ctx)1737 return value173817391740class _CustomTypeWithRawValue(click.ParamType):1741 name = "custom_raw"17421743 def convert(self, value, param, ctx):1744 if value == "bad":1745 self.fail(f"rejected: {value}", param, ctx)1746 return value174717481749class _PasswordLengthType(click.ParamType):1750 """Mirrors the issue's original use case: a password validator1751 that references the user-typed value in its error message without1752 quoting it.1753 """17541755 name = "password"17561757 def convert(self, value, param, ctx):1758 if len(value) < 10:1759 self.fail(f"{value} is too short", param, ctx)1760 return value176117621763class _MixedQuotedAndRawType(click.ParamType):1764 """Custom type that mentions the user input both quoted (built-in1765 pattern) and raw within the same message.1766 """17671768 name = "mixed"17691770 def convert(self, value, param, ctx):1771 self.fail(f"got {value!r} which is the same as {value}", param, ctx)177217731774class _StaticMessageType(click.ParamType):1775 """Custom type whose error message never references the value."""17761777 name = "static"17781779 def convert(self, value, param, ctx):1780 self.fail("Authentication failed for this account", param, ctx)178117821783class _RejectAllRawType(click.ParamType):1784 """Always rejects, with the raw value (unquoted) in the message."""17851786 name = "reject_all_raw"17871788 def convert(self, value, param, ctx):1789 self.fail(f"rejected: {value}", param, ctx)179017911792class _MultiRawType(click.ParamType):1793 """Mentions the raw value multiple times in the same message."""17941795 name = "multi_raw"17961797 def convert(self, value, param, ctx):1798 self.fail(f"got {value} but {value} is bad", param, ctx)179918001801class _MultiReprType(click.ParamType):1802 """Mentions ``repr(value)`` multiple times in the same message."""18031804 name = "multi_repr"18051806 def convert(self, value, param, ctx):1807 self.fail(f"got {value!r} and {value!r}", param, ctx)180818091810class _ApostropheReprType(click.ParamType):1811 """Custom type whose ``repr(value)`` switches to double quotes when1812 the value itself contains a single quote.1813 """18141815 name = "apostrophe_repr"18161817 def convert(self, value, param, ctx):1818 self.fail(f"rejected {value!r}", param, ctx)181918201821@pytest.mark.parametrize(1822 ("type", "user_input", "expected_fragment", "unexpected_fragment"),1823 [1824 pytest.param(1825 click.INT,1826 "bad",1827 "'***' is not a valid integer",1828 "bad",1829 id="builtin-int-masks-repr-value",1830 ),1831 pytest.param(1832 _CustomTypeNoValue(),1833 "bad",1834 "Password must be at least 4 characters",1835 None,1836 id="custom-no-value-shows-message",1837 ),1838 pytest.param(1839 _CustomTypeWithRawValue(),1840 "bad",1841 "rejected: '***'",1842 "bad",1843 id="custom-raw-value-masked",1844 ),1845 pytest.param(1846 _PasswordLengthType(),1847 "PASSWORD",1848 "'***' is too short",1849 "PASSWORD",1850 id="unquoted-custom-message-should-mask-not-fallback",1851 ),1852 pytest.param(1853 _MixedQuotedAndRawType(),1854 "leakybits",1855 "got '***' which is the same as '***'",1856 "leakybits",1857 id="mixed-quoted-and-raw-both-masked-at-source",1858 ),1859 pytest.param(1860 click.IntRange(min=10, max=99),1861 "1",1862 "is not in the range",1863 None,1864 id="intrange-numeric-substring-falls-back-to-generic",1865 ),1866 pytest.param(1867 _StaticMessageType(),1868 "ent",1869 "Authentication failed for this account",1870 None,1871 id="partial-word-match-falls-back-to-generic",1872 ),1873 # When the raw (unquoted) value appears in the message, mask it instead1874 # of replacing the whole message with a generic fallback that throws1875 # useful information away.1876 pytest.param(1877 _RejectAllRawType(),1878 "secret",1879 "rejected: '***'",1880 "secret",1881 id="raw-value-should-be-masked-not-fallback",1882 ),1883 # When the raw value occurs more than1884 # once unquoted, every occurrence must be masked.1885 pytest.param(1886 _MultiRawType(),1887 "secret",1888 "got '***' but '***' is bad",1889 "secret",1890 id="multi-occurrence-raw-mask-all",1891 ),1892 pytest.param(1893 _MultiReprType(),1894 "secret",1895 "got '***' and '***'",1896 "secret",1897 id="multi-occurrence-repr-mask-all",1898 ),1899 pytest.param(1900 _PasswordLengthType(),1901 "a.b*c+",1902 "'***' is too short",1903 "a.b*c+",1904 id="regex-special-chars-must-be-escaped",1905 ),1906 pytest.param(1907 _PasswordLengthType(),1908 "пароль",1909 "'***' is too short",1910 "пароль",1911 id="unicode-value-masked",1912 ),1913 pytest.param(1914 _ApostropheReprType(),1915 "it's",1916 "rejected '***'",1917 "it's",1918 id="apostrophe-in-value-uses-double-quote-repr",1919 ),1920 pytest.param(1921 _MixedQuotedAndRawType(),1922 "leakybits",1923 "got '***' which is the same as '***'",1924 "leakybits",1925 id="mixed-quoted-and-raw-mask-both",1926 ),1927 ],1928)1929def test_hide_input_error_message(1930 runner, type, user_input, expected_fragment, unexpected_fragment1931):1932 """https://github.com/pallets/click/issues/2809"""19331934 @click.command()1935 @click.option("--password", prompt=True, hide_input=True, type=type)1936 def cli(password):1937 click.echo(password)19381939 result = runner.invoke(cli, input=user_input)1940 assert expected_fragment in result.output1941 if unexpected_fragment is not None:1942 assert unexpected_fragment not in result.output194319441945def test_hide_input_confirmation_prompt_mismatch_unaffected(runner):1946 """The ``hide_input`` mask logic only applies to ``value_proc``1947 failures. The separate ``confirmation_prompt`` mismatch path must1948 keep emitting its own message, with no value leak from either entry.1949 """19501951 @click.command()1952 @click.option("--password", prompt=True, confirmation_prompt=True, hide_input=True)1953 def cli(password):1954 click.echo(f"got: {password}")19551956 # First pair mismatches, second pair matches.1957 result = runner.invoke(cli, input="firstone\nsecondone\nfinalone\nfinalone\n")1958 assert "Error: The two entered values do not match." in result.output1959 assert "firstone" not in result.output1960 assert "secondone" not in result.output1961 # Successful prompt echoes the final value back via the command body.1962 assert "got: finalone" in result.output1963 assert result.exit_code == 0196419651966def test_hide_input_value_never_leaks_when_err_true(runner):1967 """``click.prompt(..., err=True)`` routes its error message to1968 stderr. The masking logic must apply on that path too: the raw1969 input must not appear on either stream.1970 """19711972 @click.command()1973 def cli():1974 value = click.prompt(1975 "Password",1976 hide_input=True,1977 type=_PasswordLengthType(),1978 err=True,1979 )1980 click.echo(value)19811982 result = runner.invoke(cli, input="leaky\n", mix_stderr=False)1983 assert "leaky" not in result.stdout1984 assert "leaky" not in result.stderr