Skip to content
Myr

Merge stable into main. (#3674)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Rowlando13 · committed by GitHub · parents a44e9f0, ea811f9 · Browse files · 15 files+898 added−857 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+898 added−857 removed

  • tests:+898 added−857 removed

15 files+898 added−857 removed

added:tests/test_utils/__init__.py
added:tests/test_utils/test__detect_program_name.py+27 added
1import pathlib23import pytest45import click678class MockMain:9 __slots__ = "__package__"1011 def __init__(self, package_name):12 self.__package__ = package_name131415@pytest.mark.parametrize(16 ("path", "main", "expected"),17 [18 ("example.py", None, "example.py"),19 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),20 ("example", None, "example"),21 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),22 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),23 (str(pathlib.Path("./example")), "", "example"),24 ],25)26def test_detect_program_name(path, main, expected):27 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected
added:tests/test_utils/test__expand_args.py+17 added
1import os23import click456def test_expand_args(monkeypatch):7 user = os.path.expanduser("~")8 assert user in click.utils._expand_args(["~"])9 monkeypatch.setenv("CLICK_TEST", "hello")10 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])11 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])12 assert os.path.join("tests", "conftest.py") in click.utils._expand_args(13 ["**/conftest.py"]14 )15 assert "*.not-found" in click.utils._expand_args(["*.not-found"])16 # a bad glob pattern, such as a pytest identifier, should return itself17 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"
added:tests/test_utils/test_confirm.py+49 added
1import click234def test_prompts(runner):5 @click.command()6 def test():7 if click.confirm("Foo"):8 click.echo("yes!")9 else:10 click.echo("no :(")1112 result = runner.invoke(test, input="y\n")13 assert not result.exception14 assert result.output == "Foo [y/N]: y\nyes!\n"1516 result = runner.invoke(test, input="\n")17 assert not result.exception18 assert result.output == "Foo [y/N]: \nno :(\n"1920 result = runner.invoke(test, input="n\n")21 assert not result.exception22 assert result.output == "Foo [y/N]: n\nno :(\n"2324 @click.command()25 def test_no():26 if click.confirm("Foo", default=True):27 click.echo("yes!")28 else:29 click.echo("no :(")3031 result = runner.invoke(test_no, input="y\n")32 assert not result.exception33 assert result.output == "Foo [Y/n]: y\nyes!\n"3435 result = runner.invoke(test_no, input="\n")36 assert not result.exception37 assert result.output == "Foo [Y/n]: \nyes!\n"3839 result = runner.invoke(test_no, input="n\n")40 assert not result.exception41 assert result.output == "Foo [Y/n]: n\nno :(\n"424344def test_confirm_repeat(runner):45 cli = click.Command(46 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]47 )48 result = runner.invoke(cli, input="\ny\n")49 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"
added:tests/test_utils/test_echo_via_pager.py+259 added
1import os2import subprocess3import sys4from collections import namedtuple5from contextlib import nullcontext6from functools import partial7from unittest.mock import patch89import pytest1011import click12from click._compat import WIN1314EchoViaPagerTest = namedtuple(15 "EchoViaPagerTest",16 (17 "description",18 "test_input",19 "expected_pager",20 "expected_stdout",21 "expected_stderr",22 "expected_error",23 ),24)252627def _test_gen_func():28 yield "a"29 yield "b"30 yield "c"31 yield "abc"323334def _test_gen_func_fails():35 raise RuntimeError("This is a test.")36 yield # unreachable, keeps this a generator function373839def _test_gen_func_yields_then_fails():40 yield "test"41 raise RuntimeError("This is a test.")424344def _test_gen_func_echo(file=None):45 yield "test"46 click.echo("hello", file=file)47 yield "test"484950def _test_simulate_keyboard_interrupt(file=None):51 yield "output_before_keyboard_interrupt"52 raise KeyboardInterrupt()535455@pytest.mark.skipif(WIN, reason="Different behavior on windows.")56@pytest.mark.parametrize(57 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]58)59@pytest.mark.parametrize(60 "test",61 [62 # We need to pass a parameter function instead of a plain param63 # as pytest.mark.parametrize will reuse the parameters causing the64 # generators to be used up so they will not yield anymore65 EchoViaPagerTest(66 description="Plain string argument",67 test_input=lambda: "just text",68 expected_pager="just text\n",69 expected_stdout="",70 expected_stderr="",71 expected_error=None,72 ),73 EchoViaPagerTest(74 description="Iterable argument",75 test_input=lambda: ["itera", "ble"],76 expected_pager="iterable\n",77 expected_stdout="",78 expected_stderr="",79 expected_error=None,80 ),81 EchoViaPagerTest(82 description="Generator function argument",83 test_input=lambda: _test_gen_func,84 expected_pager="abcabc\n",85 expected_stdout="",86 expected_stderr="",87 expected_error=None,88 ),89 EchoViaPagerTest(90 description="String generator argument",91 test_input=lambda: _test_gen_func(),92 expected_pager="abcabc\n",93 expected_stdout="",94 expected_stderr="",95 expected_error=None,96 ),97 EchoViaPagerTest(98 description="Number generator expression argument",99 test_input=lambda: (c for c in range(6)),100 expected_pager="012345\n",101 expected_stdout="",102 expected_stderr="",103 expected_error=None,104 ),105 EchoViaPagerTest(106 description="Exception in generator function argument",107 test_input=lambda: _test_gen_func_fails,108 # Because generator throws early on, the pager did not have109 # a chance yet to write the file.110 expected_pager="",111 expected_stdout="",112 expected_stderr="",113 expected_error=RuntimeError,114 ),115 EchoViaPagerTest(116 description="Exception in generator argument",117 test_input=lambda: _test_gen_func_fails,118 # Because generator throws early on, the pager did not have a119 # chance yet to write the file.120 expected_pager="",121 expected_stdout="",122 expected_stderr="",123 expected_error=RuntimeError,124 ),125 EchoViaPagerTest(126 description="Keyboard interrupt should not terminate the pager",127 test_input=lambda: _test_simulate_keyboard_interrupt(),128 # Due to the keyboard interrupt during pager execution, click program129 # should abort, but the pager should stay open.130 # This allows users to cancel the program and search in the pager131 # output, before they decide to terminate the pager.132 expected_pager="output_before_keyboard_interrupt",133 expected_stdout="",134 expected_stderr="",135 expected_error=KeyboardInterrupt,136 ),137 EchoViaPagerTest(138 description="Writing to stdout during generator execution",139 test_input=lambda: _test_gen_func_echo(),140 expected_pager="testtest\n",141 expected_stdout="hello\n",142 expected_stderr="",143 expected_error=None,144 ),145 EchoViaPagerTest(146 description="Writing to stderr during generator execution",147 test_input=lambda: _test_gen_func_echo(file=sys.stderr),148 expected_pager="testtest\n",149 expected_stdout="",150 expected_stderr="hello\n",151 expected_error=None,152 ),153 ],154)155def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):156 monkeypatch.setitem(os.environ, "PAGER", pager_cmd)157 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)158159 test_input = test.test_input()160 expected_pager = test.expected_pager161 expected_stdout = test.expected_stdout162 expected_stderr = test.expected_stderr163 expected_error = test.expected_error164165 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()166167 pager_out_tmp = tmp_path / "pager_out.txt"168 with pager_out_tmp.open("w") as f:169 force_subprocess_stdout = patch.object(170 subprocess,171 "Popen",172 partial(subprocess.Popen, stdout=f),173 )174 with force_subprocess_stdout:175 with check_raise:176 click.echo_via_pager(test_input)177178 out, err = capfd.readouterr()179180 pager = pager_out_tmp.read_text()181182 assert pager == expected_pager, (183 f"Unexpected pager output in test case '{test.description}'"184 )185 assert out == expected_stdout, (186 f"Unexpected stdout in test case '{test.description}'"187 )188 assert err == expected_stderr, (189 f"Unexpected stderr in test case '{test.description}'"190 )191192193@pytest.mark.skipif(WIN, reason="Different behavior on windows.")194def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):195 """A generator that yields then raises: click writes the partial output to196 the pager stream before propagating the exception.197198 The pager file content is intentionally NOT asserted: pipe-drain timing199 between click and the pager subprocess is outside click's control200 (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent201 to the pager, which is deterministic regardless of scheduling.202 """203 monkeypatch.setitem(os.environ, "PAGER", "cat")204 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)205206 writes: list[str] = []207 real_write = click._termui_impl.MaybeStripAnsi.write208209 def spy(self, text):210 writes.append(text)211 return real_write(self, text)212213 monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)214215 pager_out_tmp = tmp_path / "pager_out.txt"216 with (217 pager_out_tmp.open("w") as f,218 patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),219 pytest.raises(RuntimeError, match="This is a test."),220 ):221 click.echo_via_pager(_test_gen_func_yields_then_fails())222223 assert "".join(writes) == "test", (224 f"click should have written the yielded chunk before exception, got {writes!r}"225 )226227228@pytest.mark.stress229@pytest.mark.skipif(WIN, reason="Different behavior on windows.")230@pytest.mark.parametrize("_", range(1000))231def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):232 """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.233234 Regression coverage for the cleanup path in ``_pipepager``'s exception235 handler (issue #2899, PR #3470). Each iteration spawns a real pager236 subprocess, raises before any data is written and check there is no leak.237 """238 monkeypatch.setitem(os.environ, "PAGER", "cat")239 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)240241 spawned: list[subprocess.Popen] = []242 real_popen = subprocess.Popen243244 def tracking_popen(*args, **kwargs):245 p = real_popen(*args, **kwargs)246 spawned.append(p)247 return p248249 pager_out_tmp = tmp_path / "pager_out.txt"250 with (251 pager_out_tmp.open("w") as f,252 patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),253 pytest.raises(RuntimeError),254 ):255 click.echo_via_pager(_test_gen_func_fails())256257 assert spawned, "pager subprocess was never started"258 for p in spawned:259 assert p.returncode is not None, "pager subprocess not reaped"
added:tests/test_utils/test_echo.py+176 added
1import sys2from io import BytesIO3from io import StringIO45import pytest67import click._termui_impl8import click.utils9from click._compat import WIN101112def test_echo(runner):13 with runner.isolation() as outstreams:14 click.echo("\N{SNOWMAN}")15 click.echo(b"\x44\x44")16 click.echo(42, nl=False)17 click.echo(b"a", nl=False)18 click.echo("\x1b[31mx\x1b[39m", nl=False)19 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")20 assert bytes == b"\xe2\x98\x83\nDD\n42ax"2122 # if wrapped, we expect bytes to survive.23 @click.command()24 def cli():25 click.echo(b"\xf6")2627 result = runner.invoke(cli, [])28 assert result.stdout_bytes == b"\xf6\n"2930 # Ensure we do not strip for bytes.31 with runner.isolation() as outstreams:32 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)33 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"343536def test_echo_custom_file():37 f = StringIO()38 click.echo("hello", file=f)39 assert f.getvalue() == "hello\n"4041 b = BytesIO()42 click.echo(b"", b)43 assert b.getvalue() == b"\n"444546def test_echo_no_streams(monkeypatch, runner):47 """echo should not fail when stdout and stderr are None with pythonw on Windows."""48 with runner.isolation():49 sys.stdout = None50 sys.stderr = None51 click.echo("test")52 click.echo("test", err=True)535455def test_echo_with_capsys(capsys):56 click.echo("Capture me.")57 out, err = capsys.readouterr()58 assert out == "Capture me.\n"596061def test_echo_color_flag(monkeypatch, capfd):62 isatty = True63 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)6465 text = "foo"66 styled_text = click.style(text, fg="red")67 assert styled_text == "\x1b[31mfoo\x1b[0m"6869 click.echo(styled_text, color=False)70 out, err = capfd.readouterr()71 assert out == f"{text}\n"7273 click.echo(styled_text, color=True)74 out, err = capfd.readouterr()75 assert out == f"{styled_text}\n"7677 isatty = True78 click.echo(styled_text)79 out, err = capfd.readouterr()80 assert out == f"{styled_text}\n"8182 isatty = False83 # Faking isatty() is not enough on Windows;84 # the implementation caches the colorama wrapped stream85 # so we have to use a new stream for each test86 stream = StringIO()87 click.echo(styled_text, file=stream)88 assert stream.getvalue() == f"{text}\n"8990 stream = StringIO()91 click.echo(styled_text, file=stream, color=True)92 assert stream.getvalue() == f"{styled_text}\n"939495@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")96def test_echo_writing_to_standard_error(capfd, monkeypatch):97 def emulate_input(text):98 """Emulate keyboard input."""99 monkeypatch.setattr(sys, "stdin", StringIO(text))100101 click.echo("Echo to standard output")102 out, err = capfd.readouterr()103 assert out == "Echo to standard output\n"104 assert err == ""105106 click.echo("Echo to standard error", err=True)107 out, err = capfd.readouterr()108 assert out == ""109 assert err == "Echo to standard error\n"110111 emulate_input("asdlkj\n")112 click.prompt("Prompt to stdin")113 out, err = capfd.readouterr()114 assert out == "Prompt to stdin: "115 assert err == ""116117 emulate_input("asdlkj\n")118 click.prompt("Prompt to stdin with no suffix", prompt_suffix="")119 out, err = capfd.readouterr()120 assert out == "Prompt to stdin with no suffix"121 assert err == ""122123 # On non-Windows the full prompt goes through redirect_stdout so124 # nothing leaks to stdout when err=True.125 # https://github.com/pallets/click/issues/2968126 emulate_input("asdlkj\n")127 click.prompt("Prompt to stderr", err=True)128 out, err = capfd.readouterr()129 assert out == ""130 assert err == "Prompt to stderr: "131132 # https://github.com/pallets/click/issues/3019133 emulate_input("asdlkj\n")134 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)135 out, err = capfd.readouterr()136 assert out == ""137 assert err == "Prompt to stderr with no suffix"138139 emulate_input("y\n")140 click.confirm("Prompt to stdin")141 out, err = capfd.readouterr()142 assert out == "Prompt to stdin [y/N]: "143 assert err == ""144145 emulate_input("y\n")146 click.confirm("Prompt to stdin with no suffix", prompt_suffix="")147 out, err = capfd.readouterr()148 assert out == "Prompt to stdin with no suffix [y/N]"149 assert err == ""150151 # https://github.com/pallets/click/issues/2968152 emulate_input("y\n")153 click.confirm("Prompt to stderr", err=True)154 out, err = capfd.readouterr()155 assert out == ""156 assert err == "Prompt to stderr [y/N]: "157158 # https://github.com/pallets/click/issues/3019159 emulate_input("y\n")160 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)161 out, err = capfd.readouterr()162 assert out == ""163 assert err == "Prompt to stderr with no suffix [y/N]"164165 monkeypatch.setattr(click.termui, "isatty", lambda x: True)166 monkeypatch.setattr(click.termui, "getchar", lambda: " ")167168 click.pause("Pause to stdout")169 out, err = capfd.readouterr()170 assert out == "Pause to stdout\n"171 assert err == ""172173 click.pause("Pause to stderr", err=True)174 out, err = capfd.readouterr()175 assert out == ""176 assert err == "Pause to stderr\n"
added:tests/test_utils/test_format_filename.py+9 added
1import click234def test_filename_formatting():5 assert click.format_filename(b"foo.txt") == "foo.txt"6 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"7 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"8 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"9 assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"
added:tests/test_utils/test_KeepOpenFile.py+10 added
1import click234def test_iter_keepopenfile(tmpdir):5 expected = list(map(str, range(10)))6 p = tmpdir.mkdir("testdir").join("testfile")7 p.write("\n".join(expected))8 with p.open() as f:9 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):10 assert e_line == a_line.strip()
added:tests/test_utils/test_LazyFile.py+11 added
1import click234def test_iter_lazyfile(tmpdir):5 expected = list(map(str, range(10)))6 p = tmpdir.mkdir("testdir").join("testfile")7 p.write("\n".join(expected))8 with p.open() as f:9 with click.utils.LazyFile(f.name) as lf:10 for e_line, a_line in zip(expected, lf, strict=False):11 assert e_line == a_line.strip()
added:tests/test_utils/test_make_default_short_help.py+39 added
1import pytest23import click456@pytest.mark.parametrize(7 ("value", "max_length", "expect"),8 [9 pytest.param("", 10, "", id="empty"),10 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),11 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),12 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),13 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),14 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),15 pytest.param(16 "token in ~/.netrc ciao ciao",17 20,18 "token in ~/.netrc...",19 id="ignore dot in word",20 ),21 ],22)23@pytest.mark.parametrize(24 "alter",25 [26 pytest.param(None, id=""),27 pytest.param(28 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"29 ),30 ],31)32def test_make_default_short_help(value, max_length, alter, expect):33 assert len(expect) <= max_length3435 if alter:36 value = alter(value)3738 out = click.utils.make_default_short_help(value, max_length)39 assert out == expect
added:tests/test_utils/test_open_file.py+122 added
1import os2import pathlib3import stat45import pytest67import click8from click._compat import WIN91011def test_open_file(runner):12 @click.command()13 @click.argument("filename")14 def cli(filename):15 with click.open_file(filename) as f:16 click.echo(f.read())1718 click.echo("meep")1920 with runner.isolated_filesystem():21 with open("hello.txt", "w") as f:22 f.write("Cool stuff")2324 result = runner.invoke(cli, ["hello.txt"])25 assert result.exception is None26 assert result.output == "Cool stuff\nmeep\n"2728 result = runner.invoke(cli, ["-"], input="foobar")29 assert result.exception is None30 assert result.output == "foobar\nmeep\n"313233def test_open_file_pathlib_dash(runner):34 @click.command()35 @click.argument(36 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)37 )38 def cli(filename):39 click.echo(str(type(filename)))4041 with click.open_file(filename) as f:42 click.echo(f.read())4344 result = runner.invoke(cli, ["-"], input="value")45 assert result.exception is None46 assert result.output == "pathlib.Path\nvalue\n"474849def test_open_file_ignore_errors_stdin(runner):50 @click.command()51 @click.argument("filename")52 def cli(filename):53 with click.open_file(filename, errors="ignore") as f:54 click.echo(f.read())5556 result = runner.invoke(cli, ["-"], input=os.urandom(16))57 assert result.exception is None585960def test_open_file_respects_ignore(runner):61 with runner.isolated_filesystem():62 with open("test.txt", "w") as f:63 f.write("Hello world!")6465 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:66 assert f.errors == "ignore"676869def test_open_file_ignore_invalid_utf8(runner):70 with runner.isolated_filesystem():71 with open("test.txt", "wb") as f:72 f.write(b"\xe2\x28\xa1")7374 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:75 f.read()767778def test_open_file_ignore_no_encoding(runner):79 with runner.isolated_filesystem():80 with open("test.bin", "wb") as f:81 f.write(os.urandom(16))8283 with click.open_file("test.bin", errors="ignore") as f:84 f.read()858687@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")88@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])89def test_open_file_atomic_permissions_existing_file(runner, permissions):90 with runner.isolated_filesystem():91 with open("existing.txt", "w") as f:92 f.write("content")93 os.chmod("existing.txt", permissions)9495 @click.command()96 @click.argument("filename")97 def cli(filename):98 click.open_file(filename, "w", atomic=True).close()99100 result = runner.invoke(cli, ["existing.txt"])101 assert result.exception is None102 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions103104105@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")106def test_open_file_atomic_permissions_new_file(runner):107 with runner.isolated_filesystem():108109 @click.command()110 @click.argument("filename")111 def cli(filename):112 click.open_file(filename, "w", atomic=True).close()113114 # Create a test file to get the expected permissions for new files115 # according to the current umask.116 with open("test.txt", "w"):117 pass118 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)119120 result = runner.invoke(cli, ["new.txt"])121 assert result.exception is None122 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions
added:tests/test_utils/test_prompt.py+74 added
1import sys2from io import StringIO34import pytest56import click7from click._compat import WIN8910def test_prompt_cast_default(capfd, monkeypatch):11 monkeypatch.setattr(sys, "stdin", StringIO("\n"))12 value = click.prompt("value", default="100", type=int)13 capfd.readouterr()14 assert isinstance(value, int)151617@pytest.mark.skipif(WIN, reason="Different behavior on windows.")18def test_prompts_abort(monkeypatch, capsys):19 def f(_):20 raise KeyboardInterrupt()2122 monkeypatch.setattr("click.termui.hidden_prompt_func", f)2324 try:25 click.prompt("Password", hide_input=True)26 except click.Abort:27 click.echo("interrupted")2829 out, err = capsys.readouterr()30 # On non-Windows, prompt is passed directly to getpass, not echoed separately31 assert out == "\ninterrupted\n"323334@pytest.mark.skipif(WIN, reason="Different behavior on windows.")35@pytest.mark.parametrize(36 ("call", "expected_prompt"),37 [38 (lambda: click.prompt("Name"), "Name: "),39 (lambda: click.prompt("Pw", hide_input=True), "Pw: "),40 (lambda: click.prompt("IP", prompt_suffix="."), "IP."),41 (lambda: click.confirm("OK"), "OK [y/N]: "),42 ],43 ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"],44)45def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt):46 """On non-Windows, prompt and confirm pass the full prompt text to the47 underlying prompt function so readline handles editing correctly.4849 https://github.com/pallets/click/issues/296850 https://github.com/pallets/click/pull/296951 """52 received = []5354 def capture(text):55 received.append(text)56 return "y"5758 monkeypatch.setattr("click.termui.visible_prompt_func", capture)59 monkeypatch.setattr("click.termui.hidden_prompt_func", capture)60 call()61 assert received == [expected_prompt]626364def test_prompts_eof(runner):65 """If too few lines of input are given, prompt should exit, not hang."""6667 @click.command68 def echo():69 for _ in range(3):70 click.echo(click.prompt("", type=int))7172 # only provide two lines of input for three prompts73 result = runner.invoke(echo, input="1\n2\n")74 assert result.exit_code == 1
added:tests/test_utils/test_sentinel.py+52 added
1from decimal import Decimal2from fractions import Fraction34from click._utils import UNSET567def test_unset_sentinel():8 value = UNSET910 assert value11 assert value is UNSET12 assert value == UNSET13 assert repr(value) == "Sentinel.UNSET"14 assert str(value) == "Sentinel.UNSET"15 assert bool(value) is True1617 # Try all native Python values that can be falsy or truthy.18 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing19 real_values = (20 None,21 True,22 False,23 0,24 1,25 0.0,26 1.0,27 0j,28 1j,29 Decimal(0),30 Decimal(1),31 Fraction(0, 1),32 Fraction(1, 1),33 "",34 "a",35 "UNSET",36 "Sentinel.UNSET",37 [1],38 (1),39 {1: "a"},40 set(),41 set([1]),42 frozenset(),43 frozenset([1]),44 range(0),45 range(1),46 )4748 for real_value in real_values:49 assert value != real_value50 assert value is not real_value5152 assert value not in real_values
added:tests/test_utils/test_style.py+53 added
1import pytest23import click456@pytest.mark.parametrize(7 ("styles", "ref"),8 [9 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),10 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),11 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),12 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),13 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),14 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),15 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),16 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),17 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),18 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),19 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),20 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),21 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),22 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),23 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),24 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),25 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),26 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),27 ({"bold": True}, "\x1b[1mx y\x1b[0m"),28 ({"dim": True}, "\x1b[2mx y\x1b[0m"),29 ({"underline": True}, "\x1b[4mx y\x1b[0m"),30 ({"overline": True}, "\x1b[53mx y\x1b[0m"),31 ({"italic": True}, "\x1b[3mx y\x1b[0m"),32 ({"blink": True}, "\x1b[5mx y\x1b[0m"),33 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),34 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),35 ({"bold": False}, "\x1b[22mx y\x1b[0m"),36 ({"dim": False}, "\x1b[22mx y\x1b[0m"),37 ({"underline": False}, "\x1b[24mx y\x1b[0m"),38 ({"overline": False}, "\x1b[55mx y\x1b[0m"),39 ({"italic": False}, "\x1b[23mx y\x1b[0m"),40 ({"blink": False}, "\x1b[25mx y\x1b[0m"),41 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),42 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),43 ({"fg": "black", "reset": False}, "\x1b[30mx y"),44 ],45)46def test_styling(styles, ref):47 assert click.style("x y", **styles) == ref48 assert click.unstyle(ref) == "x y"495051@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])52def test_unstyle_other_ansi(text, expect):53 assert click.unstyle(text) == expect
deleted:tests/test_utils.py-857 removed
1import os2import pathlib3import stat4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import BytesIO12from io import StringIO13from unittest.mock import patch1415import pytest1617import click._termui_impl18import click.utils19from click._compat import WIN20from click._utils import UNSET212223def test_unset_sentinel():24 value = UNSET2526 assert value27 assert value is UNSET28 assert value == UNSET29 assert repr(value) == "Sentinel.UNSET"30 assert str(value) == "Sentinel.UNSET"31 assert bool(value) is True3233 # Try all native Python values that can be falsy or truthy.34 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing35 real_values = (36 None,37 True,38 False,39 0,40 1,41 0.0,42 1.0,43 0j,44 1j,45 Decimal(0),46 Decimal(1),47 Fraction(0, 1),48 Fraction(1, 1),49 "",50 "a",51 "UNSET",52 "Sentinel.UNSET",53 [1],54 (1),55 {1: "a"},56 set(),57 set([1]),58 frozenset(),59 frozenset([1]),60 range(0),61 range(1),62 )6364 for real_value in real_values:65 assert value != real_value66 assert value is not real_value6768 assert value not in real_values697071def test_echo(runner):72 with runner.isolation() as outstreams:73 click.echo("\N{SNOWMAN}")74 click.echo(b"\x44\x44")75 click.echo(42, nl=False)76 click.echo(b"a", nl=False)77 click.echo("\x1b[31mx\x1b[39m", nl=False)78 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")79 assert bytes == b"\xe2\x98\x83\nDD\n42ax"8081 # if wrapped, we expect bytes to survive.82 @click.command()83 def cli():84 click.echo(b"\xf6")8586 result = runner.invoke(cli, [])87 assert result.stdout_bytes == b"\xf6\n"8889 # Ensure we do not strip for bytes.90 with runner.isolation() as outstreams:91 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)92 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"939495def test_echo_custom_file():96 f = StringIO()97 click.echo("hello", file=f)98 assert f.getvalue() == "hello\n"99100 b = BytesIO()101 click.echo(b"", b)102 assert b.getvalue() == b"\n"103104105def test_echo_no_streams(monkeypatch, runner):106 """echo should not fail when stdout and stderr are None with pythonw on Windows."""107 with runner.isolation():108 sys.stdout = None109 sys.stderr = None110 click.echo("test")111 click.echo("test", err=True)112113114@pytest.mark.parametrize(115 ("styles", "ref"),116 [117 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),118 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),119 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),120 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),121 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),122 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),123 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),124 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),125 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),126 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),127 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),128 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),129 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),130 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),131 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),132 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),133 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),134 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),135 ({"bold": True}, "\x1b[1mx y\x1b[0m"),136 ({"dim": True}, "\x1b[2mx y\x1b[0m"),137 ({"underline": True}, "\x1b[4mx y\x1b[0m"),138 ({"overline": True}, "\x1b[53mx y\x1b[0m"),139 ({"italic": True}, "\x1b[3mx y\x1b[0m"),140 ({"blink": True}, "\x1b[5mx y\x1b[0m"),141 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),142 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),143 ({"bold": False}, "\x1b[22mx y\x1b[0m"),144 ({"dim": False}, "\x1b[22mx y\x1b[0m"),145 ({"underline": False}, "\x1b[24mx y\x1b[0m"),146 ({"overline": False}, "\x1b[55mx y\x1b[0m"),147 ({"italic": False}, "\x1b[23mx y\x1b[0m"),148 ({"blink": False}, "\x1b[25mx y\x1b[0m"),149 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),150 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),151 ({"fg": "black", "reset": False}, "\x1b[30mx y"),152 ],153)154def test_styling(styles, ref):155 assert click.style("x y", **styles) == ref156 assert click.unstyle(ref) == "x y"157158159@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])160def test_unstyle_other_ansi(text, expect):161 assert click.unstyle(text) == expect162163164def test_filename_formatting():165 assert click.format_filename(b"foo.txt") == "foo.txt"166 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"167 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"168 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"169 assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"170171172def test_prompts(runner):173 @click.command()174 def test():175 if click.confirm("Foo"):176 click.echo("yes!")177 else:178 click.echo("no :(")179180 result = runner.invoke(test, input="y\n")181 assert not result.exception182 assert result.output == "Foo [y/N]: y\nyes!\n"183184 result = runner.invoke(test, input="\n")185 assert not result.exception186 assert result.output == "Foo [y/N]: \nno :(\n"187188 result = runner.invoke(test, input="n\n")189 assert not result.exception190 assert result.output == "Foo [y/N]: n\nno :(\n"191192 @click.command()193 def test_no():194 if click.confirm("Foo", default=True):195 click.echo("yes!")196 else:197 click.echo("no :(")198199 result = runner.invoke(test_no, input="y\n")200 assert not result.exception201 assert result.output == "Foo [Y/n]: y\nyes!\n"202203 result = runner.invoke(test_no, input="\n")204 assert not result.exception205 assert result.output == "Foo [Y/n]: \nyes!\n"206207 result = runner.invoke(test_no, input="n\n")208 assert not result.exception209 assert result.output == "Foo [Y/n]: n\nno :(\n"210211212def test_confirm_repeat(runner):213 cli = click.Command(214 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]215 )216 result = runner.invoke(cli, input="\ny\n")217 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"218219220@pytest.mark.skipif(WIN, reason="Different behavior on windows.")221def test_prompts_abort(monkeypatch, capsys):222 def f(_):223 raise KeyboardInterrupt()224225 monkeypatch.setattr("click.termui.hidden_prompt_func", f)226227 try:228 click.prompt("Password", hide_input=True)229 except click.Abort:230 click.echo("interrupted")231232 out, err = capsys.readouterr()233 # On non-Windows, prompt is passed directly to getpass, not echoed separately234 assert out == "\ninterrupted\n"235236237@pytest.mark.skipif(WIN, reason="Different behavior on windows.")238@pytest.mark.parametrize(239 ("call", "expected_prompt"),240 [241 (lambda: click.prompt("Name"), "Name: "),242 (lambda: click.prompt("Pw", hide_input=True), "Pw: "),243 (lambda: click.prompt("IP", prompt_suffix="."), "IP."),244 (lambda: click.confirm("OK"), "OK [y/N]: "),245 ],246 ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"],247)248def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt):249 """On non-Windows, prompt and confirm pass the full prompt text to the250 underlying prompt function so readline handles editing correctly.251252 https://github.com/pallets/click/issues/2968253 https://github.com/pallets/click/pull/2969254 """255 received = []256257 def capture(text):258 received.append(text)259 return "y"260261 monkeypatch.setattr("click.termui.visible_prompt_func", capture)262 monkeypatch.setattr("click.termui.hidden_prompt_func", capture)263 call()264 assert received == [expected_prompt]265266267def test_prompts_eof(runner):268 """If too few lines of input are given, prompt should exit, not hang."""269270 @click.command271 def echo():272 for _ in range(3):273 click.echo(click.prompt("", type=int))274275 # only provide two lines of input for three prompts276 result = runner.invoke(echo, input="1\n2\n")277 assert result.exit_code == 1278279280def _test_gen_func():281 yield "a"282 yield "b"283 yield "c"284 yield "abc"285286287def _test_gen_func_fails():288 raise RuntimeError("This is a test.")289 yield # unreachable, keeps this a generator function290291292def _test_gen_func_yields_then_fails():293 yield "test"294 raise RuntimeError("This is a test.")295296297def _test_gen_func_echo(file=None):298 yield "test"299 click.echo("hello", file=file)300 yield "test"301302303def _test_simulate_keyboard_interrupt(file=None):304 yield "output_before_keyboard_interrupt"305 raise KeyboardInterrupt()306307308EchoViaPagerTest = namedtuple(309 "EchoViaPagerTest",310 (311 "description",312 "test_input",313 "expected_pager",314 "expected_stdout",315 "expected_stderr",316 "expected_error",317 ),318)319320321@pytest.mark.skipif(WIN, reason="Different behavior on windows.")322@pytest.mark.parametrize(323 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]324)325@pytest.mark.parametrize(326 "test",327 [328 # We need to pass a parameter function instead of a plain param329 # as pytest.mark.parametrize will reuse the parameters causing the330 # generators to be used up so they will not yield anymore331 EchoViaPagerTest(332 description="Plain string argument",333 test_input=lambda: "just text",334 expected_pager="just text\n",335 expected_stdout="",336 expected_stderr="",337 expected_error=None,338 ),339 EchoViaPagerTest(340 description="Iterable argument",341 test_input=lambda: ["itera", "ble"],342 expected_pager="iterable\n",343 expected_stdout="",344 expected_stderr="",345 expected_error=None,346 ),347 EchoViaPagerTest(348 description="Generator function argument",349 test_input=lambda: _test_gen_func,350 expected_pager="abcabc\n",351 expected_stdout="",352 expected_stderr="",353 expected_error=None,354 ),355 EchoViaPagerTest(356 description="String generator argument",357 test_input=lambda: _test_gen_func(),358 expected_pager="abcabc\n",359 expected_stdout="",360 expected_stderr="",361 expected_error=None,362 ),363 EchoViaPagerTest(364 description="Number generator expression argument",365 test_input=lambda: (c for c in range(6)),366 expected_pager="012345\n",367 expected_stdout="",368 expected_stderr="",369 expected_error=None,370 ),371 EchoViaPagerTest(372 description="Exception in generator function argument",373 test_input=lambda: _test_gen_func_fails,374 # Because generator throws early on, the pager did not have375 # a chance yet to write the file.376 expected_pager="",377 expected_stdout="",378 expected_stderr="",379 expected_error=RuntimeError,380 ),381 EchoViaPagerTest(382 description="Exception in generator argument",383 test_input=lambda: _test_gen_func_fails,384 # Because generator throws early on, the pager did not have a385 # chance yet to write the file.386 expected_pager="",387 expected_stdout="",388 expected_stderr="",389 expected_error=RuntimeError,390 ),391 EchoViaPagerTest(392 description="Keyboard interrupt should not terminate the pager",393 test_input=lambda: _test_simulate_keyboard_interrupt(),394 # Due to the keyboard interrupt during pager execution, click program395 # should abort, but the pager should stay open.396 # This allows users to cancel the program and search in the pager397 # output, before they decide to terminate the pager.398 expected_pager="output_before_keyboard_interrupt",399 expected_stdout="",400 expected_stderr="",401 expected_error=KeyboardInterrupt,402 ),403 EchoViaPagerTest(404 description="Writing to stdout during generator execution",405 test_input=lambda: _test_gen_func_echo(),406 expected_pager="testtest\n",407 expected_stdout="hello\n",408 expected_stderr="",409 expected_error=None,410 ),411 EchoViaPagerTest(412 description="Writing to stderr during generator execution",413 test_input=lambda: _test_gen_func_echo(file=sys.stderr),414 expected_pager="testtest\n",415 expected_stdout="",416 expected_stderr="hello\n",417 expected_error=None,418 ),419 ],420)421def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):422 monkeypatch.setitem(os.environ, "PAGER", pager_cmd)423 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)424425 test_input = test.test_input()426 expected_pager = test.expected_pager427 expected_stdout = test.expected_stdout428 expected_stderr = test.expected_stderr429 expected_error = test.expected_error430431 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()432433 pager_out_tmp = tmp_path / "pager_out.txt"434 with pager_out_tmp.open("w") as f:435 force_subprocess_stdout = patch.object(436 subprocess,437 "Popen",438 partial(subprocess.Popen, stdout=f),439 )440 with force_subprocess_stdout:441 with check_raise:442 click.echo_via_pager(test_input)443444 out, err = capfd.readouterr()445446 pager = pager_out_tmp.read_text()447448 assert pager == expected_pager, (449 f"Unexpected pager output in test case '{test.description}'"450 )451 assert out == expected_stdout, (452 f"Unexpected stdout in test case '{test.description}'"453 )454 assert err == expected_stderr, (455 f"Unexpected stderr in test case '{test.description}'"456 )457458459@pytest.mark.skipif(WIN, reason="Different behavior on windows.")460def test_echo_via_pager_yields_before_exception(monkeypatch, tmp_path):461 """A generator that yields then raises: click writes the partial output to462 the pager stream before propagating the exception.463464 The pager file content is intentionally NOT asserted: pipe-drain timing465 between click and the pager subprocess is outside click's control466 (#2899, #3470). Spying on ``MaybeStripAnsi.write`` records what click sent467 to the pager, which is deterministic regardless of scheduling.468 """469 monkeypatch.setitem(os.environ, "PAGER", "cat")470 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)471472 writes: list[str] = []473 real_write = click._termui_impl.MaybeStripAnsi.write474475 def spy(self, text):476 writes.append(text)477 return real_write(self, text)478479 monkeypatch.setattr(click._termui_impl.MaybeStripAnsi, "write", spy)480481 pager_out_tmp = tmp_path / "pager_out.txt"482 with (483 pager_out_tmp.open("w") as f,484 patch.object(subprocess, "Popen", partial(subprocess.Popen, stdout=f)),485 pytest.raises(RuntimeError, match="This is a test."),486 ):487 click.echo_via_pager(_test_gen_func_yields_then_fails())488489 assert "".join(writes) == "test", (490 f"click should have written the yielded chunk before exception, got {writes!r}"491 )492493494@pytest.mark.stress495@pytest.mark.skipif(WIN, reason="Different behavior on windows.")496@pytest.mark.parametrize("_", range(1000))497def test_stress_echo_via_pager_exception_cleanup(_, monkeypatch, tmp_path):498 """Repeated exceptions during ``echo_via_pager`` must not leak subprocesses.499500 Regression coverage for the cleanup path in ``_pipepager``'s exception501 handler (issue #2899, PR #3470). Each iteration spawns a real pager502 subprocess, raises before any data is written and check there is no leak.503 """504 monkeypatch.setitem(os.environ, "PAGER", "cat")505 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)506507 spawned: list[subprocess.Popen] = []508 real_popen = subprocess.Popen509510 def tracking_popen(*args, **kwargs):511 p = real_popen(*args, **kwargs)512 spawned.append(p)513 return p514515 pager_out_tmp = tmp_path / "pager_out.txt"516 with (517 pager_out_tmp.open("w") as f,518 patch.object(subprocess, "Popen", partial(tracking_popen, stdout=f)),519 pytest.raises(RuntimeError),520 ):521 click.echo_via_pager(_test_gen_func_fails())522523 assert spawned, "pager subprocess was never started"524 for p in spawned:525 assert p.returncode is not None, "pager subprocess not reaped"526527528def test_echo_color_flag(monkeypatch, capfd):529 isatty = True530 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)531532 text = "foo"533 styled_text = click.style(text, fg="red")534 assert styled_text == "\x1b[31mfoo\x1b[0m"535536 click.echo(styled_text, color=False)537 out, err = capfd.readouterr()538 assert out == f"{text}\n"539540 click.echo(styled_text, color=True)541 out, err = capfd.readouterr()542 assert out == f"{styled_text}\n"543544 click.echo(styled_text)545 out, err = capfd.readouterr()546 assert out == f"{styled_text}\n"547548 isatty = False549 click.echo(styled_text)550 out, err = capfd.readouterr()551 assert out == f"{text}\n"552553 click.echo(styled_text, color=True)554 out, err = capfd.readouterr()555 assert out == f"{styled_text}\n"556557558def test_prompt_cast_default(capfd, monkeypatch):559 monkeypatch.setattr(sys, "stdin", StringIO("\n"))560 value = click.prompt("value", default="100", type=int)561 capfd.readouterr()562 assert isinstance(value, int)563564565@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")566def test_echo_writing_to_standard_error(capfd, monkeypatch):567 def emulate_input(text):568 """Emulate keyboard input."""569 monkeypatch.setattr(sys, "stdin", StringIO(text))570571 click.echo("Echo to standard output")572 out, err = capfd.readouterr()573 assert out == "Echo to standard output\n"574 assert err == ""575576 click.echo("Echo to standard error", err=True)577 out, err = capfd.readouterr()578 assert out == ""579 assert err == "Echo to standard error\n"580581 emulate_input("asdlkj\n")582 click.prompt("Prompt to stdin")583 out, err = capfd.readouterr()584 assert out == "Prompt to stdin: "585 assert err == ""586587 emulate_input("asdlkj\n")588 click.prompt("Prompt to stdin with no suffix", prompt_suffix="")589 out, err = capfd.readouterr()590 assert out == "Prompt to stdin with no suffix"591 assert err == ""592593 # On non-Windows the full prompt goes through redirect_stdout so594 # nothing leaks to stdout when err=True.595 # https://github.com/pallets/click/issues/2968596 emulate_input("asdlkj\n")597 click.prompt("Prompt to stderr", err=True)598 out, err = capfd.readouterr()599 assert out == ""600 assert err == "Prompt to stderr: "601602 # https://github.com/pallets/click/issues/3019603 emulate_input("asdlkj\n")604 click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)605 out, err = capfd.readouterr()606 assert out == ""607 assert err == "Prompt to stderr with no suffix"608609 emulate_input("y\n")610 click.confirm("Prompt to stdin")611 out, err = capfd.readouterr()612 assert out == "Prompt to stdin [y/N]: "613 assert err == ""614615 emulate_input("y\n")616 click.confirm("Prompt to stdin with no suffix", prompt_suffix="")617 out, err = capfd.readouterr()618 assert out == "Prompt to stdin with no suffix [y/N]"619 assert err == ""620621 # https://github.com/pallets/click/issues/2968622 emulate_input("y\n")623 click.confirm("Prompt to stderr", err=True)624 out, err = capfd.readouterr()625 assert out == ""626 assert err == "Prompt to stderr [y/N]: "627628 # https://github.com/pallets/click/issues/3019629 emulate_input("y\n")630 click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)631 out, err = capfd.readouterr()632 assert out == ""633 assert err == "Prompt to stderr with no suffix [y/N]"634635 monkeypatch.setattr(click.termui, "isatty", lambda x: True)636 monkeypatch.setattr(click.termui, "getchar", lambda: " ")637638 click.pause("Pause to stdout")639 out, err = capfd.readouterr()640 assert out == "Pause to stdout\n"641 assert err == ""642643 click.pause("Pause to stderr", err=True)644 out, err = capfd.readouterr()645 assert out == ""646 assert err == "Pause to stderr\n"647648649def test_echo_with_capsys(capsys):650 click.echo("Capture me.")651 out, err = capsys.readouterr()652 assert out == "Capture me.\n"653654655def test_open_file(runner):656 @click.command()657 @click.argument("filename")658 def cli(filename):659 with click.open_file(filename) as f:660 click.echo(f.read())661662 click.echo("meep")663664 with runner.isolated_filesystem():665 with open("hello.txt", "w") as f:666 f.write("Cool stuff")667668 result = runner.invoke(cli, ["hello.txt"])669 assert result.exception is None670 assert result.output == "Cool stuff\nmeep\n"671672 result = runner.invoke(cli, ["-"], input="foobar")673 assert result.exception is None674 assert result.output == "foobar\nmeep\n"675676677def test_open_file_pathlib_dash(runner):678 @click.command()679 @click.argument(680 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)681 )682 def cli(filename):683 click.echo(str(type(filename)))684685 with click.open_file(filename) as f:686 click.echo(f.read())687688 result = runner.invoke(cli, ["-"], input="value")689 assert result.exception is None690 assert result.output == "pathlib.Path\nvalue\n"691692693def test_open_file_ignore_errors_stdin(runner):694 @click.command()695 @click.argument("filename")696 def cli(filename):697 with click.open_file(filename, errors="ignore") as f:698 click.echo(f.read())699700 result = runner.invoke(cli, ["-"], input=os.urandom(16))701 assert result.exception is None702703704def test_open_file_respects_ignore(runner):705 with runner.isolated_filesystem():706 with open("test.txt", "w") as f:707 f.write("Hello world!")708709 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:710 assert f.errors == "ignore"711712713def test_open_file_ignore_invalid_utf8(runner):714 with runner.isolated_filesystem():715 with open("test.txt", "wb") as f:716 f.write(b"\xe2\x28\xa1")717718 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:719 f.read()720721722def test_open_file_ignore_no_encoding(runner):723 with runner.isolated_filesystem():724 with open("test.bin", "wb") as f:725 f.write(os.urandom(16))726727 with click.open_file("test.bin", errors="ignore") as f:728 f.read()729730731@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")732@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])733def test_open_file_atomic_permissions_existing_file(runner, permissions):734 with runner.isolated_filesystem():735 with open("existing.txt", "w") as f:736 f.write("content")737 os.chmod("existing.txt", permissions)738739 @click.command()740 @click.argument("filename")741 def cli(filename):742 click.open_file(filename, "w", atomic=True).close()743744 result = runner.invoke(cli, ["existing.txt"])745 assert result.exception is None746 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions747748749@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")750def test_open_file_atomic_permissions_new_file(runner):751 with runner.isolated_filesystem():752753 @click.command()754 @click.argument("filename")755 def cli(filename):756 click.open_file(filename, "w", atomic=True).close()757758 # Create a test file to get the expected permissions for new files759 # according to the current umask.760 with open("test.txt", "w"):761 pass762 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)763764 result = runner.invoke(cli, ["new.txt"])765 assert result.exception is None766 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions767768769def test_iter_keepopenfile(tmpdir):770 expected = list(map(str, range(10)))771 p = tmpdir.mkdir("testdir").join("testfile")772 p.write("\n".join(expected))773 with p.open() as f:774 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):775 assert e_line == a_line.strip()776777778def test_iter_lazyfile(tmpdir):779 expected = list(map(str, range(10)))780 p = tmpdir.mkdir("testdir").join("testfile")781 p.write("\n".join(expected))782 with p.open() as f:783 with click.utils.LazyFile(f.name) as lf:784 for e_line, a_line in zip(expected, lf, strict=False):785 assert e_line == a_line.strip()786787788class MockMain:789 __slots__ = "__package__"790791 def __init__(self, package_name):792 self.__package__ = package_name793794795@pytest.mark.parametrize(796 ("path", "main", "expected"),797 [798 ("example.py", None, "example.py"),799 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),800 ("example", None, "example"),801 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),802 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),803 (str(pathlib.Path("./example")), "", "example"),804 ],805)806def test_detect_program_name(path, main, expected):807 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected808809810def test_expand_args(monkeypatch):811 user = os.path.expanduser("~")812 assert user in click.utils._expand_args(["~"])813 monkeypatch.setenv("CLICK_TEST", "hello")814 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])815 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])816 assert os.path.join("tests", "conftest.py") in click.utils._expand_args(817 ["**/conftest.py"]818 )819 assert "*.not-found" in click.utils._expand_args(["*.not-found"])820 # a bad glob pattern, such as a pytest identifier, should return itself821 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"822823824@pytest.mark.parametrize(825 ("value", "max_length", "expect"),826 [827 pytest.param("", 10, "", id="empty"),828 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),829 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),830 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),831 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),832 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),833 pytest.param(834 "token in ~/.netrc ciao ciao",835 20,836 "token in ~/.netrc...",837 id="ignore dot in word",838 ),839 ],840)841@pytest.mark.parametrize(842 "alter",843 [844 pytest.param(None, id=""),845 pytest.param(846 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"847 ),848 ],849)850def test_make_default_short_help(value, max_length, alter, expect):851 assert len(expect) <= max_length852853 if alter:854 value = alter(value)855856 out = click.utils.make_default_short_help(value, max_length)857 assert out == expect