test_utils.py
This file
Path
tests/test_utils.py
658 lines · 20.9 KiB · Python
Last changed by
drop end of life python versions (#2893)David Lordbefore adoption498f882
History of this fileTake it
1import os2import pathlib3import stat4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from functools import partial9from io import StringIO10from pathlib import Path11from tempfile import tempdir12from unittest.mock import patch1314import pytest1516import click._termui_impl17import click.utils18from click._compat import WIN192021def test_echo(runner):22 with runner.isolation() as outstreams:23 click.echo("\N{SNOWMAN}")24 click.echo(b"\x44\x44")25 click.echo(42, nl=False)26 click.echo(b"a", nl=False)27 click.echo("\x1b[31mx\x1b[39m", nl=False)28 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")29 assert bytes == b"\xe2\x98\x83\nDD\n42ax"3031 # if wrapped, we expect bytes to survive.32 @click.command()33 def cli():34 click.echo(b"\xf6")3536 result = runner.invoke(cli, [])37 assert result.stdout_bytes == b"\xf6\n"3839 # Ensure we do not strip for bytes.40 with runner.isolation() as outstreams:41 click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)42 assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"434445def test_echo_custom_file():46 f = StringIO()47 click.echo("hello", file=f)48 assert f.getvalue() == "hello\n"495051def test_echo_no_streams(monkeypatch, runner):52 """echo should not fail when stdout and stderr are None with pythonw on Windows."""53 with runner.isolation():54 sys.stdout = None55 sys.stderr = None56 click.echo("test")57 click.echo("test", err=True)585960@pytest.mark.parametrize(61 ("styles", "ref"),62 [63 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),64 ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),65 ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),66 ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),67 ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),68 ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),69 ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),70 ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),71 ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),72 ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),73 ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),74 ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),75 ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),76 ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),77 ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),78 ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),79 ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),80 ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),81 ({"bold": True}, "\x1b[1mx y\x1b[0m"),82 ({"dim": True}, "\x1b[2mx y\x1b[0m"),83 ({"underline": True}, "\x1b[4mx y\x1b[0m"),84 ({"overline": True}, "\x1b[53mx y\x1b[0m"),85 ({"italic": True}, "\x1b[3mx y\x1b[0m"),86 ({"blink": True}, "\x1b[5mx y\x1b[0m"),87 ({"reverse": True}, "\x1b[7mx y\x1b[0m"),88 ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),89 ({"bold": False}, "\x1b[22mx y\x1b[0m"),90 ({"dim": False}, "\x1b[22mx y\x1b[0m"),91 ({"underline": False}, "\x1b[24mx y\x1b[0m"),92 ({"overline": False}, "\x1b[55mx y\x1b[0m"),93 ({"italic": False}, "\x1b[23mx y\x1b[0m"),94 ({"blink": False}, "\x1b[25mx y\x1b[0m"),95 ({"reverse": False}, "\x1b[27mx y\x1b[0m"),96 ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),97 ({"fg": "black", "reset": False}, "\x1b[30mx y"),98 ],99)100def test_styling(styles, ref):101 assert click.style("x y", **styles) == ref102 assert click.unstyle(ref) == "x y"103104105@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])106def test_unstyle_other_ansi(text, expect):107 assert click.unstyle(text) == expect108109110def test_filename_formatting():111 assert click.format_filename(b"foo.txt") == "foo.txt"112 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"113 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"114 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"115 assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"116117118def test_prompts(runner):119 @click.command()120 def test():121 if click.confirm("Foo"):122 click.echo("yes!")123 else:124 click.echo("no :(")125126 result = runner.invoke(test, input="y\n")127 assert not result.exception128 assert result.output == "Foo [y/N]: y\nyes!\n"129130 result = runner.invoke(test, input="\n")131 assert not result.exception132 assert result.output == "Foo [y/N]: \nno :(\n"133134 result = runner.invoke(test, input="n\n")135 assert not result.exception136 assert result.output == "Foo [y/N]: n\nno :(\n"137138 @click.command()139 def test_no():140 if click.confirm("Foo", default=True):141 click.echo("yes!")142 else:143 click.echo("no :(")144145 result = runner.invoke(test_no, input="y\n")146 assert not result.exception147 assert result.output == "Foo [Y/n]: y\nyes!\n"148149 result = runner.invoke(test_no, input="\n")150 assert not result.exception151 assert result.output == "Foo [Y/n]: \nyes!\n"152153 result = runner.invoke(test_no, input="n\n")154 assert not result.exception155 assert result.output == "Foo [Y/n]: n\nno :(\n"156157158def test_confirm_repeat(runner):159 cli = click.Command(160 "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]161 )162 result = runner.invoke(cli, input="\ny\n")163 assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"164165166@pytest.mark.skipif(WIN, reason="Different behavior on windows.")167def test_prompts_abort(monkeypatch, capsys):168 def f(_):169 raise KeyboardInterrupt()170171 monkeypatch.setattr("click.termui.hidden_prompt_func", f)172173 try:174 click.prompt("Password", hide_input=True)175 except click.Abort:176 click.echo("interrupted")177178 out, err = capsys.readouterr()179 assert out == "Password:\ninterrupted\n"180181182def _test_gen_func():183 yield "a"184 yield "b"185 yield "c"186 yield "abc"187188189def _test_gen_func_fails():190 yield "test"191 raise RuntimeError("This is a test.")192193194def _test_gen_func_echo(file=None):195 yield "test"196 click.echo("hello", file=file)197 yield "test"198199200def _test_simulate_keyboard_interrupt(file=None):201 yield "output_before_keyboard_interrupt"202 raise KeyboardInterrupt()203204205EchoViaPagerTest = namedtuple(206 "EchoViaPagerTest",207 (208 "description",209 "test_input",210 "expected_pager",211 "expected_stdout",212 "expected_stderr",213 "expected_error",214 ),215)216217218@pytest.mark.skipif(WIN, reason="Different behavior on windows.")219@pytest.mark.parametrize(220 "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]221)222@pytest.mark.parametrize(223 "test",224 [225 # We need to pass a parameter function instead of a plain param226 # as pytest.mark.parametrize will reuse the parameters causing the227 # generators to be used up so they will not yield anymore228 EchoViaPagerTest(229 description="Plain string argument",230 test_input=lambda: "just text",231 expected_pager="just text\n",232 expected_stdout="",233 expected_stderr="",234 expected_error=None,235 ),236 EchoViaPagerTest(237 description="Iterable argument",238 test_input=lambda: ["itera", "ble"],239 expected_pager="iterable\n",240 expected_stdout="",241 expected_stderr="",242 expected_error=None,243 ),244 EchoViaPagerTest(245 description="Generator function argument",246 test_input=lambda: _test_gen_func,247 expected_pager="abcabc\n",248 expected_stdout="",249 expected_stderr="",250 expected_error=None,251 ),252 EchoViaPagerTest(253 description="String generator argument",254 test_input=lambda: _test_gen_func(),255 expected_pager="abcabc\n",256 expected_stdout="",257 expected_stderr="",258 expected_error=None,259 ),260 EchoViaPagerTest(261 description="Number generator expression argument",262 test_input=lambda: (c for c in range(6)),263 expected_pager="012345\n",264 expected_stdout="",265 expected_stderr="",266 expected_error=None,267 ),268 EchoViaPagerTest(269 description="Exception in generator function argument",270 test_input=lambda: _test_gen_func_fails,271 # Because generator throws early on, the pager did not have272 # a chance yet to write the file.273 expected_pager="",274 expected_stdout="",275 expected_stderr="",276 expected_error=RuntimeError,277 ),278 EchoViaPagerTest(279 description="Exception in generator argument",280 test_input=lambda: _test_gen_func_fails,281 # Because generator throws early on, the pager did not have a282 # chance yet to write the file.283 expected_pager="",284 expected_stdout="",285 expected_stderr="",286 expected_error=RuntimeError,287 ),288 EchoViaPagerTest(289 description="Keyboard interrupt should not terminate the pager",290 test_input=lambda: _test_simulate_keyboard_interrupt(),291 # Due to the keyboard interrupt during pager execution, click program292 # should abort, but the pager should stay open.293 # This allows users to cancel the program and search in the pager294 # output, before they decide to terminate the pager.295 expected_pager="output_before_keyboard_interrupt",296 expected_stdout="",297 expected_stderr="",298 expected_error=KeyboardInterrupt,299 ),300 EchoViaPagerTest(301 description="Writing to stdout during generator execution",302 test_input=lambda: _test_gen_func_echo(),303 expected_pager="testtest\n",304 expected_stdout="hello\n",305 expected_stderr="",306 expected_error=None,307 ),308 EchoViaPagerTest(309 description="Writing to stderr during generator execution",310 test_input=lambda: _test_gen_func_echo(file=sys.stderr),311 expected_pager="testtest\n",312 expected_stdout="",313 expected_stderr="hello\n",314 expected_error=None,315 ),316 ],317)318def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):319 monkeypatch.setitem(os.environ, "PAGER", pager_cmd)320 monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)321322 test_input = test.test_input()323 expected_pager = test.expected_pager324 expected_stdout = test.expected_stdout325 expected_stderr = test.expected_stderr326 expected_error = test.expected_error327328 check_raise = pytest.raises(expected_error) if expected_error else nullcontext()329330 pager_out_tmp = Path(tempdir) / "pager_out.txt"331 pager_out_tmp.unlink(missing_ok=True)332 with pager_out_tmp.open("w") as f:333 force_subprocess_stdout = patch.object(334 subprocess,335 "Popen",336 partial(subprocess.Popen, stdout=f),337 )338 with force_subprocess_stdout:339 with check_raise:340 click.echo_via_pager(test_input)341342 out, err = capfd.readouterr()343344 pager = pager_out_tmp.read_text()345346 assert pager == expected_pager, (347 f"Unexpected pager output in test case '{test.description}'"348 )349 assert out == expected_stdout, (350 f"Unexpected stdout in test case '{test.description}'"351 )352 assert err == expected_stderr, (353 f"Unexpected stderr in test case '{test.description}'"354 )355356357def test_echo_color_flag(monkeypatch, capfd):358 isatty = True359 monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)360361 text = "foo"362 styled_text = click.style(text, fg="red")363 assert styled_text == "\x1b[31mfoo\x1b[0m"364365 click.echo(styled_text, color=False)366 out, err = capfd.readouterr()367 assert out == f"{text}\n"368369 click.echo(styled_text, color=True)370 out, err = capfd.readouterr()371 assert out == f"{styled_text}\n"372373 isatty = True374 click.echo(styled_text)375 out, err = capfd.readouterr()376 assert out == f"{styled_text}\n"377378 isatty = False379 # Faking isatty() is not enough on Windows;380 # the implementation caches the colorama wrapped stream381 # so we have to use a new stream for each test382 stream = StringIO()383 click.echo(styled_text, file=stream)384 assert stream.getvalue() == f"{text}\n"385386 stream = StringIO()387 click.echo(styled_text, file=stream, color=True)388 assert stream.getvalue() == f"{styled_text}\n"389390391def test_prompt_cast_default(capfd, monkeypatch):392 monkeypatch.setattr(sys, "stdin", StringIO("\n"))393 value = click.prompt("value", default="100", type=int)394 capfd.readouterr()395 assert isinstance(value, int)396397398@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")399def test_echo_writing_to_standard_error(capfd, monkeypatch):400 def emulate_input(text):401 """Emulate keyboard input."""402 monkeypatch.setattr(sys, "stdin", StringIO(text))403404 click.echo("Echo to standard output")405 out, err = capfd.readouterr()406 assert out == "Echo to standard output\n"407 assert err == ""408409 click.echo("Echo to standard error", err=True)410 out, err = capfd.readouterr()411 assert out == ""412 assert err == "Echo to standard error\n"413414 emulate_input("asdlkj\n")415 click.prompt("Prompt to stdin")416 out, err = capfd.readouterr()417 assert out == "Prompt to stdin: "418 assert err == ""419420 emulate_input("asdlkj\n")421 click.prompt("Prompt to stderr", err=True)422 out, err = capfd.readouterr()423 assert out == " "424 assert err == "Prompt to stderr:"425426 emulate_input("y\n")427 click.confirm("Prompt to stdin")428 out, err = capfd.readouterr()429 assert out == "Prompt to stdin [y/N]: "430 assert err == ""431432 emulate_input("y\n")433 click.confirm("Prompt to stderr", err=True)434 out, err = capfd.readouterr()435 assert out == " "436 assert err == "Prompt to stderr [y/N]:"437438 monkeypatch.setattr(click.termui, "isatty", lambda x: True)439 monkeypatch.setattr(click.termui, "getchar", lambda: " ")440441 click.pause("Pause to stdout")442 out, err = capfd.readouterr()443 assert out == "Pause to stdout\n"444 assert err == ""445446 click.pause("Pause to stderr", err=True)447 out, err = capfd.readouterr()448 assert out == ""449 assert err == "Pause to stderr\n"450451452def test_echo_with_capsys(capsys):453 click.echo("Capture me.")454 out, err = capsys.readouterr()455 assert out == "Capture me.\n"456457458def test_open_file(runner):459 @click.command()460 @click.argument("filename")461 def cli(filename):462 with click.open_file(filename) as f:463 click.echo(f.read())464465 click.echo("meep")466467 with runner.isolated_filesystem():468 with open("hello.txt", "w") as f:469 f.write("Cool stuff")470471 result = runner.invoke(cli, ["hello.txt"])472 assert result.exception is None473 assert result.output == "Cool stuff\nmeep\n"474475 result = runner.invoke(cli, ["-"], input="foobar")476 assert result.exception is None477 assert result.output == "foobar\nmeep\n"478479480def test_open_file_pathlib_dash(runner):481 @click.command()482 @click.argument(483 "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)484 )485 def cli(filename):486 click.echo(str(type(filename)))487488 with click.open_file(filename) as f:489 click.echo(f.read())490491 result = runner.invoke(cli, ["-"], input="value")492 assert result.exception is None493 assert result.output == "pathlib.Path\nvalue\n"494495496def test_open_file_ignore_errors_stdin(runner):497 @click.command()498 @click.argument("filename")499 def cli(filename):500 with click.open_file(filename, errors="ignore") as f:501 click.echo(f.read())502503 result = runner.invoke(cli, ["-"], input=os.urandom(16))504 assert result.exception is None505506507def test_open_file_respects_ignore(runner):508 with runner.isolated_filesystem():509 with open("test.txt", "w") as f:510 f.write("Hello world!")511512 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:513 assert f.errors == "ignore"514515516def test_open_file_ignore_invalid_utf8(runner):517 with runner.isolated_filesystem():518 with open("test.txt", "wb") as f:519 f.write(b"\xe2\x28\xa1")520521 with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:522 f.read()523524525def test_open_file_ignore_no_encoding(runner):526 with runner.isolated_filesystem():527 with open("test.bin", "wb") as f:528 f.write(os.urandom(16))529530 with click.open_file("test.bin", errors="ignore") as f:531 f.read()532533534@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")535@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])536def test_open_file_atomic_permissions_existing_file(runner, permissions):537 with runner.isolated_filesystem():538 with open("existing.txt", "w") as f:539 f.write("content")540 os.chmod("existing.txt", permissions)541542 @click.command()543 @click.argument("filename")544 def cli(filename):545 click.open_file(filename, "w", atomic=True).close()546547 result = runner.invoke(cli, ["existing.txt"])548 assert result.exception is None549 assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions550551552@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")553def test_open_file_atomic_permissions_new_file(runner):554 with runner.isolated_filesystem():555556 @click.command()557 @click.argument("filename")558 def cli(filename):559 click.open_file(filename, "w", atomic=True).close()560561 # Create a test file to get the expected permissions for new files562 # according to the current umask.563 with open("test.txt", "w"):564 pass565 permissions = stat.S_IMODE(os.stat("test.txt").st_mode)566567 result = runner.invoke(cli, ["new.txt"])568 assert result.exception is None569 assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions570571572def test_iter_keepopenfile(tmpdir):573 expected = list(map(str, range(10)))574 p = tmpdir.mkdir("testdir").join("testfile")575 p.write("\n".join(expected))576 with p.open() as f:577 for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):578 assert e_line == a_line.strip()579580581def test_iter_lazyfile(tmpdir):582 expected = list(map(str, range(10)))583 p = tmpdir.mkdir("testdir").join("testfile")584 p.write("\n".join(expected))585 with p.open() as f:586 with click.utils.LazyFile(f.name) as lf:587 for e_line, a_line in zip(expected, lf, strict=False):588 assert e_line == a_line.strip()589590591class MockMain:592 __slots__ = "__package__"593594 def __init__(self, package_name):595 self.__package__ = package_name596597598@pytest.mark.parametrize(599 ("path", "main", "expected"),600 [601 ("example.py", None, "example.py"),602 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),603 ("example", None, "example"),604 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),605 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),606 (str(pathlib.Path("./example")), "", "example"),607 ],608)609def test_detect_program_name(path, main, expected):610 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected611612613def test_expand_args(monkeypatch):614 user = os.path.expanduser("~")615 assert user in click.utils._expand_args(["~"])616 monkeypatch.setenv("CLICK_TEST", "hello")617 assert "hello" in click.utils._expand_args(["$CLICK_TEST"])618 assert "pyproject.toml" in click.utils._expand_args(["*.toml"])619 assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])620 assert "*.not-found" in click.utils._expand_args(["*.not-found"])621 # a bad glob pattern, such as a pytest identifier, should return itself622 assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"623624625@pytest.mark.parametrize(626 ("value", "max_length", "expect"),627 [628 pytest.param("", 10, "", id="empty"),629 pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),630 pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),631 pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),632 pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),633 pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),634 pytest.param(635 "token in ~/.netrc ciao ciao",636 20,637 "token in ~/.netrc...",638 id="ignore dot in word",639 ),640 ],641)642@pytest.mark.parametrize(643 "alter",644 [645 pytest.param(None, id=""),646 pytest.param(647 lambda text: "\n\b\n" + " ".join(text.split(" ")) + "\n", id="no-wrap mark"648 ),649 ],650)651def test_make_default_short_help(value, max_length, alter, expect):652 assert len(expect) <= max_length653654 if alter:655 value = alter(value)656657 out = click.utils.make_default_short_help(value, max_length)658 assert out == expect