Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

722 lines · 22.3 KiB · Python

Last changed by

Differentiate absence of value and value of absence for `default` and `flag_value` arguments (#3030)Rowlando13before adoption2170eec

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 stderr", err=True)486    out, err = capfd.readouterr()487    assert out == " "488    assert err == "Prompt to stderr:"489490    emulate_input("y\n")491    click.confirm("Prompt to stdin")492    out, err = capfd.readouterr()493    assert out == "Prompt to stdin [y/N]: "494    assert err == ""495496    emulate_input("y\n")497    click.confirm("Prompt to stderr", err=True)498    out, err = capfd.readouterr()499    assert out == " "500    assert err == "Prompt to stderr [y/N]:"501502    monkeypatch.setattr(click.termui, "isatty", lambda x: True)503    monkeypatch.setattr(click.termui, "getchar", lambda: " ")504505    click.pause("Pause to stdout")506    out, err = capfd.readouterr()507    assert out == "Pause to stdout\n"508    assert err == ""509510    click.pause("Pause to stderr", err=True)511    out, err = capfd.readouterr()512    assert out == ""513    assert err == "Pause to stderr\n"514515516def test_echo_with_capsys(capsys):517    click.echo("Capture me.")518    out, err = capsys.readouterr()519    assert out == "Capture me.\n"520521522def test_open_file(runner):523    @click.command()524    @click.argument("filename")525    def cli(filename):526        with click.open_file(filename) as f:527            click.echo(f.read())528529        click.echo("meep")530531    with runner.isolated_filesystem():532        with open("hello.txt", "w") as f:533            f.write("Cool stuff")534535        result = runner.invoke(cli, ["hello.txt"])536        assert result.exception is None537        assert result.output == "Cool stuff\nmeep\n"538539        result = runner.invoke(cli, ["-"], input="foobar")540        assert result.exception is None541        assert result.output == "foobar\nmeep\n"542543544def test_open_file_pathlib_dash(runner):545    @click.command()546    @click.argument(547        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)548    )549    def cli(filename):550        click.echo(str(type(filename)))551552        with click.open_file(filename) as f:553            click.echo(f.read())554555        result = runner.invoke(cli, ["-"], input="value")556        assert result.exception is None557        assert result.output == "pathlib.Path\nvalue\n"558559560def test_open_file_ignore_errors_stdin(runner):561    @click.command()562    @click.argument("filename")563    def cli(filename):564        with click.open_file(filename, errors="ignore") as f:565            click.echo(f.read())566567    result = runner.invoke(cli, ["-"], input=os.urandom(16))568    assert result.exception is None569570571def test_open_file_respects_ignore(runner):572    with runner.isolated_filesystem():573        with open("test.txt", "w") as f:574            f.write("Hello world!")575576        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:577            assert f.errors == "ignore"578579580def test_open_file_ignore_invalid_utf8(runner):581    with runner.isolated_filesystem():582        with open("test.txt", "wb") as f:583            f.write(b"\xe2\x28\xa1")584585        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:586            f.read()587588589def test_open_file_ignore_no_encoding(runner):590    with runner.isolated_filesystem():591        with open("test.bin", "wb") as f:592            f.write(os.urandom(16))593594        with click.open_file("test.bin", errors="ignore") as f:595            f.read()596597598@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")599@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])600def test_open_file_atomic_permissions_existing_file(runner, permissions):601    with runner.isolated_filesystem():602        with open("existing.txt", "w") as f:603            f.write("content")604        os.chmod("existing.txt", permissions)605606        @click.command()607        @click.argument("filename")608        def cli(filename):609            click.open_file(filename, "w", atomic=True).close()610611        result = runner.invoke(cli, ["existing.txt"])612        assert result.exception is None613        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions614615616@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")617def test_open_file_atomic_permissions_new_file(runner):618    with runner.isolated_filesystem():619620        @click.command()621        @click.argument("filename")622        def cli(filename):623            click.open_file(filename, "w", atomic=True).close()624625        # Create a test file to get the expected permissions for new files626        # according to the current umask.627        with open("test.txt", "w"):628            pass629        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)630631        result = runner.invoke(cli, ["new.txt"])632        assert result.exception is None633        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions634635636def test_iter_keepopenfile(tmpdir):637    expected = list(map(str, range(10)))638    p = tmpdir.mkdir("testdir").join("testfile")639    p.write("\n".join(expected))640    with p.open() as f:641        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):642            assert e_line == a_line.strip()643644645def test_iter_lazyfile(tmpdir):646    expected = list(map(str, range(10)))647    p = tmpdir.mkdir("testdir").join("testfile")648    p.write("\n".join(expected))649    with p.open() as f:650        with click.utils.LazyFile(f.name) as lf:651            for e_line, a_line in zip(expected, lf, strict=False):652                assert e_line == a_line.strip()653654655class MockMain:656    __slots__ = "__package__"657658    def __init__(self, package_name):659        self.__package__ = package_name660661662@pytest.mark.parametrize(663    ("path", "main", "expected"),664    [665        ("example.py", None, "example.py"),666        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),667        ("example", None, "example"),668        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),669        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),670        (str(pathlib.Path("./example")), "", "example"),671    ],672)673def test_detect_program_name(path, main, expected):674    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected675676677def test_expand_args(monkeypatch):678    user = os.path.expanduser("~")679    assert user in click.utils._expand_args(["~"])680    monkeypatch.setenv("CLICK_TEST", "hello")681    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])682    assert "pyproject.toml" in click.utils._expand_args(["*.toml"])683    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])684    assert "*.not-found" in click.utils._expand_args(["*.not-found"])685    # a bad glob pattern, such as a pytest identifier, should return itself686    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"687688689@pytest.mark.parametrize(690    ("value", "max_length", "expect"),691    [692        pytest.param("", 10, "", id="empty"),693        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),694        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),695        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),696        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),697        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),698        pytest.param(699            "token in ~/.netrc ciao ciao",700            20,701            "token in ~/.netrc...",702            id="ignore dot in word",703        ),704    ],705)706@pytest.mark.parametrize(707    "alter",708    [709        pytest.param(None, id=""),710        pytest.param(711            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"712        ),713    ],714)715def test_make_default_short_help(value, max_length, alter, expect):716    assert len(expect) <= max_length717718    if alter:719        value = alter(value)720721    out = click.utils.make_default_short_help(value, max_length)722    assert out == expect