Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

671 lines · 21.3 KiB · Python

Last changed by

Raise an exception on end of input in CliRunner (#2934)David Lordbefore adoption262bdf0

History of this file

Take 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("/x/\ufffd.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_prompts_eof(runner):183    """If too few lines of input are given, prompt should exit, not hang."""184185    @click.command186    def echo():187        for _ in range(3):188            click.echo(click.prompt("", type=int))189190    # only provide two lines of input for three prompts191    result = runner.invoke(echo, input="1\n2\n")192    assert result.exit_code == 1193194195def _test_gen_func():196    yield "a"197    yield "b"198    yield "c"199    yield "abc"200201202def _test_gen_func_fails():203    yield "test"204    raise RuntimeError("This is a test.")205206207def _test_gen_func_echo(file=None):208    yield "test"209    click.echo("hello", file=file)210    yield "test"211212213def _test_simulate_keyboard_interrupt(file=None):214    yield "output_before_keyboard_interrupt"215    raise KeyboardInterrupt()216217218EchoViaPagerTest = namedtuple(219    "EchoViaPagerTest",220    (221        "description",222        "test_input",223        "expected_pager",224        "expected_stdout",225        "expected_stderr",226        "expected_error",227    ),228)229230231@pytest.mark.skipif(WIN, reason="Different behavior on windows.")232@pytest.mark.parametrize(233    "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]234)235@pytest.mark.parametrize(236    "test",237    [238        # We need to pass a parameter function instead of a plain param239        # as pytest.mark.parametrize will reuse the parameters causing the240        # generators to be used up so they will not yield anymore241        EchoViaPagerTest(242            description="Plain string argument",243            test_input=lambda: "just text",244            expected_pager="just text\n",245            expected_stdout="",246            expected_stderr="",247            expected_error=None,248        ),249        EchoViaPagerTest(250            description="Iterable argument",251            test_input=lambda: ["itera", "ble"],252            expected_pager="iterable\n",253            expected_stdout="",254            expected_stderr="",255            expected_error=None,256        ),257        EchoViaPagerTest(258            description="Generator function argument",259            test_input=lambda: _test_gen_func,260            expected_pager="abcabc\n",261            expected_stdout="",262            expected_stderr="",263            expected_error=None,264        ),265        EchoViaPagerTest(266            description="String generator argument",267            test_input=lambda: _test_gen_func(),268            expected_pager="abcabc\n",269            expected_stdout="",270            expected_stderr="",271            expected_error=None,272        ),273        EchoViaPagerTest(274            description="Number generator expression argument",275            test_input=lambda: (c for c in range(6)),276            expected_pager="012345\n",277            expected_stdout="",278            expected_stderr="",279            expected_error=None,280        ),281        EchoViaPagerTest(282            description="Exception in generator function argument",283            test_input=lambda: _test_gen_func_fails,284            # Because generator throws early on, the pager did not have285            # a chance yet to write the file.286            expected_pager="",287            expected_stdout="",288            expected_stderr="",289            expected_error=RuntimeError,290        ),291        EchoViaPagerTest(292            description="Exception in generator argument",293            test_input=lambda: _test_gen_func_fails,294            # Because generator throws early on, the pager did not have a295            # chance yet to write the file.296            expected_pager="",297            expected_stdout="",298            expected_stderr="",299            expected_error=RuntimeError,300        ),301        EchoViaPagerTest(302            description="Keyboard interrupt should not terminate the pager",303            test_input=lambda: _test_simulate_keyboard_interrupt(),304            # Due to the keyboard interrupt during pager execution, click program305            # should abort, but the pager should stay open.306            # This allows users to cancel the program and search in the pager307            # output, before they decide to terminate the pager.308            expected_pager="output_before_keyboard_interrupt",309            expected_stdout="",310            expected_stderr="",311            expected_error=KeyboardInterrupt,312        ),313        EchoViaPagerTest(314            description="Writing to stdout during generator execution",315            test_input=lambda: _test_gen_func_echo(),316            expected_pager="testtest\n",317            expected_stdout="hello\n",318            expected_stderr="",319            expected_error=None,320        ),321        EchoViaPagerTest(322            description="Writing to stderr during generator execution",323            test_input=lambda: _test_gen_func_echo(file=sys.stderr),324            expected_pager="testtest\n",325            expected_stdout="",326            expected_stderr="hello\n",327            expected_error=None,328        ),329    ],330)331def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):332    monkeypatch.setitem(os.environ, "PAGER", pager_cmd)333    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)334335    test_input = test.test_input()336    expected_pager = test.expected_pager337    expected_stdout = test.expected_stdout338    expected_stderr = test.expected_stderr339    expected_error = test.expected_error340341    check_raise = pytest.raises(expected_error) if expected_error else nullcontext()342343    pager_out_tmp = Path(tempdir) / "pager_out.txt"344    pager_out_tmp.unlink(missing_ok=True)345    with pager_out_tmp.open("w") as f:346        force_subprocess_stdout = patch.object(347            subprocess,348            "Popen",349            partial(subprocess.Popen, stdout=f),350        )351        with force_subprocess_stdout:352            with check_raise:353                click.echo_via_pager(test_input)354355    out, err = capfd.readouterr()356357    pager = pager_out_tmp.read_text()358359    assert pager == expected_pager, (360        f"Unexpected pager output in test case '{test.description}'"361    )362    assert out == expected_stdout, (363        f"Unexpected stdout in test case '{test.description}'"364    )365    assert err == expected_stderr, (366        f"Unexpected stderr in test case '{test.description}'"367    )368369370def test_echo_color_flag(monkeypatch, capfd):371    isatty = True372    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)373374    text = "foo"375    styled_text = click.style(text, fg="red")376    assert styled_text == "\x1b[31mfoo\x1b[0m"377378    click.echo(styled_text, color=False)379    out, err = capfd.readouterr()380    assert out == f"{text}\n"381382    click.echo(styled_text, color=True)383    out, err = capfd.readouterr()384    assert out == f"{styled_text}\n"385386    isatty = True387    click.echo(styled_text)388    out, err = capfd.readouterr()389    assert out == f"{styled_text}\n"390391    isatty = False392    # Faking isatty() is not enough on Windows;393    # the implementation caches the colorama wrapped stream394    # so we have to use a new stream for each test395    stream = StringIO()396    click.echo(styled_text, file=stream)397    assert stream.getvalue() == f"{text}\n"398399    stream = StringIO()400    click.echo(styled_text, file=stream, color=True)401    assert stream.getvalue() == f"{styled_text}\n"402403404def test_prompt_cast_default(capfd, monkeypatch):405    monkeypatch.setattr(sys, "stdin", StringIO("\n"))406    value = click.prompt("value", default="100", type=int)407    capfd.readouterr()408    assert isinstance(value, int)409410411@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")412def test_echo_writing_to_standard_error(capfd, monkeypatch):413    def emulate_input(text):414        """Emulate keyboard input."""415        monkeypatch.setattr(sys, "stdin", StringIO(text))416417    click.echo("Echo to standard output")418    out, err = capfd.readouterr()419    assert out == "Echo to standard output\n"420    assert err == ""421422    click.echo("Echo to standard error", err=True)423    out, err = capfd.readouterr()424    assert out == ""425    assert err == "Echo to standard error\n"426427    emulate_input("asdlkj\n")428    click.prompt("Prompt to stdin")429    out, err = capfd.readouterr()430    assert out == "Prompt to stdin: "431    assert err == ""432433    emulate_input("asdlkj\n")434    click.prompt("Prompt to stderr", err=True)435    out, err = capfd.readouterr()436    assert out == " "437    assert err == "Prompt to stderr:"438439    emulate_input("y\n")440    click.confirm("Prompt to stdin")441    out, err = capfd.readouterr()442    assert out == "Prompt to stdin [y/N]: "443    assert err == ""444445    emulate_input("y\n")446    click.confirm("Prompt to stderr", err=True)447    out, err = capfd.readouterr()448    assert out == " "449    assert err == "Prompt to stderr [y/N]:"450451    monkeypatch.setattr(click.termui, "isatty", lambda x: True)452    monkeypatch.setattr(click.termui, "getchar", lambda: " ")453454    click.pause("Pause to stdout")455    out, err = capfd.readouterr()456    assert out == "Pause to stdout\n"457    assert err == ""458459    click.pause("Pause to stderr", err=True)460    out, err = capfd.readouterr()461    assert out == ""462    assert err == "Pause to stderr\n"463464465def test_echo_with_capsys(capsys):466    click.echo("Capture me.")467    out, err = capsys.readouterr()468    assert out == "Capture me.\n"469470471def test_open_file(runner):472    @click.command()473    @click.argument("filename")474    def cli(filename):475        with click.open_file(filename) as f:476            click.echo(f.read())477478        click.echo("meep")479480    with runner.isolated_filesystem():481        with open("hello.txt", "w") as f:482            f.write("Cool stuff")483484        result = runner.invoke(cli, ["hello.txt"])485        assert result.exception is None486        assert result.output == "Cool stuff\nmeep\n"487488        result = runner.invoke(cli, ["-"], input="foobar")489        assert result.exception is None490        assert result.output == "foobar\nmeep\n"491492493def test_open_file_pathlib_dash(runner):494    @click.command()495    @click.argument(496        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)497    )498    def cli(filename):499        click.echo(str(type(filename)))500501        with click.open_file(filename) as f:502            click.echo(f.read())503504        result = runner.invoke(cli, ["-"], input="value")505        assert result.exception is None506        assert result.output == "pathlib.Path\nvalue\n"507508509def test_open_file_ignore_errors_stdin(runner):510    @click.command()511    @click.argument("filename")512    def cli(filename):513        with click.open_file(filename, errors="ignore") as f:514            click.echo(f.read())515516    result = runner.invoke(cli, ["-"], input=os.urandom(16))517    assert result.exception is None518519520def test_open_file_respects_ignore(runner):521    with runner.isolated_filesystem():522        with open("test.txt", "w") as f:523            f.write("Hello world!")524525        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:526            assert f.errors == "ignore"527528529def test_open_file_ignore_invalid_utf8(runner):530    with runner.isolated_filesystem():531        with open("test.txt", "wb") as f:532            f.write(b"\xe2\x28\xa1")533534        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:535            f.read()536537538def test_open_file_ignore_no_encoding(runner):539    with runner.isolated_filesystem():540        with open("test.bin", "wb") as f:541            f.write(os.urandom(16))542543        with click.open_file("test.bin", errors="ignore") as f:544            f.read()545546547@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")548@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])549def test_open_file_atomic_permissions_existing_file(runner, permissions):550    with runner.isolated_filesystem():551        with open("existing.txt", "w") as f:552            f.write("content")553        os.chmod("existing.txt", permissions)554555        @click.command()556        @click.argument("filename")557        def cli(filename):558            click.open_file(filename, "w", atomic=True).close()559560        result = runner.invoke(cli, ["existing.txt"])561        assert result.exception is None562        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions563564565@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")566def test_open_file_atomic_permissions_new_file(runner):567    with runner.isolated_filesystem():568569        @click.command()570        @click.argument("filename")571        def cli(filename):572            click.open_file(filename, "w", atomic=True).close()573574        # Create a test file to get the expected permissions for new files575        # according to the current umask.576        with open("test.txt", "w"):577            pass578        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)579580        result = runner.invoke(cli, ["new.txt"])581        assert result.exception is None582        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions583584585def test_iter_keepopenfile(tmpdir):586    expected = list(map(str, range(10)))587    p = tmpdir.mkdir("testdir").join("testfile")588    p.write("\n".join(expected))589    with p.open() as f:590        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):591            assert e_line == a_line.strip()592593594def test_iter_lazyfile(tmpdir):595    expected = list(map(str, range(10)))596    p = tmpdir.mkdir("testdir").join("testfile")597    p.write("\n".join(expected))598    with p.open() as f:599        with click.utils.LazyFile(f.name) as lf:600            for e_line, a_line in zip(expected, lf, strict=False):601                assert e_line == a_line.strip()602603604class MockMain:605    __slots__ = "__package__"606607    def __init__(self, package_name):608        self.__package__ = package_name609610611@pytest.mark.parametrize(612    ("path", "main", "expected"),613    [614        ("example.py", None, "example.py"),615        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),616        ("example", None, "example"),617        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),618        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),619        (str(pathlib.Path("./example")), "", "example"),620    ],621)622def test_detect_program_name(path, main, expected):623    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected624625626def test_expand_args(monkeypatch):627    user = os.path.expanduser("~")628    assert user in click.utils._expand_args(["~"])629    monkeypatch.setenv("CLICK_TEST", "hello")630    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])631    assert "pyproject.toml" in click.utils._expand_args(["*.toml"])632    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])633    assert "*.not-found" in click.utils._expand_args(["*.not-found"])634    # a bad glob pattern, such as a pytest identifier, should return itself635    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"636637638@pytest.mark.parametrize(639    ("value", "max_length", "expect"),640    [641        pytest.param("", 10, "", id="empty"),642        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),643        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),644        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),645        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),646        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),647        pytest.param(648            "token in ~/.netrc ciao ciao",649            20,650            "token in ~/.netrc...",651            id="ignore dot in word",652        ),653    ],654)655@pytest.mark.parametrize(656    "alter",657    [658        pytest.param(None, id=""),659        pytest.param(660            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"661        ),662    ],663)664def test_make_default_short_help(value, max_length, alter, expect):665    assert len(expect) <= max_length666667    if alter:668        value = alter(value)669670    out = click.utils.make_default_short_help(value, max_length)671    assert out == expect