test_termui.py
This file
Path
tests/test_termui.py
990 lines · 35.6 KiB · Python
Last changed by
Show default string in prompt (#3328)Rowlando13before adoption76552ff
History of this fileTake it
The walk stopped after 200 commits: lines older than 388b0e1 point at it.
Bump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
line 1why, one step back1import platformPath normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 2why, one step back2import shlexAdds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
line 3why, one step back3import tempfileBump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
line 4why, one step back4import timeDocument and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
line 5why, one step back5from unittest.mock import patchBump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 6–10why, one step back67import pytest89import click._termui_impl10from click._compat import WINDocument and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
line 11why, one step back11from click._termui_impl import EditorShow default string in prompt (#3328)Rowlando13before adoption76552ff
line 12why, one step back12from click._utils import UNSETMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 13–14why, one step back13from click.exceptions import BadParameter14from click.exceptions import MissingParameterBump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 15–80why, one step back151617class FakeClock:18 def __init__(self):19 self.now = time.time()2021 def advance_time(self, seconds=1):22 self.now += seconds2324 def time(self):25 return self.now262728def _create_progress(length=10, **kwargs):29 progress = click.progressbar(tuple(range(length)))30 for key, value in kwargs.items():31 setattr(progress, key, value)32 return progress333435def test_progressbar_strip_regression(runner, monkeypatch):36 label = " padded line"3738 @click.command()39 def cli():40 with _create_progress(label=label) as progress:41 for _ in progress:42 pass4344 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)45 assert (46 label47 in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output48 )495051def test_progressbar_length_hint(runner, monkeypatch):52 class Hinted:53 def __init__(self, n):54 self.items = list(range(n))5556 def __length_hint__(self):57 return len(self.items)5859 def __iter__(self):60 return self6162 def __next__(self):63 if self.items:64 return self.items.pop()65 else:66 raise StopIteration6768 next = __next__6970 @click.command()71 def cli():72 with click.progressbar(Hinted(10), label="test") as progress:73 for _ in progress:74 pass7576 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)77 result = runner.invoke(cli, [])78 assert result.exception is None7980Add functionality to hide the progress bar #2609 (#2727)bhuffman-usgsbefore adoptionfcd8503
line 81why, one step back81def test_progressbar_no_tty(runner, monkeypatch):Bump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 82–89why, one step back82 @click.command()83 def cli():84 with _create_progress(label="working") as progress:85 for _ in progress:86 pass8788 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)89 assert runner.invoke(cli, []).output == "working\n"Add functionality to hide the progress bar #2609 (#2727)bhuffman-usgsbefore adoptionfcd8503
lines 90–100why, one step back909192def test_progressbar_hidden_manual(runner, monkeypatch):93 @click.command()94 def cli():95 with _create_progress(label="see nothing", hidden=True) as progress:96 for _ in progress:97 pass9899 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)100 assert runner.invoke(cli, []).output == ""Bump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 101–250why, one step back101102103@pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])104def test_progressbar_time_per_iteration(runner, avg, expected):105 with _create_progress(2, avg=avg) as progress:106 assert progress.time_per_iteration == expected107108109@pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])110def test_progressbar_eta(runner, finished, expected):111 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:112 assert progress.eta == expected113114115@pytest.mark.parametrize(116 "eta, expected",117 [118 (0, "00:00:00"),119 (30, "00:00:30"),120 (90, "00:01:30"),121 (900, "00:15:00"),122 (9000, "02:30:00"),123 (99999999999, "1157407d 09:46:39"),124 (None, ""),125 ],126)127def test_progressbar_format_eta(runner, eta, expected):128 with _create_progress(1, eta_known=eta is not None, avg=[eta]) as progress:129 assert progress.format_eta() == expected130131132@pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])133def test_progressbar_format_pos(runner, pos, length):134 with _create_progress(length, pos=pos) as progress:135 result = progress.format_pos()136 assert result == f"{pos}/{length}"137138139@pytest.mark.parametrize(140 "length, finished, pos, avg, expected",141 [142 (8, False, 7, 0, "#######-"),143 (0, True, 8, 0, "########"),144 ],145)146def test_progressbar_format_bar(runner, length, finished, pos, avg, expected):147 with _create_progress(148 length, width=8, pos=pos, finished=finished, avg=[avg]149 ) as progress:150 assert progress.format_bar() == expected151152153@pytest.mark.parametrize(154 "length, show_percent, show_pos, pos, expected",155 [156 (0, True, True, 0, " [--------] 0/0 0%"),157 (0, False, True, 0, " [--------] 0/0"),158 (0, False, False, 0, " [--------]"),159 (0, False, False, 0, " [--------]"),160 (8, True, True, 8, " [########] 8/8 100%"),161 ],162)163def test_progressbar_format_progress_line(164 runner, length, show_percent, show_pos, pos, expected165):166 with _create_progress(167 length,168 width=8,169 show_percent=show_percent,170 pos=pos,171 show_pos=show_pos,172 ) as progress:173 assert progress.format_progress_line() == expected174175176@pytest.mark.parametrize("test_item", ["test", None])177def test_progressbar_format_progress_line_with_show_func(runner, test_item):178 def item_show_func(item):179 return item180181 with _create_progress(182 item_show_func=item_show_func, current_item=test_item183 ) as progress:184 if test_item:185 assert progress.format_progress_line().endswith(test_item)186 else:187 assert progress.format_progress_line().endswith(progress.format_pct())188189190def test_progressbar_init_exceptions(runner):191 with pytest.raises(TypeError, match="iterable or length is required"):192 click.progressbar()193194195def test_progressbar_iter_outside_with_exceptions(runner):196 progress = click.progressbar(length=2)197198 with pytest.raises(RuntimeError, match="with block"):199 iter(progress)200201202def test_progressbar_is_iterator(runner, monkeypatch):203 @click.command()204 def cli():205 with click.progressbar(range(10), label="test") as progress:206 while True:207 try:208 next(progress)209 except StopIteration:210 break211212 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)213 result = runner.invoke(cli, [])214 assert result.exception is None215216217def test_choices_list_in_prompt(runner, monkeypatch):218 @click.command()219 @click.option(220 "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True221 )222 def cli_with_choices(g):223 pass224225 @click.command()226 @click.option(227 "-g",228 type=click.Choice(["none", "day", "week", "month"]),229 prompt=True,230 show_choices=False,231 )232 def cli_without_choices(g):233 pass234235 result = runner.invoke(cli_with_choices, [], input="none")236 assert "(none, day, week, month)" in result.output237238 result = runner.invoke(cli_without_choices, [], input="none")239 assert "(none, day, week, month)" not in result.output240241242@pytest.mark.parametrize(243 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]244)245def test_file_prompt_default_format(runner, file_kwargs):246 @click.command()247 @click.option("-f", default=__file__, prompt="file", type=click.File(**file_kwargs))248 def cli(f):249 click.echo(f.name)250Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0
line 251why, one step back251 result = runner.invoke(cli, input="\n")Bump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 252–266why, one step back252 assert result.output == f"file [{__file__}]: \n{__file__}\n"253254255def test_secho(runner):256 with runner.isolation() as outstreams:257 click.secho(None, nl=False)258 bytes = outstreams[0].getvalue()259 assert bytes == b""260261262@pytest.mark.skipif(platform.system() == "Windows", reason="No style on Windows.")263@pytest.mark.parametrize(264 ("value", "expect"), [(123, b"\x1b[45m123\x1b[0m"), (b"test", b"test")]265)266def test_secho_non_text(runner, value, expect):Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003
line 267why, one step back267 with runner.isolation() as (out, _, _):Bump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 268–387why, one step back268 click.secho(value, nl=False, color=True, bg="magenta")269 result = out.getvalue()270 assert result == expect271272273def test_progressbar_yields_all_items(runner):274 with click.progressbar(range(3)) as progress:275 assert len(list(progress)) == 3276277278def test_progressbar_update(runner, monkeypatch):279 fake_clock = FakeClock()280281 @click.command()282 def cli():283 with click.progressbar(range(4)) as progress:284 for _ in progress:285 fake_clock.advance_time()286 print("")287288 monkeypatch.setattr(time, "time", fake_clock.time)289 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)290 output = runner.invoke(cli, []).output291292 lines = [line for line in output.split("\n") if "[" in line]293294 assert " 0%" in lines[0]295 assert " 25% 00:00:03" in lines[1]296 assert " 50% 00:00:02" in lines[2]297 assert " 75% 00:00:01" in lines[3]298 assert "100% " in lines[4]299300301def test_progressbar_item_show_func(runner, monkeypatch):302 """item_show_func should show the current item being yielded."""303304 @click.command()305 def cli():306 with click.progressbar(range(3), item_show_func=lambda x: str(x)) as progress:307 for item in progress:308 click.echo(f" item {item}")309310 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)311 lines = runner.invoke(cli).output.splitlines()312313 for i, line in enumerate(x for x in lines if "item" in x):314 assert f"{i} item {i}" in line315316317def test_progressbar_update_with_item_show_func(runner, monkeypatch):318 @click.command()319 def cli():320 with click.progressbar(321 length=6, item_show_func=lambda x: f"Custom {x}"322 ) as progress:323 while not progress.finished:324 progress.update(2, progress.pos)325 click.echo()326327 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)328 output = runner.invoke(cli, []).output329330 lines = [line for line in output.split("\n") if "[" in line]331332 assert "Custom 0" in lines[0]333 assert "Custom 2" in lines[1]334 assert "Custom 4" in lines[2]335336337def test_progress_bar_update_min_steps(runner):338 bar = _create_progress(update_min_steps=5)339 bar.update(3)340 assert bar._completed_intervals == 3341 assert bar.pos == 0342 bar.update(2)343 assert bar._completed_intervals == 0344 assert bar.pos == 5345346347@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))348@pytest.mark.parametrize("echo", [True, False])349@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")350def test_getchar_windows(runner, monkeypatch, key_char, echo):351 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)352 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)353 monkeypatch.setattr(click.termui, "_getchar", None)354 assert click.getchar(echo) == key_char355356357@pytest.mark.parametrize(358 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]359)360@pytest.mark.skipif(361 not WIN, reason="Tests special character inputs using the msvcrt module."362)363def test_getchar_special_key_windows(runner, monkeypatch, special_key_char, key_char):364 ordered_inputs = [key_char, special_key_char]365 monkeypatch.setattr(366 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()367 )368 monkeypatch.setattr(click.termui, "_getchar", None)369 assert click.getchar() == f"{special_key_char}{key_char}"370371372@pytest.mark.parametrize(373 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)]374)375@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")376def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):377 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)378 monkeypatch.setattr(click.termui, "_getchar", None)379380 with pytest.raises(exc):381 click.getchar()382383384@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")385def test_fast_edit(runner):386 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")387 assert result == "aTest\nbTest\n"Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 388–392why, one step back388389390@pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")391def test_edit(runner):392 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:Fix test_edit to work with BSD sed (#3129)Rowlando13before adoptiona92c573
line 393why, one step back393 named_tempfile.write("a\nb\n")Adds support for editing multiple files (#2068)Yash Rathibefore adoption0d69b6c
lines 394–400why, one step back394 named_tempfile.flush()395396 result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")397 assert result is None398399 # We need ot reopen the file as it becomes unreadable after the edit.400 with open(named_tempfile.name) as reopened_file:Fix test_edit to work with BSD sed (#3129)Rowlando13before adoptiona92c573
lines 401–408why, one step back401 # POSIX says that when sed writes a pattern space to output then it402 # is immediately followed by a newline and so the expected result403 # should contain the newline. However, some sed implementations404 # (e.g. GNU sed) does not terminate the last line in the output405 # with the newline in a case the input data missed newline at the406 # end of last line. Hence the input data (see above) should be407 # terminated by newline too.408 assert reopened_file.read() == "aTest\nbTest\n"Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 409–430why, one step back409410411@pytest.mark.parametrize(412 ("editor_cmd", "filenames", "expected_args"),413 [414 pytest.param(415 "myeditor --wait --flag",416 ["file1.txt", "file2.txt"],417 ["myeditor", "--wait", "--flag", "file1.txt", "file2.txt"],418 id="editor with args",419 ),420 pytest.param(421 "vi",422 ['file"; rm -rf / ; echo "'],423 ["vi", 'file"; rm -rf / ; echo "'],424 id="shell metacharacters in filename",425 ),426 # Issue #1026: editor path with spaces must be quoted.427 pytest.param(428 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe"',429 ["f.txt"],430 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 431why, one step back431 id="quoted windows path with spaces",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 432–437why, one step back432 ),433 # PR #1477: pager/editor command with flags, like ``less -FRSX``.434 pytest.param(435 "less -FRSX",436 ["f.txt"],437 ["less", "-FRSX", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 438why, one step back438 id="command with flags",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 439–444why, one step back439 ),440 # Issue #1026: quoted command with ``--wait`` flag.441 pytest.param(442 '"my command" --option value arg',443 ["f.txt"],444 ["my command", "--option", "value", "arg", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 445why, one step back445 id="quoted command with args",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 446–458why, one step back446 ),447 # PR #1477: unquoted unix path.448 pytest.param(449 "/usr/bin/vim",450 ["f.txt"],451 ["/usr/bin/vim", "f.txt"],452 id="unix absolute path",453 ),454 # Issue #1026: macOS path with escaped space.455 pytest.param(456 "/Applications/Sublime\\ Text.app/Contents/SharedSupport/bin/subl",457 ["f.txt"],458 ["/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl", "f.txt"],Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
line 459why, one step back459 id="escaped space in unix path",Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
line 460why, one step back460 ),Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
lines 461–502why, one step back461 pytest.param(462 " vim ",463 ["f.txt"],464 ["vim", "f.txt"],465 id="leading and trailing whitespace",466 ),467 pytest.param(468 "vim\tf.txt",469 [],470 ["vim", "f.txt"],471 id="tab-separated tokens",472 ),473 pytest.param(474 "'/Applications/My Editor.app/Contents/MacOS/editor'",475 ["f.txt"],476 ["/Applications/My Editor.app/Contents/MacOS/editor", "f.txt"],477 id="single-quoted path with spaces",478 ),479 pytest.param(480 '"my editor" --wait --new-window',481 ["file 1.txt", "file 2.txt"],482 ["my editor", "--wait", "--new-window", "file 1.txt", "file 2.txt"],483 id="quoted editor with multiple flags and filenames with spaces",484 ),485 pytest.param(486 "vim -u NONE -N",487 ["f.txt"],488 ["vim", "-u", "NONE", "-N", "f.txt"],489 id="multiple short flags",490 ),491 pytest.param(492 "editor",493 ['file"name.txt'],494 ["editor", 'file"name.txt'],495 id="filename with double quote",496 ),497 pytest.param(498 "editor",499 ["file'name.txt"],500 ["editor", "file'name.txt"],501 id="filename with single quote",502 ),Document and fix command sanitizing with `shlex.split` (#3245)Rowlando13before adoption63ea71f
lines 503–564why, one step back503 ],504)505def test_editor_path_normalization(editor_cmd, filenames, expected_args):506 with patch("subprocess.Popen") as mock_popen:507 mock_popen.return_value.wait.return_value = 0508 Editor(editor=editor_cmd).edit_files(filenames)509510 mock_popen.assert_called_once()511 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]512 assert args == expected_args513 assert mock_popen.call_args[1].get("shell") is None514515516@pytest.mark.skipif(not WIN, reason="Windows-specific editor paths")517@pytest.mark.parametrize(518 ("editor_cmd", "expected_cmd"),519 [520 pytest.param(521 "notepad",522 ["notepad"],523 id="plain notepad",524 ),525 pytest.param(526 '"C:\\Program Files\\Sublime Text 3\\sublime_text.exe" --wait',527 ["C:\\Program Files\\Sublime Text 3\\sublime_text.exe", "--wait"],528 id="quoted path with flag",529 ),530 ],531)532def test_editor_windows_path_normalization(editor_cmd, expected_cmd):533 """Windows-specific tests: verify ``Popen`` receives unquoted paths that534 ``subprocess.list2cmdline`` can re-quote for ``CreateProcess``."""535 with patch("subprocess.Popen") as mock_popen:536 mock_popen.return_value.wait.return_value = 0537 Editor(editor=editor_cmd).edit_files(["f.txt"])538539 args = mock_popen.call_args[1].get("args") or mock_popen.call_args[0][0]540 assert args == expected_cmd + ["f.txt"]541 assert mock_popen.call_args[1].get("shell") is None542543544def test_editor_env_passed_through():545 with patch("subprocess.Popen") as mock_popen:546 mock_popen.return_value.wait.return_value = 0547 Editor(editor="vi", env={"MY_VAR": "1"}).edit_files(["f.txt"])548549 env = mock_popen.call_args[1].get("env")550 assert env is not None551 assert env["MY_VAR"] == "1"552553554def test_editor_failure_exception():555 with patch("subprocess.Popen") as mock_popen:556 mock_popen.return_value.wait.return_value = 1557 with pytest.raises(click.ClickException, match="Editing failed"):558 Editor(editor="vi").edit_files(["f.txt"])559560561def test_editor_nonexistent_exception():562 with patch("subprocess.Popen", side_effect=OSError("not found")):563 with pytest.raises(click.ClickException, match="not found"):564 Editor(editor="nonexistent").edit_files(["f.txt"])Path normalization documentation clean-up + `shlex.split` extensive tests (#3330)Rowlando13before adoption4529351
lines 565–626why, one step back565566567@pytest.mark.parametrize(568 ("pager_env", "expected_parts"),569 [570 # Simple commands.571 pytest.param("cat", ["cat"], id="simple command"),572 pytest.param("less", ["less"], id="less"),573 pytest.param("less -FRSX", ["less", "-FRSX"], id="command with flags"),574 # Whitespace handling.575 pytest.param("", [], id="empty string"),576 pytest.param(" ", [], id="whitespace only"),577 pytest.param(" less ", ["less"], id="leading and trailing spaces"),578 pytest.param("less\t-R", ["less", "-R"], id="tab as separator"),579 # Quoted Windows paths: quotes are stripped in POSIX mode (the580 # default), preserving backslashes inside quoted tokens (issue #1026).581 pytest.param(582 '"C:\\Program Files\\Git\\usr\\bin\\less.exe"',583 ["C:\\Program Files\\Git\\usr\\bin\\less.exe"],584 id="quoted windows path with spaces",585 ),586 pytest.param(587 '"C:\\Program Files\\Git\\usr\\bin\\less.exe" -R',588 ["C:\\Program Files\\Git\\usr\\bin\\less.exe", "-R"],589 id="quoted windows path with flag",590 ),591 # Single-quoted path.592 pytest.param(593 "'/usr/local/bin/my pager'",594 ["/usr/local/bin/my pager"],595 id="single-quoted path with spaces",596 ),597 # Unix paths.598 pytest.param("/usr/bin/less", ["/usr/bin/less"], id="unix absolute path"),599 pytest.param(600 "/usr/bin/my\\ pager",601 ["/usr/bin/my pager"],602 id="escaped space in unix path",603 ),604 # PR #1477: POSIX mode (the default) eats unquoted backslashes.605 # On Windows, users must quote paths that contain backslashes.606 pytest.param(607 "C:\\path\\to\\exe /test other\\path",608 ["C:pathtoexe", "/test", "otherpath"],609 id="unquoted backslashes eaten in POSIX mode",610 ),611 ],612)613def test_pager_shlex_split(pager_env, expected_parts):614 """Verify shlex.split produces the expected argv for PAGER values.615616 Tests the splitting logic used by :func:`click._termui_impl.pager` to617 turn the ``PAGER`` environment variable into an ``argv`` list. See618 issue #1026, PR #1477, PR #1543, PR #2775.619 """620 assert shlex.split(pager_env) == expected_parts621622623def test_editor_unclosed_quote():624 """An unclosed quote in the editor command raises ValueError."""625 with pytest.raises(ValueError, match="No closing quotation"):626 Editor(editor='"unclosed').edit_files(["f.txt"])Bump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 627–684why, one step back627628629@pytest.mark.parametrize(630 ("prompt_required", "required", "args", "expect"),631 [632 (True, False, None, "prompt"),633 (True, False, ["-v"], "Option '-v' requires an argument."),634 (False, True, None, "prompt"),635 (False, True, ["-v"], "prompt"),636 ],637)638def test_prompt_required_with_required(runner, prompt_required, required, args, expect):639 @click.command()640 @click.option("-v", prompt=True, prompt_required=prompt_required, required=required)641 def cli(v):642 click.echo(str(v))643644 result = runner.invoke(cli, args, input="prompt")645 assert expect in result.output646647648@pytest.mark.parametrize(649 ("args", "expect"),650 [651 # Flag not passed, don't prompt.652 pytest.param(None, None, id="no flag"),653 # Flag and value passed, don't prompt.654 pytest.param(["-v", "value"], "value", id="short sep value"),655 pytest.param(["--value", "value"], "value", id="long sep value"),656 pytest.param(["-vvalue"], "value", id="short join value"),657 pytest.param(["--value=value"], "value", id="long join value"),658 # Flag without value passed, prompt.659 pytest.param(["-v"], "prompt", id="short no value"),660 pytest.param(["--value"], "prompt", id="long no value"),661 # Don't use next option flag as value.662 pytest.param(["-v", "-o", "42"], ("prompt", "42"), id="no value opt"),663 ],664)665def test_prompt_required_false(runner, args, expect):666 @click.command()667 @click.option("-v", "--value", prompt=True, prompt_required=False)668 @click.option("-o")669 def cli(value, o):670 if o is not None:671 return value, o672673 return value674675 result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)676 assert result.exception is None677 assert result.return_value == expect678679680@pytest.mark.parametrize(681 ("prompt", "input", "default", "expect"),682 [683 (True, "password\npassword", None, "password"),684 ("Confirm Password", "password\npassword\n", None, "password"),Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0
line 685why, one step back685 (True, "\n\n", "", ""),Bump actions/setup-python from 4.6.1 to 4.7.0 (#2578)David Lordbefore adoption388b0e1
lines 686–706why, one step back686 (False, None, None, None),687 ],688)689def test_confirmation_prompt(runner, prompt, input, default, expect):690 @click.command()691 @click.option(692 "--password",693 prompt=prompt,694 hide_input=True,695 default=default,696 confirmation_prompt=prompt,697 )698 def cli(password):699 return password700701 result = runner.invoke(cli, input=input, standalone_mode=False)702 assert result.exception is None703 assert result.return_value == expect704705 if prompt == "Confirm Password":706 assert "Confirm Password: " in result.outputHide default value when show_default is False (#2509)Patrick Hayesbefore adoptiona6e0d29
lines 707–718why, one step back707708709def test_false_show_default_cause_no_default_display_in_prompt(runner):710 @click.command()711 @click.option("--arg1", show_default=False, prompt=True, default="my-default-value")712 def cmd(arg1):713 pass714715 # Confirm that the default value is not included in the output when `show_default`716 # is False717 result = runner.invoke(cmd, input="my-input", standalone_mode=False)718 assert "my-default-value" not in result.outputShow default string in prompt (#3328)Rowlando13before adoption76552ff
lines 719–770why, one step back719720721@pytest.mark.parametrize(722 ("show_default", "default", "user_input", "in_prompt", "not_in_prompt"),723 [724 # Regular string replaces the actual default in the prompt.725 ("custom", "actual", "\n", "(custom)", "actual"),726 # String with spaces.727 ("custom label", "actual", "\n", "(custom label)", "actual"),728 # Unicode characters.729 ("∞", "0", "\n", "(∞)", None),730 # Numeric default: custom string hides the number.731 ("unlimited", 42, "\n", "(unlimited)", "42"),732 # Explicit default=None: custom string still appears, must provide input.733 ("computed at runtime", None, "value\n", "(computed at runtime)", None),734 # No default kwarg at all (internal UNSET sentinel): same as None.735 ("computed at runtime", UNSET, "value\n", "(computed at runtime)", None),736 # Empty string is falsy: suppresses any default display.737 ("", "actual", "\n", None, "actual"),738 ],739 ids=[740 "simple-string",741 "string-with-spaces",742 "unicode",743 "numeric-default",744 "default-is-none",745 "default-is-unset",746 "empty-string-is-falsy",747 ],748)749def test_string_show_default_in_prompt(750 runner, show_default, default, user_input, in_prompt, not_in_prompt751):752 """When show_default is a string, the prompt should display that753 string in parentheses instead of the actual default value,754 matching the help text behavior. See pallets/click#2836."""755756 option_kwargs = {"show_default": show_default, "prompt": True}757 if default is not UNSET:758 option_kwargs["default"] = default759760 @click.command()761 @click.option("--arg1", **option_kwargs)762 def cmd(arg1):763 click.echo(arg1)764765 result = runner.invoke(cmd, input=user_input, standalone_mode=False)766 prompt_line = result.output.split("\n")[0]767 if in_prompt is not None:768 assert in_prompt in prompt_line769 if not_in_prompt is not None:770 assert not_in_prompt not in prompt_lineMerge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 771–880why, one step back771772773REPEAT = object()774"""Sentinel value to indicate that the prompt is expected to be repeated.775776I.e. the value provided by the user is not satisfactory and need to be re-prompted.777"""778779INVALID = object()780"""Sentinel value to indicate that the prompt is expected to be invalid.781782On invalid input, Click will output an error message and re-prompt the user.783"""784785BOOLEAN_FLAG_PROMPT_CASES = [786 ###787 ### Test cases with prompt=True explicitly enabled for the flag.788 ###789 # Prompt is allowed and the flag has no default, so it prompts.790 ({"prompt": True}, [], "[y/N]", "y", True),791 ({"prompt": True}, [], "[y/N]", "n", False),792 # Empty input default to False.793 ({"prompt": True}, [], "[y/N]", "", False),794 # Changing the default to True, makes the prompt change to [Y/n].795 ({"prompt": True, "default": True}, [], "[Y/n]", "", True),796 ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),797 ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),798 # False is the default's default, so it prompts with [y/N].799 ({"prompt": True, "default": False}, [], "[y/N]", "", False),800 ({"prompt": True, "default": False}, [], "[y/N]", "y", True),801 ({"prompt": True, "default": False}, [], "[y/N]", "n", False),802 # Defaulting to None, prompts with [y/n], which makes the user explicitly choose803 # between True or False.804 ({"prompt": True, "default": None}, [], "[y/n]", "y", True),805 ({"prompt": True, "default": None}, [], "[y/n]", "n", False),806 # Random string default is treated as a truthy value, so it prompts with [Y/n].807 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),808 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),809 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),810 ###811 ### Test cases with required=True explicitly enabled for the flag.812 ###813 # A required flag just raises an error unless a default is set.814 ({"required": True}, [], None, None, MissingParameter),815 ({"required": True, "default": True}, [], None, None, True),816 ({"required": True, "default": False}, [], None, None, False),817 ({"required": True, "default": None}, [], None, None, None),818 ({"required": True, "default": "on"}, [], None, None, True),819 ({"required": True, "default": "off"}, [], None, None, False),820 ({"required": True, "default": "foo"}, [], None, None, BadParameter),821 ###822 ### Explicitly passing the flag to the CLI bypass any prompt, whatever the823 ### configuration of the flag.824 ###825 # Flag allowing a prompt.826 ({"prompt": True}, ["--flag"], None, None, True),827 ({"prompt": True}, ["--no-flag"], None, None, False),828 ({"prompt": True, "default": None}, ["--flag"], None, None, True),829 ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),830 ({"prompt": True, "default": True}, ["--flag"], None, None, True),831 ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),832 ({"prompt": True, "default": False}, ["--flag"], None, None, True),833 ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),834 ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),835 ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),836 # Required flag.837 ({"required": True}, ["--flag"], None, None, True),838 ({"required": True}, ["--no-flag"], None, None, False),839 ({"required": True, "default": None}, ["--flag"], None, None, True),840 ({"required": True, "default": None}, ["--no-flag"], None, None, False),841 ({"required": True, "default": True}, ["--flag"], None, None, True),842 ({"required": True, "default": True}, ["--no-flag"], None, None, False),843 ({"required": True, "default": False}, ["--flag"], None, None, True),844 ({"required": True, "default": False}, ["--no-flag"], None, None, False),845 ({"required": True, "default": "foo"}, ["--flag"], None, None, True),846 ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),847]848849FLAG_VALUE_PROMPT_CASES = [850 ###851 ### Test cases with prompt=True explicitly enabled for the flag.852 ###853 # Prompt is allowed and the flag has no default, so it prompts.854 # But the flag_value is not set, so it defaults to a string.855 ({"prompt": True}, [], "", "", REPEAT),856 ({"prompt": True}, [], "", "y", "y"),857 ({"prompt": True}, [], "", "n", "n"),858 ({"prompt": True}, [], "", "foo", "foo"),859 # This time we provide a boolean flag_value, which makes the flag behave like a860 # boolean flag, and use the appropriate variation of [y/n].861 ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),862 ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),863 ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),864 ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),865 ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),866 ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),867 # Other flag values changes the auto-detection of the flag type.868 ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),869 ({"prompt": True, "flag_value": None}, [], "", "y", "y"),870 ({"prompt": True, "flag_value": None}, [], "", "n", "n"),871 ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),872 ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),873 ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),874 ###875 ### Test cases with a flag_value and a default.876 ###877 # default=True878 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),879 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),880 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),Reconcile default value passing and default activation (#3239)Rowlando13before adoption8c95c73
lines 881–887why, one step back881 # For boolean flags, default=True is a literal value, not a sentinel meaning882 # "activate flag", so the prompt shows [Y/n] with default=True. See:883 # https://github.com/pallets/click/issues/3111884 # https://github.com/pallets/click/pull/3239885 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),886 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),887 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),Merge branch 'main' into stableDavid Lordbefore adoption81a482f
lines 888–990why, one step back888 # default=False889 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),890 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),891 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),892 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),893 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),894 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),895 # default=None896 (897 {"prompt": True, "default": None, "flag_value": True},898 [],899 "[y/n]",900 "",901 INVALID,902 ),903 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),904 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),905 (906 {"prompt": True, "default": None, "flag_value": False},907 [],908 "[y/n]",909 "",910 INVALID,911 ),912 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),913 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),914 # If the flag_value is None, the flag behave like a string flag, whatever the915 # default is.916 ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),917 ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),918 ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),919 (920 {"prompt": True, "default": False, "flag_value": None},921 [],922 "[False]",923 "",924 "False",925 ),926 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),927 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),928 ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),929 ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),930 ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),931]932933934@pytest.mark.parametrize(935 ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),936 # Boolean flag prompt cases.937 [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]938 # Non-boolean flag prompt cases.939 + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],940)941def test_flag_value_prompt(942 runner, opt_decls, opt_params, args, prompt, input, expected943):944 """Check how flag value are prompted and handled by all combinations of945 ``prompt``, ``default``, and ``flag_value`` parameters.946947 Covers concerns raised in issue https://github.com/pallets/click/issues/1992.948 """949950 @click.command()951 @click.option(opt_decls, **opt_params)952 def cli(flag):953 click.echo(repr(flag))954955 invoke_options = {"standalone_mode": False}956 if input is not None:957 assert isinstance(input, str)958 invoke_options["input"] = f"{input}\n"959960 result = runner.invoke(cli, args, **invoke_options)961962 if expected in (MissingParameter, BadParameter):963 assert isinstance(result.exception, expected)964 assert not result.output965 assert result.exit_code == 1966967 else:968 expected_output = ""969 if prompt is not None:970 # Build the expected prompt.971 assert isinstance(prompt, str)972 expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "973974 # Add the user input to the expected output.975 assert isinstance(input, str)976 expected_output += f"{expected_prompt}{input}\n"977978 if expected is INVALID:979 expected_output += "Error: invalid input\n"980981 # The prompt is expected to be repeated.982 if expected in (REPEAT, INVALID):983 expected_output += expected_prompt984985 if expected not in (REPEAT, INVALID):986 expected_output += f"{expected!r}\n"987988 assert result.output == expected_output989 assert not result.stderr990 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1