Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

746 lines · 23.2 KiB · Python

Last changed by

Fix rendering when `prompt_suffix` is empty (#3021)Rowlando13before adoption8533c96

History of this file

Take it

1import os2import pathlib3import stat4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import StringIO12from pathlib import Path13from tempfile import tempdir14from unittest.mock import patch1516import pytest1718import click._termui_impl19import click.utils20from click._compat import WIN21from click._utils import UNSET222324def test_unset_sentinel():25    value = UNSET2627    assert value28    assert value is UNSET29    assert value == UNSET30    assert repr(value) == "Sentinel.UNSET"31    assert str(value) == "Sentinel.UNSET"32    assert bool(value) is True3334    # Try all native Python values that can be falsy or truthy.35    # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing36    real_values = (37        None,38        True,39        False,40        0,41        1,42        0.0,43        1.0,44        0j,45        1j,46        Decimal(0),47        Decimal(1),48        Fraction(0, 1),49        Fraction(1, 1),50        "",51        "a",52        "UNSET",53        "Sentinel.UNSET",54        [1],55        (1),56        {1: "a"},57        set(),58        set([1]),59        frozenset(),60        frozenset([1]),61        range(0),62        range(1),63    )6465    for real_value in real_values:66        assert value != real_value67        assert value is not real_value6869    assert value not in real_values707172def test_echo(runner):73    with runner.isolation() as outstreams:74        click.echo("\N{SNOWMAN}")75        click.echo(b"\x44\x44")76        click.echo(42, nl=False)77        click.echo(b"a", nl=False)78        click.echo("\x1b[31mx\x1b[39m", nl=False)79        bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")80        assert bytes == b"\xe2\x98\x83\nDD\n42ax"8182    # if wrapped, we expect bytes to survive.83    @click.command()84    def cli():85        click.echo(b"\xf6")8687    result = runner.invoke(cli, [])88    assert result.stdout_bytes == b"\xf6\n"8990    # Ensure we do not strip for bytes.91    with runner.isolation() as outstreams:92        click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)93        assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"949596def test_echo_custom_file():97    f = StringIO()98    click.echo("hello", file=f)99    assert f.getvalue() == "hello\n"100101102def test_echo_no_streams(monkeypatch, runner):103    """echo should not fail when stdout and stderr are None with pythonw on Windows."""104    with runner.isolation():105        sys.stdout = None106        sys.stderr = None107        click.echo("test")108        click.echo("test", err=True)109110111@pytest.mark.parametrize(112    ("styles", "ref"),113    [114        ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),115        ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),116        ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),117        ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),118        ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),119        ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),120        ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),121        ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),122        ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),123        ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),124        ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),125        ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),126        ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),127        ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),128        ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),129        ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),130        ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),131        ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),132        ({"bold": True}, "\x1b[1mx y\x1b[0m"),133        ({"dim": True}, "\x1b[2mx y\x1b[0m"),134        ({"underline": True}, "\x1b[4mx y\x1b[0m"),135        ({"overline": True}, "\x1b[53mx y\x1b[0m"),136        ({"italic": True}, "\x1b[3mx y\x1b[0m"),137        ({"blink": True}, "\x1b[5mx y\x1b[0m"),138        ({"reverse": True}, "\x1b[7mx y\x1b[0m"),139        ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),140        ({"bold": False}, "\x1b[22mx y\x1b[0m"),141        ({"dim": False}, "\x1b[22mx y\x1b[0m"),142        ({"underline": False}, "\x1b[24mx y\x1b[0m"),143        ({"overline": False}, "\x1b[55mx y\x1b[0m"),144        ({"italic": False}, "\x1b[23mx y\x1b[0m"),145        ({"blink": False}, "\x1b[25mx y\x1b[0m"),146        ({"reverse": False}, "\x1b[27mx y\x1b[0m"),147        ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),148        ({"fg": "black", "reset": False}, "\x1b[30mx y"),149    ],150)151def test_styling(styles, ref):152    assert click.style("x y", **styles) == ref153    assert click.unstyle(ref) == "x y"154155156@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])157def test_unstyle_other_ansi(text, expect):158    assert click.unstyle(text) == expect159160161def test_filename_formatting():162    assert click.format_filename(b"foo.txt") == "foo.txt"163    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"164    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"165    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"166    assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"167168169def test_prompts(runner):170    @click.command()171    def test():172        if click.confirm("Foo"):173            click.echo("yes!")174        else:175            click.echo("no :(")176177    result = runner.invoke(test, input="y\n")178    assert not result.exception179    assert result.output == "Foo [y/N]: y\nyes!\n"180181    result = runner.invoke(test, input="\n")182    assert not result.exception183    assert result.output == "Foo [y/N]: \nno :(\n"184185    result = runner.invoke(test, input="n\n")186    assert not result.exception187    assert result.output == "Foo [y/N]: n\nno :(\n"188189    @click.command()190    def test_no():191        if click.confirm("Foo", default=True):192            click.echo("yes!")193        else:194            click.echo("no :(")195196    result = runner.invoke(test_no, input="y\n")197    assert not result.exception198    assert result.output == "Foo [Y/n]: y\nyes!\n"199200    result = runner.invoke(test_no, input="\n")201    assert not result.exception202    assert result.output == "Foo [Y/n]: \nyes!\n"203204    result = runner.invoke(test_no, input="n\n")205    assert not result.exception206    assert result.output == "Foo [Y/n]: n\nno :(\n"207208209def test_confirm_repeat(runner):210    cli = click.Command(211        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]212    )213    result = runner.invoke(cli, input="\ny\n")214    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"215216217@pytest.mark.skipif(WIN, reason="Different behavior on windows.")218def test_prompts_abort(monkeypatch, capsys):219    def f(_):220        raise KeyboardInterrupt()221222    monkeypatch.setattr("click.termui.hidden_prompt_func", f)223224    try:225        click.prompt("Password", hide_input=True)226    except click.Abort:227        click.echo("interrupted")228229    out, err = capsys.readouterr()230    assert out == "Password:\ninterrupted\n"231232233def test_prompts_eof(runner):234    """If too few lines of input are given, prompt should exit, not hang."""235236    @click.command237    def echo():238        for _ in range(3):239            click.echo(click.prompt("", type=int))240241    # only provide two lines of input for three prompts242    result = runner.invoke(echo, input="1\n2\n")243    assert result.exit_code == 1244245246def _test_gen_func():247    yield "a"248    yield "b"249    yield "c"250    yield "abc"251252253def _test_gen_func_fails():254    yield "test"255    raise RuntimeError("This is a test.")256257258def _test_gen_func_echo(file=None):259    yield "test"260    click.echo("hello", file=file)261    yield "test"262263264def _test_simulate_keyboard_interrupt(file=None):265    yield "output_before_keyboard_interrupt"266    raise KeyboardInterrupt()267268269EchoViaPagerTest = namedtuple(270    "EchoViaPagerTest",271    (272        "description",273        "test_input",274        "expected_pager",275        "expected_stdout",276        "expected_stderr",277        "expected_error",278    ),279)280281282@pytest.mark.skipif(WIN, reason="Different behavior on windows.")283@pytest.mark.parametrize(284    "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]285)286@pytest.mark.parametrize(287    "test",288    [289        # We need to pass a parameter function instead of a plain param290        # as pytest.mark.parametrize will reuse the parameters causing the291        # generators to be used up so they will not yield anymore292        EchoViaPagerTest(293            description="Plain string argument",294            test_input=lambda: "just text",295            expected_pager="just text\n",296            expected_stdout="",297            expected_stderr="",298            expected_error=None,299        ),300        EchoViaPagerTest(301            description="Iterable argument",302            test_input=lambda: ["itera", "ble"],303            expected_pager="iterable\n",304            expected_stdout="",305            expected_stderr="",306            expected_error=None,307        ),308        EchoViaPagerTest(309            description="Generator function argument",310            test_input=lambda: _test_gen_func,311            expected_pager="abcabc\n",312            expected_stdout="",313            expected_stderr="",314            expected_error=None,315        ),316        EchoViaPagerTest(317            description="String generator argument",318            test_input=lambda: _test_gen_func(),319            expected_pager="abcabc\n",320            expected_stdout="",321            expected_stderr="",322            expected_error=None,323        ),324        EchoViaPagerTest(325            description="Number generator expression argument",326            test_input=lambda: (c for c in range(6)),327            expected_pager="012345\n",328            expected_stdout="",329            expected_stderr="",330            expected_error=None,331        ),332        EchoViaPagerTest(333            description="Exception in generator function argument",334            test_input=lambda: _test_gen_func_fails,335            # Because generator throws early on, the pager did not have336            # a chance yet to write the file.337            expected_pager="",338            expected_stdout="",339            expected_stderr="",340            expected_error=RuntimeError,341        ),342        EchoViaPagerTest(343            description="Exception in generator argument",344            test_input=lambda: _test_gen_func_fails,345            # Because generator throws early on, the pager did not have a346            # chance yet to write the file.347            expected_pager="",348            expected_stdout="",349            expected_stderr="",350            expected_error=RuntimeError,351        ),352        EchoViaPagerTest(353            description="Keyboard interrupt should not terminate the pager",354            test_input=lambda: _test_simulate_keyboard_interrupt(),355            # Due to the keyboard interrupt during pager execution, click program356            # should abort, but the pager should stay open.357            # This allows users to cancel the program and search in the pager358            # output, before they decide to terminate the pager.359            expected_pager="output_before_keyboard_interrupt",360            expected_stdout="",361            expected_stderr="",362            expected_error=KeyboardInterrupt,363        ),364        EchoViaPagerTest(365            description="Writing to stdout during generator execution",366            test_input=lambda: _test_gen_func_echo(),367            expected_pager="testtest\n",368            expected_stdout="hello\n",369            expected_stderr="",370            expected_error=None,371        ),372        EchoViaPagerTest(373            description="Writing to stderr during generator execution",374            test_input=lambda: _test_gen_func_echo(file=sys.stderr),375            expected_pager="testtest\n",376            expected_stdout="",377            expected_stderr="hello\n",378            expected_error=None,379        ),380    ],381)382def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test):383    monkeypatch.setitem(os.environ, "PAGER", pager_cmd)384    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)385386    test_input = test.test_input()387    expected_pager = test.expected_pager388    expected_stdout = test.expected_stdout389    expected_stderr = test.expected_stderr390    expected_error = test.expected_error391392    check_raise = pytest.raises(expected_error) if expected_error else nullcontext()393394    pager_out_tmp = Path(tempdir) / "pager_out.txt"395    pager_out_tmp.unlink(missing_ok=True)396    with pager_out_tmp.open("w") as f:397        force_subprocess_stdout = patch.object(398            subprocess,399            "Popen",400            partial(subprocess.Popen, stdout=f),401        )402        with force_subprocess_stdout:403            with check_raise:404                click.echo_via_pager(test_input)405406    out, err = capfd.readouterr()407408    pager = pager_out_tmp.read_text()409410    assert pager == expected_pager, (411        f"Unexpected pager output in test case '{test.description}'"412    )413    assert out == expected_stdout, (414        f"Unexpected stdout in test case '{test.description}'"415    )416    assert err == expected_stderr, (417        f"Unexpected stderr in test case '{test.description}'"418    )419420421def test_echo_color_flag(monkeypatch, capfd):422    isatty = True423    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)424425    text = "foo"426    styled_text = click.style(text, fg="red")427    assert styled_text == "\x1b[31mfoo\x1b[0m"428429    click.echo(styled_text, color=False)430    out, err = capfd.readouterr()431    assert out == f"{text}\n"432433    click.echo(styled_text, color=True)434    out, err = capfd.readouterr()435    assert out == f"{styled_text}\n"436437    isatty = True438    click.echo(styled_text)439    out, err = capfd.readouterr()440    assert out == f"{styled_text}\n"441442    isatty = False443    # Faking isatty() is not enough on Windows;444    # the implementation caches the colorama wrapped stream445    # so we have to use a new stream for each test446    stream = StringIO()447    click.echo(styled_text, file=stream)448    assert stream.getvalue() == f"{text}\n"449450    stream = StringIO()451    click.echo(styled_text, file=stream, color=True)452    assert stream.getvalue() == f"{styled_text}\n"453454455def test_prompt_cast_default(capfd, monkeypatch):456    monkeypatch.setattr(sys, "stdin", StringIO("\n"))457    value = click.prompt("value", default="100", type=int)458    capfd.readouterr()459    assert isinstance(value, int)460461462@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")463def test_echo_writing_to_standard_error(capfd, monkeypatch):464    def emulate_input(text):465        """Emulate keyboard input."""466        monkeypatch.setattr(sys, "stdin", StringIO(text))467468    click.echo("Echo to standard output")469    out, err = capfd.readouterr()470    assert out == "Echo to standard output\n"471    assert err == ""472473    click.echo("Echo to standard error", err=True)474    out, err = capfd.readouterr()475    assert out == ""476    assert err == "Echo to standard error\n"477478    emulate_input("asdlkj\n")479    click.prompt("Prompt to stdin")480    out, err = capfd.readouterr()481    assert out == "Prompt to stdin: "482    assert err == ""483484    emulate_input("asdlkj\n")485    click.prompt("Prompt to stdin with no suffix", prompt_suffix="")486    out, err = capfd.readouterr()487    assert out == "Prompt to stdin with no suffix"488    assert err == ""489490    emulate_input("asdlkj\n")491    click.prompt("Prompt to stderr", err=True)492    out, err = capfd.readouterr()493    assert out == " "494    assert err == "Prompt to stderr:"495496    emulate_input("asdlkj\n")497    click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)498    out, err = capfd.readouterr()499    assert out == "x"500    assert err == "Prompt to stderr with no suffi"501502    emulate_input("y\n")503    click.confirm("Prompt to stdin")504    out, err = capfd.readouterr()505    assert out == "Prompt to stdin [y/N]: "506    assert err == ""507508    emulate_input("y\n")509    click.confirm("Prompt to stdin with no suffix", prompt_suffix="")510    out, err = capfd.readouterr()511    assert out == "Prompt to stdin with no suffix [y/N]"512    assert err == ""513514    emulate_input("y\n")515    click.confirm("Prompt to stderr", err=True)516    out, err = capfd.readouterr()517    assert out == " "518    assert err == "Prompt to stderr [y/N]:"519520    emulate_input("y\n")521    click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)522    out, err = capfd.readouterr()523    assert out == "]"524    assert err == "Prompt to stderr with no suffix [y/N"525526    monkeypatch.setattr(click.termui, "isatty", lambda x: True)527    monkeypatch.setattr(click.termui, "getchar", lambda: " ")528529    click.pause("Pause to stdout")530    out, err = capfd.readouterr()531    assert out == "Pause to stdout\n"532    assert err == ""533534    click.pause("Pause to stderr", err=True)535    out, err = capfd.readouterr()536    assert out == ""537    assert err == "Pause to stderr\n"538539540def test_echo_with_capsys(capsys):541    click.echo("Capture me.")542    out, err = capsys.readouterr()543    assert out == "Capture me.\n"544545546def test_open_file(runner):547    @click.command()548    @click.argument("filename")549    def cli(filename):550        with click.open_file(filename) as f:551            click.echo(f.read())552553        click.echo("meep")554555    with runner.isolated_filesystem():556        with open("hello.txt", "w") as f:557            f.write("Cool stuff")558559        result = runner.invoke(cli, ["hello.txt"])560        assert result.exception is None561        assert result.output == "Cool stuff\nmeep\n"562563        result = runner.invoke(cli, ["-"], input="foobar")564        assert result.exception is None565        assert result.output == "foobar\nmeep\n"566567568def test_open_file_pathlib_dash(runner):569    @click.command()570    @click.argument(571        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)572    )573    def cli(filename):574        click.echo(str(type(filename)))575576        with click.open_file(filename) as f:577            click.echo(f.read())578579        result = runner.invoke(cli, ["-"], input="value")580        assert result.exception is None581        assert result.output == "pathlib.Path\nvalue\n"582583584def test_open_file_ignore_errors_stdin(runner):585    @click.command()586    @click.argument("filename")587    def cli(filename):588        with click.open_file(filename, errors="ignore") as f:589            click.echo(f.read())590591    result = runner.invoke(cli, ["-"], input=os.urandom(16))592    assert result.exception is None593594595def test_open_file_respects_ignore(runner):596    with runner.isolated_filesystem():597        with open("test.txt", "w") as f:598            f.write("Hello world!")599600        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:601            assert f.errors == "ignore"602603604def test_open_file_ignore_invalid_utf8(runner):605    with runner.isolated_filesystem():606        with open("test.txt", "wb") as f:607            f.write(b"\xe2\x28\xa1")608609        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:610            f.read()611612613def test_open_file_ignore_no_encoding(runner):614    with runner.isolated_filesystem():615        with open("test.bin", "wb") as f:616            f.write(os.urandom(16))617618        with click.open_file("test.bin", errors="ignore") as f:619            f.read()620621622@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")623@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])624def test_open_file_atomic_permissions_existing_file(runner, permissions):625    with runner.isolated_filesystem():626        with open("existing.txt", "w") as f:627            f.write("content")628        os.chmod("existing.txt", permissions)629630        @click.command()631        @click.argument("filename")632        def cli(filename):633            click.open_file(filename, "w", atomic=True).close()634635        result = runner.invoke(cli, ["existing.txt"])636        assert result.exception is None637        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions638639640@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")641def test_open_file_atomic_permissions_new_file(runner):642    with runner.isolated_filesystem():643644        @click.command()645        @click.argument("filename")646        def cli(filename):647            click.open_file(filename, "w", atomic=True).close()648649        # Create a test file to get the expected permissions for new files650        # according to the current umask.651        with open("test.txt", "w"):652            pass653        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)654655        result = runner.invoke(cli, ["new.txt"])656        assert result.exception is None657        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions658659660def test_iter_keepopenfile(tmpdir):661    expected = list(map(str, range(10)))662    p = tmpdir.mkdir("testdir").join("testfile")663    p.write("\n".join(expected))664    with p.open() as f:665        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):666            assert e_line == a_line.strip()667668669def test_iter_lazyfile(tmpdir):670    expected = list(map(str, range(10)))671    p = tmpdir.mkdir("testdir").join("testfile")672    p.write("\n".join(expected))673    with p.open() as f:674        with click.utils.LazyFile(f.name) as lf:675            for e_line, a_line in zip(expected, lf, strict=False):676                assert e_line == a_line.strip()677678679class MockMain:680    __slots__ = "__package__"681682    def __init__(self, package_name):683        self.__package__ = package_name684685686@pytest.mark.parametrize(687    ("path", "main", "expected"),688    [689        ("example.py", None, "example.py"),690        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),691        ("example", None, "example"),692        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),693        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),694        (str(pathlib.Path("./example")), "", "example"),695    ],696)697def test_detect_program_name(path, main, expected):698    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected699700701def test_expand_args(monkeypatch):702    user = os.path.expanduser("~")703    assert user in click.utils._expand_args(["~"])704    monkeypatch.setenv("CLICK_TEST", "hello")705    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])706    assert "pyproject.toml" in click.utils._expand_args(["*.toml"])707    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])708    assert "*.not-found" in click.utils._expand_args(["*.not-found"])709    # a bad glob pattern, such as a pytest identifier, should return itself710    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"711712713@pytest.mark.parametrize(714    ("value", "max_length", "expect"),715    [716        pytest.param("", 10, "", id="empty"),717        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),718        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),719        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),720        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),721        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),722        pytest.param(723            "token in ~/.netrc ciao ciao",724            20,725            "token in ~/.netrc...",726            id="ignore dot in word",727        ),728    ],729)730@pytest.mark.parametrize(731    "alter",732    [733        pytest.param(None, id=""),734        pytest.param(735            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"736        ),737    ],738)739def test_make_default_short_help(value, max_length, alter, expect):740    assert len(expect) <= max_length741742    if alter:743        value = alter(value)744745    out = click.utils.make_default_short_help(value, max_length)746    assert out == expect