Skip to content
Myr

Add files for _detect_program_name, _expand_args, and make_default_short_help.

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

authored by Edward G · committed by Edward G · parent 7007982 · Browse files · 26 files+898 added−894 removed
This commit

State

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

Diff stats

26 files+898 added−894 removed

  • tests:+898 added−894 removed

26 files+898 added−894 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_2/__init__.py
deleted:tests/test_utils_2/test_confirm.py-49 removed
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"
deleted:tests/test_utils_2/test_echo_via_pager.py-259 removed
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"
deleted:tests/test_utils_2/test_echo.py-176 removed
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"
deleted:tests/test_utils_2/test_format_filename.py-9 removed
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"
deleted:tests/test_utils_2/test_KeepOpenFile.py-10 removed
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()
deleted:tests/test_utils_2/test_LazyFile.py-11 removed
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()
deleted:tests/test_utils_2/test_open_file.py-122 removed
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
deleted:tests/test_utils_2/test_prompt.py-74 removed
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
deleted:tests/test_utils_2/test_sentinel.py-52 removed
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
deleted:tests/test_utils_2/test_style.py-53 removed
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-79 removed
1import os2import pathlib34import pytest56import click._termui_impl7import click.utils8910class MockMain:11 __slots__ = "__package__"1213 def __init__(self, package_name):14 self.__package__ = package_name151617@pytest.mark.parametrize(18 ("path", "main", "expected"),19 [20 ("example.py", None, "example.py"),21 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),22 ("example", None, "example"),23 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),24 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),25 (str(pathlib.Path("./example")), "", "example"),26 ],27)28def test_detect_program_name(path, main, expected):29 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected303132def test_expand_args(monkeypatch):33 user = os.path.expanduser("~")34 assert user in click.utils._expand_args(["~"])35 monkeypatch.setenv("CLICK_TEST", "hello")36 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])37 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])38 assert os.path.join("tests", "conftest.py") in click.utils._expand_args(39 ["**/conftest.py"]40 )41 assert "*.not-found" in click.utils._expand_args(["*.not-found"])42 # a bad glob pattern, such as a pytest identifier, should return itself43 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"444546@pytest.mark.parametrize(47 ("value", "max_length", "expect"),48 [49 pytest.param("", 10, "", id="empty"),50 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),51 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),52 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),53 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),54 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),55 pytest.param(56 "token in ~/.netrc ciao ciao",57 20,58 "token in ~/.netrc...",59 id="ignore dot in word",60 ),61 ],62)63@pytest.mark.parametrize(64 "alter",65 [66 pytest.param(None, id=""),67 pytest.param(68 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"69 ),70 ],71)72def test_make_default_short_help(value, max_length, alter, expect):73 assert len(expect) <= max_length7475 if alter:76 value = alter(value)7778 out = click.utils.make_default_short_help(value, max_length)79 assert out == expect