Debian Codegraph @

tests/test_termui.py

raw
1 import platform
2 import shlex
3 import tempfile
4 import time
5 from unittest.mock import patch
6
7 import pytest
8
9 import click._termui_impl
10 from click._compat import WIN
11 from click._termui_impl import Editor
12 from click._utils import UNSET
13 from click.exceptions import BadParameter
14 from click.exceptions import MissingParameter
15
16
17 class FakeClock:
18 def __init__(self):
19 self.now = time.time()
20
21 def advance_time(self, seconds=1):
22 self.now += seconds
23
24 def time(self):
25 return self.now
26
27
28 def _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 progress
33
34
35 def test_progressbar_strip_regression(runner, monkeypatch):
36 label = " padded line"
37
38 @click.command()
39 def cli():
40 with _create_progress(label=label) as progress:
41 for _ in progress:
42 pass
43
44 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
45 assert (
46 label
47 in runner.invoke(cli, [], standalone_mode=False, catch_exceptions=False).output
48 )
49
50
51 def test_progressbar_length_hint(runner, monkeypatch):
52 class Hinted:
53 def __init__(self, n):
54 self.items = list(range(n))
55
56 def __length_hint__(self):
57 return len(self.items)
58
59 def __iter__(self):
60 return self
61
62 def __next__(self):
63 if self.items:
64 return self.items.pop()
65 else:
66 raise StopIteration
67
68 next = __next__
69
70 @click.command()
71 def cli():
72 with click.progressbar(Hinted(10), label="test") as progress:
73 for _ in progress:
74 pass
75
76 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
77 result = runner.invoke(cli, [])
78 assert result.exception is None
79
80
81 def test_progressbar_no_tty(runner, monkeypatch):
82 @click.command()
83 def cli():
84 with _create_progress(label="working") as progress:
85 for _ in progress:
86 pass
87
88 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: False)
89 assert runner.invoke(cli, []).output == "working\n"
90
91
92 def 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 pass
98
99 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
100 assert runner.invoke(cli, []).output == ""
101
102
103 @pytest.mark.parametrize("avg, expected", [([], 0.0), ([1, 4], 2.5)])
104 def test_progressbar_time_per_iteration(runner, avg, expected):
105 with _create_progress(2, avg=avg) as progress:
106 assert progress.time_per_iteration == expected
107
108
109 @pytest.mark.parametrize("finished, expected", [(False, 5), (True, 0)])
110 def test_progressbar_eta(runner, finished, expected):
111 with _create_progress(2, finished=finished, avg=[1, 4]) as progress:
112 assert progress.eta == expected
113
114
115 @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 )
127 def 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() == expected
130
131
132 @pytest.mark.parametrize("pos, length", [(0, 5), (-1, 1), (5, 5), (6, 5), (4, 0)])
133 def 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}"
137
138
139 @pytest.mark.parametrize(
140 "length, finished, pos, avg, expected",
141 [
142 (8, False, 7, 0, "#######-"),
143 (0, True, 8, 0, "########"),
144 ],
145 )
146 def 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() == expected
151
152
153 @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 )
163 def test_progressbar_format_progress_line(
164 runner, length, show_percent, show_pos, pos, expected
165 ):
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() == expected
174
175
176 @pytest.mark.parametrize("test_item", ["test", None])
177 def test_progressbar_format_progress_line_with_show_func(runner, test_item):
178 def item_show_func(item):
179 return item
180
181 with _create_progress(
182 item_show_func=item_show_func, current_item=test_item
183 ) 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())
188
189
190 def test_progressbar_init_exceptions(runner):
191 with pytest.raises(TypeError, match="iterable or length is required"):
192 click.progressbar()
193
194
195 def test_progressbar_iter_outside_with_exceptions(runner):
196 progress = click.progressbar(length=2)
197
198 with pytest.raises(RuntimeError, match="with block"):
199 iter(progress)
200
201
202 def 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 break
211
212 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
213 result = runner.invoke(cli, [])
214 assert result.exception is None
215
216
217 def test_choices_list_in_prompt(runner, monkeypatch):
218 @click.command()
219 @click.option(
220 "-g", type=click.Choice(["none", "day", "week", "month"]), prompt=True
221 )
222 def cli_with_choices(g):
223 pass
224
225 @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 pass
234
235 result = runner.invoke(cli_with_choices, [], input="none")
236 assert "(none, day, week, month)" in result.output
237
238 result = runner.invoke(cli_without_choices, [], input="none")
239 assert "(none, day, week, month)" not in result.output
240
241
242 @pytest.mark.parametrize(
243 "file_kwargs", [{"mode": "rt"}, {"mode": "rb"}, {"lazy": True}]
244 )
245 def 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)
250
251 result = runner.invoke(cli, input="\n")
252 assert result.output == f"file [{__file__}]: \n{__file__}\n"
253
254
255 def test_secho(runner):
256 with runner.isolation() as outstreams:
257 click.secho(None, nl=False)
258 bytes = outstreams[0].getvalue()
259 assert bytes == b""
260
261
262 @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 )
266 def test_secho_non_text(runner, value, expect):
267 with runner.isolation() as (out, _, _):
268 click.secho(value, nl=False, color=True, bg="magenta")
269 result = out.getvalue()
270 assert result == expect
271
272
273 def test_progressbar_yields_all_items(runner):
274 with click.progressbar(range(3)) as progress:
275 assert len(list(progress)) == 3
276
277
278 def test_progressbar_update(runner, monkeypatch):
279 fake_clock = FakeClock()
280
281 @click.command()
282 def cli():
283 with click.progressbar(range(4)) as progress:
284 for _ in progress:
285 fake_clock.advance_time()
286 print("")
287
288 monkeypatch.setattr(time, "time", fake_clock.time)
289 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
290 output = runner.invoke(cli, []).output
291
292 lines = [line for line in output.split("\n") if "[" in line]
293
294 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]
299
300
301 def test_progressbar_item_show_func(runner, monkeypatch):
302 """item_show_func should show the current item being yielded."""
303
304 @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}")
309
310 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
311 lines = runner.invoke(cli).output.splitlines()
312
313 for i, line in enumerate(x for x in lines if "item" in x):
314 assert f"{i} item {i}" in line
315
316
317 def 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()
326
327 monkeypatch.setattr(click._termui_impl, "isatty", lambda _: True)
328 output = runner.invoke(cli, []).output
329
330 lines = [line for line in output.split("\n") if "[" in line]
331
332 assert "Custom 0" in lines[0]
333 assert "Custom 2" in lines[1]
334 assert "Custom 4" in lines[2]
335
336
337 def test_progress_bar_update_min_steps(runner):
338 bar = _create_progress(update_min_steps=5)
339 bar.update(3)
340 assert bar._completed_intervals == 3
341 assert bar.pos == 0
342 bar.update(2)
343 assert bar._completed_intervals == 0
344 assert bar.pos == 5
345
346
347 @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.")
350 def 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_char
355
356
357 @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 )
363 def 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}"
370
371
372 @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.")
376 def 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)
379
380 with pytest.raises(exc):
381 click.getchar()
382
383
384 @pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")
385 def test_fast_edit(runner):
386 result = click.edit("a\nb", editor="sed -i~ 's/$/Test/'")
387 assert result == "aTest\nbTest\n"
388
389
390 @pytest.mark.skipif(platform.system() == "Windows", reason="No sed on Windows.")
391 def test_edit(runner):
392 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:
393 named_tempfile.write("a\nb\n")
394 named_tempfile.flush()
395
396 result = click.edit(filename=named_tempfile.name, editor="sed -i~ 's/$/Test/'")
397 assert result is None
398
399 # We need ot reopen the file as it becomes unreadable after the edit.
400 with open(named_tempfile.name) as reopened_file:
401 # POSIX says that when sed writes a pattern space to output then it
402 # is immediately followed by a newline and so the expected result
403 # should contain the newline. However, some sed implementations
404 # (e.g. GNU sed) does not terminate the last line in the output
405 # with the newline in a case the input data missed newline at the
406 # end of last line. Hence the input data (see above) should be
407 # terminated by newline too.
408 assert reopened_file.read() == "aTest\nbTest\n"
409
410
411 @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"],
431 id="quoted windows path with spaces",
432 ),
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"],
438 id="command with flags",
439 ),
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"],
445 id="quoted command with args",
446 ),
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"],
459 id="escaped space in unix path",
460 ),
461 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 ),
503 ],
504 )
505 def 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 = 0
508 Editor(editor=editor_cmd).edit_files(filenames)
509
510 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_args
513 assert mock_popen.call_args[1].get("shell") is None
514
515
516 @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 )
532 def test_editor_windows_path_normalization(editor_cmd, expected_cmd):
533 """Windows-specific tests: verify ``Popen`` receives unquoted paths that
534 ``subprocess.list2cmdline`` can re-quote for ``CreateProcess``."""
535 with patch("subprocess.Popen") as mock_popen:
536 mock_popen.return_value.wait.return_value = 0
537 Editor(editor=editor_cmd).edit_files(["f.txt"])
538
539 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 None
542
543
544 def test_editor_env_passed_through():
545 with patch("subprocess.Popen") as mock_popen:
546 mock_popen.return_value.wait.return_value = 0
547 Editor(editor="vi", env={"MY_VAR": "1"}).edit_files(["f.txt"])
548
549 env = mock_popen.call_args[1].get("env")
550 assert env is not None
551 assert env["MY_VAR"] == "1"
552
553
554 def test_editor_failure_exception():
555 with patch("subprocess.Popen") as mock_popen:
556 mock_popen.return_value.wait.return_value = 1
557 with pytest.raises(click.ClickException, match="Editing failed"):
558 Editor(editor="vi").edit_files(["f.txt"])
559
560
561 def 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"])
565
566
567 @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 (the
580 # 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 )
613 def test_pager_shlex_split(pager_env, expected_parts):
614 """Verify shlex.split produces the expected argv for PAGER values.
615
616 Tests the splitting logic used by :func:`click._termui_impl.pager` to
617 turn the ``PAGER`` environment variable into an ``argv`` list. See
618 issue #1026, PR #1477, PR #1543, PR #2775.
619 """
620 assert shlex.split(pager_env) == expected_parts
621
622
623 def 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"])
627
628
629 @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 )
638 def 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))
643
644 result = runner.invoke(cli, args, input="prompt")
645 assert expect in result.output
646
647
648 @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 )
665 def 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, o
672
673 return value
674
675 result = runner.invoke(cli, args=args, input="prompt", standalone_mode=False)
676 assert result.exception is None
677 assert result.return_value == expect
678
679
680 @pytest.mark.parametrize(
681 ("prompt", "input", "default", "expect"),
682 [
683 (True, "password\npassword", None, "password"),
684 ("Confirm Password", "password\npassword\n", None, "password"),
685 (True, "\n\n", "", ""),
686 (False, None, None, None),
687 ],
688 )
689 def 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 password
700
701 result = runner.invoke(cli, input=input, standalone_mode=False)
702 assert result.exception is None
703 assert result.return_value == expect
704
705 if prompt == "Confirm Password":
706 assert "Confirm Password: " in result.output
707
708
709 def 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 pass
714
715 # Confirm that the default value is not included in the output when `show_default`
716 # is False
717 result = runner.invoke(cmd, input="my-input", standalone_mode=False)
718 assert "my-default-value" not in result.output
719
720
721 @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 )
749 def test_string_show_default_in_prompt(
750 runner, show_default, default, user_input, in_prompt, not_in_prompt
751 ):
752 """When show_default is a string, the prompt should display that
753 string in parentheses instead of the actual default value,
754 matching the help text behavior. See pallets/click#2836."""
755
756 option_kwargs = {"show_default": show_default, "prompt": True}
757 if default is not UNSET:
758 option_kwargs["default"] = default
759
760 @click.command()
761 @click.option("--arg1", **option_kwargs)
762 def cmd(arg1):
763 click.echo(arg1)
764
765 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_line
769 if not_in_prompt is not None:
770 assert not_in_prompt not in prompt_line
771
772
773 REPEAT = object()
774 """Sentinel value to indicate that the prompt is expected to be repeated.
775
776 I.e. the value provided by the user is not satisfactory and need to be re-prompted.
777 """
778
779 INVALID = object()
780 """Sentinel value to indicate that the prompt is expected to be invalid.
781
782 On invalid input, Click will output an error message and re-prompt the user.
783 """
784
785 BOOLEAN_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 choose
803 # 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 the
823 ### 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 ]
848
849 FLAG_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 a
860 # 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=True
878 ({"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),
881 # For boolean flags, default=True is a literal value, not a sentinel meaning
882 # "activate flag", so the prompt shows [Y/n] with default=True. See:
883 # https://github.com/pallets/click/issues/3111
884 # https://github.com/pallets/click/pull/3239
885 ({"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),
888 # default=False
889 ({"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=None
896 (
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 the
915 # 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 ]
932
933
934 @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 )
941 def test_flag_value_prompt(
942 runner, opt_decls, opt_params, args, prompt, input, expected
943 ):
944 """Check how flag value are prompted and handled by all combinations of
945 ``prompt``, ``default``, and ``flag_value`` parameters.
946
947 Covers concerns raised in issue https://github.com/pallets/click/issues/1992.
948 """
949
950 @click.command()
951 @click.option(opt_decls, **opt_params)
952 def cli(flag):
953 click.echo(repr(flag))
954
955 invoke_options = {"standalone_mode": False}
956 if input is not None:
957 assert isinstance(input, str)
958 invoke_options["input"] = f"{input}\n"
959
960 result = runner.invoke(cli, args, **invoke_options)
961
962 if expected in (MissingParameter, BadParameter):
963 assert isinstance(result.exception, expected)
964 assert not result.output
965 assert result.exit_code == 1
966
967 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: "
973
974 # Add the user input to the expected output.
975 assert isinstance(input, str)
976 expected_output += f"{expected_prompt}{input}\n"
977
978 if expected is INVALID:
979 expected_output += "Error: invalid input\n"
980
981 # The prompt is expected to be repeated.
982 if expected in (REPEAT, INVALID):
983 expected_output += expected_prompt
984
985 if expected not in (REPEAT, INVALID):
986 expected_output += f"{expected!r}\n"
987
988 assert result.output == expected_output
989 assert not result.stderr
990 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1