Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

653 lines · 20.7 KiB · Python

Last changed by

Improve echo_via_pager behaviour in face of errors (#2775)Steffen Neubauerbefore adoption3b06e0b

History of this file

Take it

1import os2import pathlib3import stat4import sys5from collections import namedtuple6from io import StringIO7from tempfile import tempdir89import pytest1011import click._termui_impl12import click.utils13from click._compat import WIN141516def test_echo(runner):17    with runner.isolation() as outstreams:18        click.echo("\N{SNOWMAN}")19        click.echo(b"\x44\x44")20        click.echo(42, nl=False)21        click.echo(b"a", nl=False)22        click.echo("\x1b[31mx\x1b[39m", nl=False)23        bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")24        assert bytes == b"\xe2\x98\x83\nDD\n42ax"2526    # if wrapped, we expect bytes to survive.27    @click.command()28    def cli():29        click.echo(b"\xf6")3031    result = runner.invoke(cli, [])32    assert result.stdout_bytes == b"\xf6\n"3334    # Ensure we do not strip for bytes.35    with runner.isolation() as outstreams:36        click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)37        assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"383940def test_echo_custom_file():41    f = StringIO()42    click.echo("hello", file=f)43    assert f.getvalue() == "hello\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)535455@pytest.mark.parametrize(56    ("styles", "ref"),57    [58        ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),59        ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),60        ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),61        ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),62        ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),63        ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),64        ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),65        ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),66        ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),67        ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),68        ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),69        ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),70        ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),71        ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),72        ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),73        ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),74        ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),75        ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),76        ({"bold": True}, "\x1b[1mx y\x1b[0m"),77        ({"dim": True}, "\x1b[2mx y\x1b[0m"),78        ({"underline": True}, "\x1b[4mx y\x1b[0m"),79        ({"overline": True}, "\x1b[53mx y\x1b[0m"),80        ({"italic": True}, "\x1b[3mx y\x1b[0m"),81        ({"blink": True}, "\x1b[5mx y\x1b[0m"),82        ({"reverse": True}, "\x1b[7mx y\x1b[0m"),83        ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),84        ({"bold": False}, "\x1b[22mx y\x1b[0m"),85        ({"dim": False}, "\x1b[22mx y\x1b[0m"),86        ({"underline": False}, "\x1b[24mx y\x1b[0m"),87        ({"overline": False}, "\x1b[55mx y\x1b[0m"),88        ({"italic": False}, "\x1b[23mx y\x1b[0m"),89        ({"blink": False}, "\x1b[25mx y\x1b[0m"),90        ({"reverse": False}, "\x1b[27mx y\x1b[0m"),91        ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),92        ({"fg": "black", "reset": False}, "\x1b[30mx y"),93    ],94)95def test_styling(styles, ref):96    assert click.style("x y", **styles) == ref97    assert click.unstyle(ref) == "x y"9899100@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])101def test_unstyle_other_ansi(text, expect):102    assert click.unstyle(text) == expect103104105def test_filename_formatting():106    assert click.format_filename(b"foo.txt") == "foo.txt"107    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"108    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"109    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"110    assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"111112113def test_prompts(runner):114    @click.command()115    def test():116        if click.confirm("Foo"):117            click.echo("yes!")118        else:119            click.echo("no :(")120121    result = runner.invoke(test, input="y\n")122    assert not result.exception123    assert result.output == "Foo [y/N]: y\nyes!\n"124125    result = runner.invoke(test, input="\n")126    assert not result.exception127    assert result.output == "Foo [y/N]: \nno :(\n"128129    result = runner.invoke(test, input="n\n")130    assert not result.exception131    assert result.output == "Foo [y/N]: n\nno :(\n"132133    @click.command()134    def test_no():135        if click.confirm("Foo", default=True):136            click.echo("yes!")137        else:138            click.echo("no :(")139140    result = runner.invoke(test_no, input="y\n")141    assert not result.exception142    assert result.output == "Foo [Y/n]: y\nyes!\n"143144    result = runner.invoke(test_no, input="\n")145    assert not result.exception146    assert result.output == "Foo [Y/n]: \nyes!\n"147148    result = runner.invoke(test_no, input="n\n")149    assert not result.exception150    assert result.output == "Foo [Y/n]: n\nno :(\n"151152153def test_confirm_repeat(runner):154    cli = click.Command(155        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]156    )157    result = runner.invoke(cli, input="\ny\n")158    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"159160161@pytest.mark.skipif(WIN, reason="Different behavior on windows.")162def test_prompts_abort(monkeypatch, capsys):163    def f(_):164        raise KeyboardInterrupt()165166    monkeypatch.setattr("click.termui.hidden_prompt_func", f)167168    try:169        click.prompt("Password", hide_input=True)170    except click.Abort:171        click.echo("interrupted")172173    out, err = capsys.readouterr()174    assert out == "Password:\ninterrupted\n"175176177def _test_gen_func():178    yield "a"179    yield "b"180    yield "c"181    yield "abc"182183184def _test_gen_func_fails():185    yield "test"186    raise RuntimeError("This is a test.")187188189def _test_gen_func_echo(file=None):190    yield "test"191    click.echo("hello", file=file)192    yield "test"193194195def _test_simulate_keyboard_interrupt(file=None):196    yield "output_before_keyboard_interrupt"197    raise KeyboardInterrupt()198199200EchoViaPagerTest = namedtuple(201    "EchoViaPagerTest",202    (203        "description",204        "test_input",205        "expected_pager",206        "expected_stdout",207        "expected_stderr",208        "expected_error",209    ),210)211212213@pytest.mark.skipif(WIN, reason="Different behavior on windows.")214@pytest.mark.parametrize(215    "test",216    [217        # We need to pass a parameter function instead of a plain param218        # as pytest.mark.parametrize will reuse the parameters causing the219        # generators to be used up so they will not yield anymore220        EchoViaPagerTest(221            description="Plain string argument",222            test_input=lambda: "just text",223            expected_pager="just text\n",224            expected_stdout="",225            expected_stderr="",226            expected_error=None,227        ),228        EchoViaPagerTest(229            description="Iterable argument",230            test_input=lambda: ["itera", "ble"],231            expected_pager="iterable\n",232            expected_stdout="",233            expected_stderr="",234            expected_error=None,235        ),236        EchoViaPagerTest(237            description="Generator function argument",238            test_input=lambda: _test_gen_func,239            expected_pager="abcabc\n",240            expected_stdout="",241            expected_stderr="",242            expected_error=None,243        ),244        EchoViaPagerTest(245            description="String generator 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="Number generator expression argument",254            test_input=lambda: (c for c in range(6)),255            expected_pager="012345\n",256            expected_stdout="",257            expected_stderr="",258            expected_error=None,259        ),260        EchoViaPagerTest(261            description="Exception in generator function argument",262            test_input=lambda: _test_gen_func_fails,263            # Because generator throws early on, the pager did not have264            # a chance yet to write the file.265            expected_pager=None,266            expected_stdout="",267            expected_stderr="",268            expected_error=RuntimeError,269        ),270        EchoViaPagerTest(271            description="Exception in generator argument",272            test_input=lambda: _test_gen_func_fails,273            # Because generator throws early on, the pager did not have a274            # chance yet to write the file.275            expected_pager=None,276            expected_stdout="",277            expected_stderr="",278            expected_error=RuntimeError,279        ),280        EchoViaPagerTest(281            description="Keyboard interrupt should not terminate the pager",282            test_input=lambda: _test_simulate_keyboard_interrupt(),283            # Due to the keyboard interrupt during pager execution, click program284            # should abort, but the pager should stay open.285            # This allows users to cancel the program and search in the pager286            # output, before they decide to terminate the pager.287            expected_pager="output_before_keyboard_interrupt",288            expected_stdout="",289            expected_stderr="",290            expected_error=KeyboardInterrupt,291        ),292        EchoViaPagerTest(293            description="Writing to stdout during generator execution",294            test_input=lambda: _test_gen_func_echo(),295            expected_pager="testtest\n",296            expected_stdout="hello\n",297            expected_stderr="",298            expected_error=None,299        ),300        EchoViaPagerTest(301            description="Writing to stderr during generator execution",302            test_input=lambda: _test_gen_func_echo(file=sys.stderr),303            expected_pager="testtest\n",304            expected_stdout="",305            expected_stderr="hello\n",306            expected_error=None,307        ),308    ],309)310def test_echo_via_pager(monkeypatch, capfd, test):311    pager_out_tmp = f"{tempdir}/pager_out.txt"312313    if os.path.exists(pager_out_tmp):314        os.remove(pager_out_tmp)315316    monkeypatch.setitem(os.environ, "PAGER", f"cat > {pager_out_tmp}")317    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)318319    test_input = test.test_input()320    expected_pager = test.expected_pager321    expected_stdout = test.expected_stdout322    expected_stderr = test.expected_stderr323    expected_error = test.expected_error324325    if expected_error:326        with pytest.raises(expected_error):327            click.echo_via_pager(test_input)328    else:329        click.echo_via_pager(test_input)330331    out, err = capfd.readouterr()332333    if os.path.exists(pager_out_tmp):334        with open(pager_out_tmp) as f:335            pager = f.read()336    else:337        # The pager process was not started or has been338        # terminated before it could finish writing339        pager = None340341    assert (342        pager == expected_pager343    ), f"Unexpected pager output in test case '{test.description}'"344    assert (345        out == expected_stdout346    ), f"Unexpected stdout in test case '{test.description}'"347    assert (348        err == expected_stderr349    ), f"Unexpected stderr in test case '{test.description}'"350351352def test_echo_color_flag(monkeypatch, capfd):353    isatty = True354    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)355356    text = "foo"357    styled_text = click.style(text, fg="red")358    assert styled_text == "\x1b[31mfoo\x1b[0m"359360    click.echo(styled_text, color=False)361    out, err = capfd.readouterr()362    assert out == f"{text}\n"363364    click.echo(styled_text, color=True)365    out, err = capfd.readouterr()366    assert out == f"{styled_text}\n"367368    isatty = True369    click.echo(styled_text)370    out, err = capfd.readouterr()371    assert out == f"{styled_text}\n"372373    isatty = False374    # Faking isatty() is not enough on Windows;375    # the implementation caches the colorama wrapped stream376    # so we have to use a new stream for each test377    stream = StringIO()378    click.echo(styled_text, file=stream)379    assert stream.getvalue() == f"{text}\n"380381    stream = StringIO()382    click.echo(styled_text, file=stream, color=True)383    assert stream.getvalue() == f"{styled_text}\n"384385386def test_prompt_cast_default(capfd, monkeypatch):387    monkeypatch.setattr(sys, "stdin", StringIO("\n"))388    value = click.prompt("value", default="100", type=int)389    capfd.readouterr()390    assert isinstance(value, int)391392393@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")394def test_echo_writing_to_standard_error(capfd, monkeypatch):395    def emulate_input(text):396        """Emulate keyboard input."""397        monkeypatch.setattr(sys, "stdin", StringIO(text))398399    click.echo("Echo to standard output")400    out, err = capfd.readouterr()401    assert out == "Echo to standard output\n"402    assert err == ""403404    click.echo("Echo to standard error", err=True)405    out, err = capfd.readouterr()406    assert out == ""407    assert err == "Echo to standard error\n"408409    emulate_input("asdlkj\n")410    click.prompt("Prompt to stdin")411    out, err = capfd.readouterr()412    assert out == "Prompt to stdin: "413    assert err == ""414415    emulate_input("asdlkj\n")416    click.prompt("Prompt to stderr", err=True)417    out, err = capfd.readouterr()418    assert out == " "419    assert err == "Prompt to stderr:"420421    emulate_input("y\n")422    click.confirm("Prompt to stdin")423    out, err = capfd.readouterr()424    assert out == "Prompt to stdin [y/N]: "425    assert err == ""426427    emulate_input("y\n")428    click.confirm("Prompt to stderr", err=True)429    out, err = capfd.readouterr()430    assert out == " "431    assert err == "Prompt to stderr [y/N]:"432433    monkeypatch.setattr(click.termui, "isatty", lambda x: True)434    monkeypatch.setattr(click.termui, "getchar", lambda: " ")435436    click.pause("Pause to stdout")437    out, err = capfd.readouterr()438    assert out == "Pause to stdout\n"439    assert err == ""440441    click.pause("Pause to stderr", err=True)442    out, err = capfd.readouterr()443    assert out == ""444    assert err == "Pause to stderr\n"445446447def test_echo_with_capsys(capsys):448    click.echo("Capture me.")449    out, err = capsys.readouterr()450    assert out == "Capture me.\n"451452453def test_open_file(runner):454    @click.command()455    @click.argument("filename")456    def cli(filename):457        with click.open_file(filename) as f:458            click.echo(f.read())459460        click.echo("meep")461462    with runner.isolated_filesystem():463        with open("hello.txt", "w") as f:464            f.write("Cool stuff")465466        result = runner.invoke(cli, ["hello.txt"])467        assert result.exception is None468        assert result.output == "Cool stuff\nmeep\n"469470        result = runner.invoke(cli, ["-"], input="foobar")471        assert result.exception is None472        assert result.output == "foobar\nmeep\n"473474475def test_open_file_pathlib_dash(runner):476    @click.command()477    @click.argument(478        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)479    )480    def cli(filename):481        click.echo(str(type(filename)))482483        with click.open_file(filename) as f:484            click.echo(f.read())485486        result = runner.invoke(cli, ["-"], input="value")487        assert result.exception is None488        assert result.output == "pathlib.Path\nvalue\n"489490491def test_open_file_ignore_errors_stdin(runner):492    @click.command()493    @click.argument("filename")494    def cli(filename):495        with click.open_file(filename, errors="ignore") as f:496            click.echo(f.read())497498    result = runner.invoke(cli, ["-"], input=os.urandom(16))499    assert result.exception is None500501502def test_open_file_respects_ignore(runner):503    with runner.isolated_filesystem():504        with open("test.txt", "w") as f:505            f.write("Hello world!")506507        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:508            assert f.errors == "ignore"509510511def test_open_file_ignore_invalid_utf8(runner):512    with runner.isolated_filesystem():513        with open("test.txt", "wb") as f:514            f.write(b"\xe2\x28\xa1")515516        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:517            f.read()518519520def test_open_file_ignore_no_encoding(runner):521    with runner.isolated_filesystem():522        with open("test.bin", "wb") as f:523            f.write(os.urandom(16))524525        with click.open_file("test.bin", errors="ignore") as f:526            f.read()527528529@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")530@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])531def test_open_file_atomic_permissions_existing_file(runner, permissions):532    with runner.isolated_filesystem():533        with open("existing.txt", "w") as f:534            f.write("content")535        os.chmod("existing.txt", permissions)536537        @click.command()538        @click.argument("filename")539        def cli(filename):540            click.open_file(filename, "w", atomic=True).close()541542        result = runner.invoke(cli, ["existing.txt"])543        assert result.exception is None544        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions545546547@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")548def test_open_file_atomic_permissions_new_file(runner):549    with runner.isolated_filesystem():550551        @click.command()552        @click.argument("filename")553        def cli(filename):554            click.open_file(filename, "w", atomic=True).close()555556        # Create a test file to get the expected permissions for new files557        # according to the current umask.558        with open("test.txt", "w"):559            pass560        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)561562        result = runner.invoke(cli, ["new.txt"])563        assert result.exception is None564        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions565566567def test_iter_keepopenfile(tmpdir):568    expected = list(map(str, range(10)))569    p = tmpdir.mkdir("testdir").join("testfile")570    p.write("\n".join(expected))571    with p.open() as f:572        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):573            assert e_line == a_line.strip()574575576def test_iter_lazyfile(tmpdir):577    expected = list(map(str, range(10)))578    p = tmpdir.mkdir("testdir").join("testfile")579    p.write("\n".join(expected))580    with p.open() as f:581        with click.utils.LazyFile(f.name) as lf:582            for e_line, a_line in zip(expected, lf):583                assert e_line == a_line.strip()584585586class MockMain:587    __slots__ = "__package__"588589    def __init__(self, package_name):590        self.__package__ = package_name591592593@pytest.mark.parametrize(594    ("path", "main", "expected"),595    [596        ("example.py", None, "example.py"),597        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),598        ("example", None, "example"),599        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),600        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),601        (str(pathlib.Path("./example")), "", "example"),602    ],603)604def test_detect_program_name(path, main, expected):605    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected606607608def test_expand_args(monkeypatch):609    user = os.path.expanduser("~")610    assert user in click.utils._expand_args(["~"])611    monkeypatch.setenv("CLICK_TEST", "hello")612    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])613    assert "pyproject.toml" in click.utils._expand_args(["*.toml"])614    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])615    assert "*.not-found" in click.utils._expand_args(["*.not-found"])616    # a bad glob pattern, such as a pytest identifier, should return itself617    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"618619620@pytest.mark.parametrize(621    ("value", "max_length", "expect"),622    [623        pytest.param("", 10, "", id="empty"),624        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),625        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),626        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),627        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),628        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),629        pytest.param(630            "token in ~/.netrc ciao ciao",631            20,632            "token in ~/.netrc...",633            id="ignore dot in word",634        ),635    ],636)637@pytest.mark.parametrize(638    "alter",639    [640        pytest.param(None, id=""),641        pytest.param(642            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"643        ),644    ],645)646def test_make_default_short_help(value, max_length, alter, expect):647    assert len(expect) <= max_length648649    if alter:650        value = alter(value)651652    out = click.utils.make_default_short_help(value, max_length)653    assert out == expect