Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

745 lines · 23.1 KiB · Python

Last changed by

Fix pager test leaks (#3238)Rowlando13before adoption5df1001

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 unittest.mock import patch1314import pytest1516import click._termui_impl17import click.utils18from click._compat import WIN19from click._utils import UNSET202122def test_unset_sentinel():23    value = UNSET2425    assert value26    assert value is UNSET27    assert value == UNSET28    assert repr(value) == "Sentinel.UNSET"29    assert str(value) == "Sentinel.UNSET"30    assert bool(value) is True3132    # Try all native Python values that can be falsy or truthy.33    # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing34    real_values = (35        None,36        True,37        False,38        0,39        1,40        0.0,41        1.0,42        0j,43        1j,44        Decimal(0),45        Decimal(1),46        Fraction(0, 1),47        Fraction(1, 1),48        "",49        "a",50        "UNSET",51        "Sentinel.UNSET",52        [1],53        (1),54        {1: "a"},55        set(),56        set([1]),57        frozenset(),58        frozenset([1]),59        range(0),60        range(1),61    )6263    for real_value in real_values:64        assert value != real_value65        assert value is not real_value6667    assert value not in real_values686970def test_echo(runner):71    with runner.isolation() as outstreams:72        click.echo("\N{SNOWMAN}")73        click.echo(b"\x44\x44")74        click.echo(42, nl=False)75        click.echo(b"a", nl=False)76        click.echo("\x1b[31mx\x1b[39m", nl=False)77        bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")78        assert bytes == b"\xe2\x98\x83\nDD\n42ax"7980    # if wrapped, we expect bytes to survive.81    @click.command()82    def cli():83        click.echo(b"\xf6")8485    result = runner.invoke(cli, [])86    assert result.stdout_bytes == b"\xf6\n"8788    # Ensure we do not strip for bytes.89    with runner.isolation() as outstreams:90        click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)91        assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"929394def test_echo_custom_file():95    f = StringIO()96    click.echo("hello", file=f)97    assert f.getvalue() == "hello\n"9899100def test_echo_no_streams(monkeypatch, runner):101    """echo should not fail when stdout and stderr are None with pythonw on Windows."""102    with runner.isolation():103        sys.stdout = None104        sys.stderr = None105        click.echo("test")106        click.echo("test", err=True)107108109@pytest.mark.parametrize(110    ("styles", "ref"),111    [112        ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),113        ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),114        ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),115        ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),116        ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),117        ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),118        ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),119        ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),120        ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),121        ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),122        ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),123        ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),124        ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),125        ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),126        ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),127        ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),128        ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),129        ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),130        ({"bold": True}, "\x1b[1mx y\x1b[0m"),131        ({"dim": True}, "\x1b[2mx y\x1b[0m"),132        ({"underline": True}, "\x1b[4mx y\x1b[0m"),133        ({"overline": True}, "\x1b[53mx y\x1b[0m"),134        ({"italic": True}, "\x1b[3mx y\x1b[0m"),135        ({"blink": True}, "\x1b[5mx y\x1b[0m"),136        ({"reverse": True}, "\x1b[7mx y\x1b[0m"),137        ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),138        ({"bold": False}, "\x1b[22mx y\x1b[0m"),139        ({"dim": False}, "\x1b[22mx y\x1b[0m"),140        ({"underline": False}, "\x1b[24mx y\x1b[0m"),141        ({"overline": False}, "\x1b[55mx y\x1b[0m"),142        ({"italic": False}, "\x1b[23mx y\x1b[0m"),143        ({"blink": False}, "\x1b[25mx y\x1b[0m"),144        ({"reverse": False}, "\x1b[27mx y\x1b[0m"),145        ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),146        ({"fg": "black", "reset": False}, "\x1b[30mx y"),147    ],148)149def test_styling(styles, ref):150    assert click.style("x y", **styles) == ref151    assert click.unstyle(ref) == "x y"152153154@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])155def test_unstyle_other_ansi(text, expect):156    assert click.unstyle(text) == expect157158159def test_filename_formatting():160    assert click.format_filename(b"foo.txt") == "foo.txt"161    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"162    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"163    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"164    assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"165166167def test_prompts(runner):168    @click.command()169    def test():170        if click.confirm("Foo"):171            click.echo("yes!")172        else:173            click.echo("no :(")174175    result = runner.invoke(test, input="y\n")176    assert not result.exception177    assert result.output == "Foo [y/N]: y\nyes!\n"178179    result = runner.invoke(test, input="\n")180    assert not result.exception181    assert result.output == "Foo [y/N]: \nno :(\n"182183    result = runner.invoke(test, input="n\n")184    assert not result.exception185    assert result.output == "Foo [y/N]: n\nno :(\n"186187    @click.command()188    def test_no():189        if click.confirm("Foo", default=True):190            click.echo("yes!")191        else:192            click.echo("no :(")193194    result = runner.invoke(test_no, input="y\n")195    assert not result.exception196    assert result.output == "Foo [Y/n]: y\nyes!\n"197198    result = runner.invoke(test_no, input="\n")199    assert not result.exception200    assert result.output == "Foo [Y/n]: \nyes!\n"201202    result = runner.invoke(test_no, input="n\n")203    assert not result.exception204    assert result.output == "Foo [Y/n]: n\nno :(\n"205206207def test_confirm_repeat(runner):208    cli = click.Command(209        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]210    )211    result = runner.invoke(cli, input="\ny\n")212    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"213214215@pytest.mark.skipif(WIN, reason="Different behavior on windows.")216def test_prompts_abort(monkeypatch, capsys):217    def f(_):218        raise KeyboardInterrupt()219220    monkeypatch.setattr("click.termui.hidden_prompt_func", f)221222    try:223        click.prompt("Password", hide_input=True)224    except click.Abort:225        click.echo("interrupted")226227    out, err = capsys.readouterr()228    assert out == "Password:\ninterrupted\n"229230231def test_prompts_eof(runner):232    """If too few lines of input are given, prompt should exit, not hang."""233234    @click.command235    def echo():236        for _ in range(3):237            click.echo(click.prompt("", type=int))238239    # only provide two lines of input for three prompts240    result = runner.invoke(echo, input="1\n2\n")241    assert result.exit_code == 1242243244def _test_gen_func():245    yield "a"246    yield "b"247    yield "c"248    yield "abc"249250251def _test_gen_func_fails():252    yield "test"253    raise RuntimeError("This is a test.")254255256def _test_gen_func_echo(file=None):257    yield "test"258    click.echo("hello", file=file)259    yield "test"260261262def _test_simulate_keyboard_interrupt(file=None):263    yield "output_before_keyboard_interrupt"264    raise KeyboardInterrupt()265266267EchoViaPagerTest = namedtuple(268    "EchoViaPagerTest",269    (270        "description",271        "test_input",272        "expected_pager",273        "expected_stdout",274        "expected_stderr",275        "expected_error",276    ),277)278279280@pytest.mark.skipif(WIN, reason="Different behavior on windows.")281@pytest.mark.parametrize(282    "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]283)284@pytest.mark.parametrize(285    "test",286    [287        # We need to pass a parameter function instead of a plain param288        # as pytest.mark.parametrize will reuse the parameters causing the289        # generators to be used up so they will not yield anymore290        EchoViaPagerTest(291            description="Plain string argument",292            test_input=lambda: "just text",293            expected_pager="just text\n",294            expected_stdout="",295            expected_stderr="",296            expected_error=None,297        ),298        EchoViaPagerTest(299            description="Iterable argument",300            test_input=lambda: ["itera", "ble"],301            expected_pager="iterable\n",302            expected_stdout="",303            expected_stderr="",304            expected_error=None,305        ),306        EchoViaPagerTest(307            description="Generator function argument",308            test_input=lambda: _test_gen_func,309            expected_pager="abcabc\n",310            expected_stdout="",311            expected_stderr="",312            expected_error=None,313        ),314        EchoViaPagerTest(315            description="String generator argument",316            test_input=lambda: _test_gen_func(),317            expected_pager="abcabc\n",318            expected_stdout="",319            expected_stderr="",320            expected_error=None,321        ),322        EchoViaPagerTest(323            description="Number generator expression argument",324            test_input=lambda: (c for c in range(6)),325            expected_pager="012345\n",326            expected_stdout="",327            expected_stderr="",328            expected_error=None,329        ),330        EchoViaPagerTest(331            description="Exception in generator function argument",332            test_input=lambda: _test_gen_func_fails,333            # Because generator throws early on, the pager did not have334            # a chance yet to write the file.335            expected_pager="",336            expected_stdout="",337            expected_stderr="",338            expected_error=RuntimeError,339        ),340        EchoViaPagerTest(341            description="Exception in generator argument",342            test_input=lambda: _test_gen_func_fails,343            # Because generator throws early on, the pager did not have a344            # chance yet to write the file.345            expected_pager="",346            expected_stdout="",347            expected_stderr="",348            expected_error=RuntimeError,349        ),350        EchoViaPagerTest(351            description="Keyboard interrupt should not terminate the pager",352            test_input=lambda: _test_simulate_keyboard_interrupt(),353            # Due to the keyboard interrupt during pager execution, click program354            # should abort, but the pager should stay open.355            # This allows users to cancel the program and search in the pager356            # output, before they decide to terminate the pager.357            expected_pager="output_before_keyboard_interrupt",358            expected_stdout="",359            expected_stderr="",360            expected_error=KeyboardInterrupt,361        ),362        EchoViaPagerTest(363            description="Writing to stdout during generator execution",364            test_input=lambda: _test_gen_func_echo(),365            expected_pager="testtest\n",366            expected_stdout="hello\n",367            expected_stderr="",368            expected_error=None,369        ),370        EchoViaPagerTest(371            description="Writing to stderr during generator execution",372            test_input=lambda: _test_gen_func_echo(file=sys.stderr),373            expected_pager="testtest\n",374            expected_stdout="",375            expected_stderr="hello\n",376            expected_error=None,377        ),378    ],379)380def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):381    monkeypatch.setitem(os.environ, "PAGER", pager_cmd)382    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)383384    test_input = test.test_input()385    expected_pager = test.expected_pager386    expected_stdout = test.expected_stdout387    expected_stderr = test.expected_stderr388    expected_error = test.expected_error389390    check_raise = pytest.raises(expected_error) if expected_error else nullcontext()391392    pager_out_tmp = tmp_path / "pager_out.txt"393    with pager_out_tmp.open("w") as f:394        force_subprocess_stdout = patch.object(395            subprocess,396            "Popen",397            partial(subprocess.Popen, stdout=f),398        )399        with force_subprocess_stdout:400            with check_raise:401                click.echo_via_pager(test_input)402403    out, err = capfd.readouterr()404405    pager = pager_out_tmp.read_text()406407    assert pager == expected_pager, (408        f"Unexpected pager output in test case '{test.description}'"409    )410    assert out == expected_stdout, (411        f"Unexpected stdout in test case '{test.description}'"412    )413    assert err == expected_stderr, (414        f"Unexpected stderr in test case '{test.description}'"415    )416417418def test_echo_color_flag(monkeypatch, capfd):419    isatty = True420    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)421422    text = "foo"423    styled_text = click.style(text, fg="red")424    assert styled_text == "\x1b[31mfoo\x1b[0m"425426    click.echo(styled_text, color=False)427    out, err = capfd.readouterr()428    assert out == f"{text}\n"429430    click.echo(styled_text, color=True)431    out, err = capfd.readouterr()432    assert out == f"{styled_text}\n"433434    isatty = True435    click.echo(styled_text)436    out, err = capfd.readouterr()437    assert out == f"{styled_text}\n"438439    isatty = False440    # Faking isatty() is not enough on Windows;441    # the implementation caches the colorama wrapped stream442    # so we have to use a new stream for each test443    stream = StringIO()444    click.echo(styled_text, file=stream)445    assert stream.getvalue() == f"{text}\n"446447    stream = StringIO()448    click.echo(styled_text, file=stream, color=True)449    assert stream.getvalue() == f"{styled_text}\n"450451452def test_prompt_cast_default(capfd, monkeypatch):453    monkeypatch.setattr(sys, "stdin", StringIO("\n"))454    value = click.prompt("value", default="100", type=int)455    capfd.readouterr()456    assert isinstance(value, int)457458459@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")460def test_echo_writing_to_standard_error(capfd, monkeypatch):461    def emulate_input(text):462        """Emulate keyboard input."""463        monkeypatch.setattr(sys, "stdin", StringIO(text))464465    click.echo("Echo to standard output")466    out, err = capfd.readouterr()467    assert out == "Echo to standard output\n"468    assert err == ""469470    click.echo("Echo to standard error", err=True)471    out, err = capfd.readouterr()472    assert out == ""473    assert err == "Echo to standard error\n"474475    emulate_input("asdlkj\n")476    click.prompt("Prompt to stdin")477    out, err = capfd.readouterr()478    assert out == "Prompt to stdin: "479    assert err == ""480481    emulate_input("asdlkj\n")482    click.prompt("Prompt to stdin with no suffix", prompt_suffix="")483    out, err = capfd.readouterr()484    assert out == "Prompt to stdin with no suffix"485    assert err == ""486487    emulate_input("asdlkj\n")488    click.prompt("Prompt to stderr", err=True)489    out, err = capfd.readouterr()490    assert out == " "491    assert err == "Prompt to stderr:"492493    emulate_input("asdlkj\n")494    click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)495    out, err = capfd.readouterr()496    assert out == "x"497    assert err == "Prompt to stderr with no suffi"498499    emulate_input("y\n")500    click.confirm("Prompt to stdin")501    out, err = capfd.readouterr()502    assert out == "Prompt to stdin [y/N]: "503    assert err == ""504505    emulate_input("y\n")506    click.confirm("Prompt to stdin with no suffix", prompt_suffix="")507    out, err = capfd.readouterr()508    assert out == "Prompt to stdin with no suffix [y/N]"509    assert err == ""510511    emulate_input("y\n")512    click.confirm("Prompt to stderr", err=True)513    out, err = capfd.readouterr()514    assert out == " "515    assert err == "Prompt to stderr [y/N]:"516517    emulate_input("y\n")518    click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)519    out, err = capfd.readouterr()520    assert out == "]"521    assert err == "Prompt to stderr with no suffix [y/N"522523    monkeypatch.setattr(click.termui, "isatty", lambda x: True)524    monkeypatch.setattr(click.termui, "getchar", lambda: " ")525526    click.pause("Pause to stdout")527    out, err = capfd.readouterr()528    assert out == "Pause to stdout\n"529    assert err == ""530531    click.pause("Pause to stderr", err=True)532    out, err = capfd.readouterr()533    assert out == ""534    assert err == "Pause to stderr\n"535536537def test_echo_with_capsys(capsys):538    click.echo("Capture me.")539    out, err = capsys.readouterr()540    assert out == "Capture me.\n"541542543def test_open_file(runner):544    @click.command()545    @click.argument("filename")546    def cli(filename):547        with click.open_file(filename) as f:548            click.echo(f.read())549550        click.echo("meep")551552    with runner.isolated_filesystem():553        with open("hello.txt", "w") as f:554            f.write("Cool stuff")555556        result = runner.invoke(cli, ["hello.txt"])557        assert result.exception is None558        assert result.output == "Cool stuff\nmeep\n"559560        result = runner.invoke(cli, ["-"], input="foobar")561        assert result.exception is None562        assert result.output == "foobar\nmeep\n"563564565def test_open_file_pathlib_dash(runner):566    @click.command()567    @click.argument(568        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)569    )570    def cli(filename):571        click.echo(str(type(filename)))572573        with click.open_file(filename) as f:574            click.echo(f.read())575576        result = runner.invoke(cli, ["-"], input="value")577        assert result.exception is None578        assert result.output == "pathlib.Path\nvalue\n"579580581def test_open_file_ignore_errors_stdin(runner):582    @click.command()583    @click.argument("filename")584    def cli(filename):585        with click.open_file(filename, errors="ignore") as f:586            click.echo(f.read())587588    result = runner.invoke(cli, ["-"], input=os.urandom(16))589    assert result.exception is None590591592def test_open_file_respects_ignore(runner):593    with runner.isolated_filesystem():594        with open("test.txt", "w") as f:595            f.write("Hello world!")596597        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:598            assert f.errors == "ignore"599600601def test_open_file_ignore_invalid_utf8(runner):602    with runner.isolated_filesystem():603        with open("test.txt", "wb") as f:604            f.write(b"\xe2\x28\xa1")605606        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:607            f.read()608609610def test_open_file_ignore_no_encoding(runner):611    with runner.isolated_filesystem():612        with open("test.bin", "wb") as f:613            f.write(os.urandom(16))614615        with click.open_file("test.bin", errors="ignore") as f:616            f.read()617618619@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")620@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])621def test_open_file_atomic_permissions_existing_file(runner, permissions):622    with runner.isolated_filesystem():623        with open("existing.txt", "w") as f:624            f.write("content")625        os.chmod("existing.txt", permissions)626627        @click.command()628        @click.argument("filename")629        def cli(filename):630            click.open_file(filename, "w", atomic=True).close()631632        result = runner.invoke(cli, ["existing.txt"])633        assert result.exception is None634        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions635636637@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")638def test_open_file_atomic_permissions_new_file(runner):639    with runner.isolated_filesystem():640641        @click.command()642        @click.argument("filename")643        def cli(filename):644            click.open_file(filename, "w", atomic=True).close()645646        # Create a test file to get the expected permissions for new files647        # according to the current umask.648        with open("test.txt", "w"):649            pass650        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)651652        result = runner.invoke(cli, ["new.txt"])653        assert result.exception is None654        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions655656657def test_iter_keepopenfile(tmpdir):658    expected = list(map(str, range(10)))659    p = tmpdir.mkdir("testdir").join("testfile")660    p.write("\n".join(expected))661    with p.open() as f:662        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):663            assert e_line == a_line.strip()664665666def test_iter_lazyfile(tmpdir):667    expected = list(map(str, range(10)))668    p = tmpdir.mkdir("testdir").join("testfile")669    p.write("\n".join(expected))670    with p.open() as f:671        with click.utils.LazyFile(f.name) as lf:672            for e_line, a_line in zip(expected, lf, strict=False):673                assert e_line == a_line.strip()674675676class MockMain:677    __slots__ = "__package__"678679    def __init__(self, package_name):680        self.__package__ = package_name681682683@pytest.mark.parametrize(684    ("path", "main", "expected"),685    [686        ("example.py", None, "example.py"),687        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),688        ("example", None, "example"),689        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),690        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),691        (str(pathlib.Path("./example")), "", "example"),692    ],693)694def test_detect_program_name(path, main, expected):695    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected696697698def test_expand_args(monkeypatch):699    user = os.path.expanduser("~")700    assert user in click.utils._expand_args(["~"])701    monkeypatch.setenv("CLICK_TEST", "hello")702    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])703    assert "pyproject.toml" in click.utils._expand_args(["*.toml"])704    assert os.path.join("tests", "conftest.py") in click.utils._expand_args(705        ["**/conftest.py"]706    )707    assert "*.not-found" in click.utils._expand_args(["*.not-found"])708    # a bad glob pattern, such as a pytest identifier, should return itself709    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"710711712@pytest.mark.parametrize(713    ("value", "max_length", "expect"),714    [715        pytest.param("", 10, "", id="empty"),716        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),717        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),718        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),719        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),720        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),721        pytest.param(722            "token in ~/.netrc ciao ciao",723            20,724            "token in ~/.netrc...",725            id="ignore dot in word",726        ),727    ],728)729@pytest.mark.parametrize(730    "alter",731    [732        pytest.param(None, id=""),733        pytest.param(734            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"735        ),736    ],737)738def test_make_default_short_help(value, max_length, alter, expect):739    assert len(expect) <= max_length740741    if alter:742        value = alter(value)743744    out = click.utils.make_default_short_help(value, max_length)745    assert out == expect