Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

431 lines · 12.8 KiB · Python

Last changed by

Merge pull request #1402 from yurihs/add-repeat-behavior-to-promptDavid Lordbefore adoption719690a

History of this file

Take it

1import os2import pathlib3import stat4import sys5from io import StringIO67import pytest89import click._termui_impl10import click.utils11from click._compat import WIN121314def test_echo(runner):15    with runner.isolation() as outstreams:16        click.echo("\N{SNOWMAN}")17        click.echo(b"\x44\x44")18        click.echo(42, nl=False)19        click.echo(b"a", nl=False)20        click.echo("\x1b[31mx\x1b[39m", nl=False)21        bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")22        assert bytes == b"\xe2\x98\x83\nDD\n42ax"2324    # if wrapped, we expect bytes to survive.25    @click.command()26    def cli():27        click.echo(b"\xf6")2829    result = runner.invoke(cli, [])30    assert result.stdout_bytes == b"\xf6\n"3132    # Ensure we do not strip for bytes.33    with runner.isolation() as outstreams:34        click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)35        assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"363738def test_echo_custom_file():39    import io4041    f = io.StringIO()42    click.echo("hello", file=f)43    assert f.getvalue() == "hello\n"444546@pytest.mark.parametrize(47    ("styles", "ref"),48    [49        ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),50        ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),51        ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),52        ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),53        ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),54        ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),55        ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),56        ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),57        ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),58        ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),59        ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),60        ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),61        ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),62        ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),63        ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),64        ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),65        ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),66        ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),67        ({"blink": True}, "\x1b[5mx y\x1b[0m"),68        ({"underline": True}, "\x1b[4mx y\x1b[0m"),69        ({"bold": True}, "\x1b[1mx y\x1b[0m"),70        ({"dim": True}, "\x1b[2mx y\x1b[0m"),71    ],72)73def test_styling(styles, ref):74    assert click.style("x y", **styles) == ref75    assert click.unstyle(ref) == "x y"767778@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])79def test_unstyle_other_ansi(text, expect):80    assert click.unstyle(text) == expect818283def test_filename_formatting():84    assert click.format_filename(b"foo.txt") == "foo.txt"85    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"86    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"87    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"8889    # filesystem encoding on windows permits this.90    if not WIN:91        assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\ufffd.txt"929394def test_prompts(runner):95    @click.command()96    def test():97        if click.confirm("Foo"):98            click.echo("yes!")99        else:100            click.echo("no :(")101102    result = runner.invoke(test, input="y\n")103    assert not result.exception104    assert result.output == "Foo [y/N]: y\nyes!\n"105106    result = runner.invoke(test, input="\n")107    assert not result.exception108    assert result.output == "Foo [y/N]: \nno :(\n"109110    result = runner.invoke(test, input="n\n")111    assert not result.exception112    assert result.output == "Foo [y/N]: n\nno :(\n"113114    @click.command()115    def test_no():116        if click.confirm("Foo", default=True):117            click.echo("yes!")118        else:119            click.echo("no :(")120121    result = runner.invoke(test_no, input="y\n")122    assert not result.exception123    assert result.output == "Foo [Y/n]: y\nyes!\n"124125    result = runner.invoke(test_no, input="\n")126    assert not result.exception127    assert result.output == "Foo [Y/n]: \nyes!\n"128129    result = runner.invoke(test_no, input="n\n")130    assert not result.exception131    assert result.output == "Foo [Y/n]: n\nno :(\n"132133134def test_confirm_repeat(runner):135    cli = click.Command(136        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]137    )138    result = runner.invoke(cli, input="\ny\n")139    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"140141142@pytest.mark.skipif(WIN, reason="Different behavior on windows.")143def test_prompts_abort(monkeypatch, capsys):144    def f(_):145        raise KeyboardInterrupt()146147    monkeypatch.setattr("click.termui.hidden_prompt_func", f)148149    try:150        click.prompt("Password", hide_input=True)151    except click.Abort:152        click.echo("Screw you.")153154    out, err = capsys.readouterr()155    assert out == "Password: \nScrew you.\n"156157158def _test_gen_func():159    yield "a"160    yield "b"161    yield "c"162    yield "abc"163164165@pytest.mark.skipif(WIN, reason="Different behavior on windows.")166@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])167@pytest.mark.parametrize(168    "test",169    [170        # We need lambda here, because pytest will171        # reuse the parameters, and then the generators172        # are already used and will not yield anymore173        ("just text\n", lambda: "just text"),174        ("iterable\n", lambda: ["itera", "ble"]),175        ("abcabc\n", lambda: _test_gen_func),176        ("abcabc\n", lambda: _test_gen_func()),177        ("012345\n", lambda: (c for c in range(6))),178    ],179)180def test_echo_via_pager(monkeypatch, capfd, cat, test):181    monkeypatch.setitem(os.environ, "PAGER", cat)182    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)183184    expected_output = test[0]185    test_input = test[1]()186187    click.echo_via_pager(test_input)188189    out, err = capfd.readouterr()190    assert out == expected_output191192193@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")194def test_echo_color_flag(monkeypatch, capfd):195    isatty = True196    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)197198    text = "foo"199    styled_text = click.style(text, fg="red")200    assert styled_text == "\x1b[31mfoo\x1b[0m"201202    click.echo(styled_text, color=False)203    out, err = capfd.readouterr()204    assert out == f"{text}\n"205206    click.echo(styled_text, color=True)207    out, err = capfd.readouterr()208    assert out == f"{styled_text}\n"209210    isatty = True211    click.echo(styled_text)212    out, err = capfd.readouterr()213    assert out == f"{styled_text}\n"214215    isatty = False216    click.echo(styled_text)217    out, err = capfd.readouterr()218    assert out == f"{text}\n"219220221def test_prompt_cast_default(capfd, monkeypatch):222    monkeypatch.setattr(sys, "stdin", StringIO("\n"))223    value = click.prompt("value", default="100", type=int)224    capfd.readouterr()225    assert type(value) is int226227228@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")229def test_echo_writing_to_standard_error(capfd, monkeypatch):230    def emulate_input(text):231        """Emulate keyboard input."""232        monkeypatch.setattr(sys, "stdin", StringIO(text))233234    click.echo("Echo to standard output")235    out, err = capfd.readouterr()236    assert out == "Echo to standard output\n"237    assert err == ""238239    click.echo("Echo to standard error", err=True)240    out, err = capfd.readouterr()241    assert out == ""242    assert err == "Echo to standard error\n"243244    emulate_input("asdlkj\n")245    click.prompt("Prompt to stdin")246    out, err = capfd.readouterr()247    assert out == "Prompt to stdin: "248    assert err == ""249250    emulate_input("asdlkj\n")251    click.prompt("Prompt to stderr", err=True)252    out, err = capfd.readouterr()253    assert out == ""254    assert err == "Prompt to stderr: "255256    emulate_input("y\n")257    click.confirm("Prompt to stdin")258    out, err = capfd.readouterr()259    assert out == "Prompt to stdin [y/N]: "260    assert err == ""261262    emulate_input("y\n")263    click.confirm("Prompt to stderr", err=True)264    out, err = capfd.readouterr()265    assert out == ""266    assert err == "Prompt to stderr [y/N]: "267268    monkeypatch.setattr(click.termui, "isatty", lambda x: True)269    monkeypatch.setattr(click.termui, "getchar", lambda: " ")270271    click.pause("Pause to stdout")272    out, err = capfd.readouterr()273    assert out == "Pause to stdout\n"274    assert err == ""275276    click.pause("Pause to stderr", err=True)277    out, err = capfd.readouterr()278    assert out == ""279    assert err == "Pause to stderr\n"280281282def test_echo_with_capsys(capsys):283    click.echo("Capture me.")284    out, err = capsys.readouterr()285    assert out == "Capture me.\n"286287288def test_open_file(runner):289    @click.command()290    @click.argument("filename")291    def cli(filename):292        with click.open_file(filename) as f:293            click.echo(f.read())294295        click.echo("meep")296297    with runner.isolated_filesystem():298        with open("hello.txt", "w") as f:299            f.write("Cool stuff")300301        result = runner.invoke(cli, ["hello.txt"])302        assert result.exception is None303        assert result.output == "Cool stuff\nmeep\n"304305        result = runner.invoke(cli, ["-"], input="foobar")306        assert result.exception is None307        assert result.output == "foobar\nmeep\n"308309310def test_open_file_ignore_errors_stdin(runner):311    @click.command()312    @click.argument("filename")313    def cli(filename):314        with click.open_file(filename, errors="ignore") as f:315            click.echo(f.read())316317    result = runner.invoke(cli, ["-"], input=os.urandom(16))318    assert result.exception is None319320321def test_open_file_respects_ignore(runner):322    with runner.isolated_filesystem():323        with open("test.txt", "w") as f:324            f.write("Hello world!")325326        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:327            assert f.errors == "ignore"328329330def test_open_file_ignore_invalid_utf8(runner):331    with runner.isolated_filesystem():332        with open("test.txt", "wb") as f:333            f.write(b"\xe2\x28\xa1")334335        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:336            f.read()337338339def test_open_file_ignore_no_encoding(runner):340    with runner.isolated_filesystem():341        with open("test.bin", "wb") as f:342            f.write(os.urandom(16))343344        with click.open_file("test.bin", errors="ignore") as f:345            f.read()346347348@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")349@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])350def test_open_file_atomic_permissions_existing_file(runner, permissions):351    with runner.isolated_filesystem():352        with open("existing.txt", "w") as f:353            f.write("content")354        os.chmod("existing.txt", permissions)355356        @click.command()357        @click.argument("filename")358        def cli(filename):359            click.open_file(filename, "w", atomic=True).close()360361        result = runner.invoke(cli, ["existing.txt"])362        assert result.exception is None363        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions364365366@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")367def test_open_file_atomic_permissions_new_file(runner):368    with runner.isolated_filesystem():369370        @click.command()371        @click.argument("filename")372        def cli(filename):373            click.open_file(filename, "w", atomic=True).close()374375        # Create a test file to get the expected permissions for new files376        # according to the current umask.377        with open("test.txt", "w"):378            pass379        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)380381        result = runner.invoke(cli, ["new.txt"])382        assert result.exception is None383        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions384385386def test_iter_keepopenfile(tmpdir):387    expected = list(map(str, range(10)))388    p = tmpdir.mkdir("testdir").join("testfile")389    p.write("\n".join(expected))390    with p.open() as f:391        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):392            assert e_line == a_line.strip()393394395def test_iter_lazyfile(tmpdir):396    expected = list(map(str, range(10)))397    p = tmpdir.mkdir("testdir").join("testfile")398    p.write("\n".join(expected))399    with p.open() as f:400        with click.utils.LazyFile(f.name) as lf:401            for e_line, a_line in zip(expected, lf):402                assert e_line == a_line.strip()403404405class MockMain:406    __slots__ = "__package__"407408    def __init__(self, package_name):409        self.__package__ = package_name410411412@pytest.mark.parametrize(413    ("path", "main", "expected"),414    [415        ("example.py", None, "example.py"),416        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),417        ("example", None, "example"),418        (419            str(pathlib.Path("example/__main__.py")),420            MockMain(".example"),421            "python -m example",422        ),423        (424            str(pathlib.Path("example/cli.py")),425            MockMain(".example"),426            "python -m example.cli",427        ),428    ],429)430def test_detect_program_name(path, main, expected):431    assert click.utils._detect_program_name(path, _main=main) == expected