Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

395 lines · 11.8 KiB · Python

Last changed by

apply flake8David Lordbefore adoption5f75f9e

History of this file

Take it

1import os2import stat3import sys45import pytest67import click._termui_impl8import click.utils9from click._compat import WIN101112def test_echo(runner):13    with runner.isolation() as outstreams:14        click.echo(u"\N{SNOWMAN}")15        click.echo(b"\x44\x44")16        click.echo(42, nl=False)17        click.echo(b"a", nl=False)18        click.echo("\x1b[31mx\x1b[39m", nl=False)19        bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")20        assert bytes == b"\xe2\x98\x83\nDD\n42ax"2122    # If we are in Python 2, we expect that writing bytes into a string io23    # does not do anything crazy.  In Python 324    if sys.version_info[0] == 2:25        import StringIO2627        sys.stdout = x = StringIO.StringIO()28        try:29            click.echo("\xf6")30        finally:31            sys.stdout = sys.__stdout__32        assert x.getvalue() == "\xf6\n"3334    # And in any case, if wrapped, we expect bytes to survive.35    @click.command()36    def cli():37        click.echo(b"\xf6")3839    result = runner.invoke(cli, [])40    assert result.stdout_bytes == b"\xf6\n"4142    # Ensure we do not strip for bytes.43    with runner.isolation() as outstreams:44        click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)45        assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"464748def test_echo_custom_file():49    import io5051    f = io.StringIO()52    click.echo(u"hello", file=f)53    assert f.getvalue() == u"hello\n"545556@pytest.mark.parametrize(57    ("styles", "ref"),58    [59        ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),60        ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),61        ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),62        ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),63        ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),64        ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),65        ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),66        ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),67        ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),68        ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),69        ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),70        ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),71        ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),72        ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),73        ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),74        ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),75        ({"blink": True}, "\x1b[5mx y\x1b[0m"),76        ({"underline": True}, "\x1b[4mx y\x1b[0m"),77        ({"bold": True}, "\x1b[1mx y\x1b[0m"),78        ({"dim": True}, "\x1b[2mx y\x1b[0m"),79    ],80)81def test_styling(styles, ref):82    assert click.style("x y", **styles) == ref83    assert click.unstyle(ref) == "x y"848586@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])87def test_unstyle_other_ansi(text, expect):88    assert click.unstyle(text) == expect899091def test_filename_formatting():92    assert click.format_filename(b"foo.txt") == "foo.txt"93    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"94    assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt"95    assert click.format_filename(u"/x/foo.txt", shorten=True) == "foo.txt"9697    # filesystem encoding on windows permits this.98    if not WIN:99        assert (100            click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt"101        )102103104def test_prompts(runner):105    @click.command()106    def test():107        if click.confirm("Foo"):108            click.echo("yes!")109        else:110            click.echo("no :(")111112    result = runner.invoke(test, input="y\n")113    assert not result.exception114    assert result.output == "Foo [y/N]: y\nyes!\n"115116    result = runner.invoke(test, input="\n")117    assert not result.exception118    assert result.output == "Foo [y/N]: \nno :(\n"119120    result = runner.invoke(test, input="n\n")121    assert not result.exception122    assert result.output == "Foo [y/N]: n\nno :(\n"123124    @click.command()125    def test_no():126        if click.confirm("Foo", default=True):127            click.echo("yes!")128        else:129            click.echo("no :(")130131    result = runner.invoke(test_no, input="y\n")132    assert not result.exception133    assert result.output == "Foo [Y/n]: y\nyes!\n"134135    result = runner.invoke(test_no, input="\n")136    assert not result.exception137    assert result.output == "Foo [Y/n]: \nyes!\n"138139    result = runner.invoke(test_no, input="n\n")140    assert not result.exception141    assert result.output == "Foo [Y/n]: n\nno :(\n"142143144@pytest.mark.skipif(WIN, reason="Different behavior on windows.")145def test_prompts_abort(monkeypatch, capsys):146    def f(_):147        raise KeyboardInterrupt()148149    monkeypatch.setattr("click.termui.hidden_prompt_func", f)150151    try:152        click.prompt("Password", hide_input=True)153    except click.Abort:154        click.echo("Screw you.")155156    out, err = capsys.readouterr()157    assert out == "Password: \nScrew you.\n"158159160def _test_gen_func():161    yield "a"162    yield "b"163    yield "c"164    yield "abc"165166167@pytest.mark.skipif(WIN, reason="Different behavior on windows.")168@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])169@pytest.mark.parametrize(170    "test",171    [172        # We need lambda here, because pytest will173        # reuse the parameters, and then the generators174        # are already used and will not yield anymore175        ("just text\n", lambda: "just text"),176        ("iterable\n", lambda: ["itera", "ble"]),177        ("abcabc\n", lambda: _test_gen_func),178        ("abcabc\n", lambda: _test_gen_func()),179        ("012345\n", lambda: (c for c in range(6))),180    ],181)182def test_echo_via_pager(monkeypatch, capfd, cat, test):183    monkeypatch.setitem(os.environ, "PAGER", cat)184    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)185186    expected_output = test[0]187    test_input = test[1]()188189    click.echo_via_pager(test_input)190191    out, err = capfd.readouterr()192    assert out == expected_output193194195@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")196def test_echo_color_flag(monkeypatch, capfd):197    isatty = True198    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)199200    text = "foo"201    styled_text = click.style(text, fg="red")202    assert styled_text == "\x1b[31mfoo\x1b[0m"203204    click.echo(styled_text, color=False)205    out, err = capfd.readouterr()206    assert out == text + "\n"207208    click.echo(styled_text, color=True)209    out, err = capfd.readouterr()210    assert out == styled_text + "\n"211212    isatty = True213    click.echo(styled_text)214    out, err = capfd.readouterr()215    assert out == styled_text + "\n"216217    isatty = False218    click.echo(styled_text)219    out, err = capfd.readouterr()220    assert out == text + "\n"221222223@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")224def test_echo_writing_to_standard_error(capfd, monkeypatch):225    def emulate_input(text):226        """Emulate keyboard input."""227        if sys.version_info[0] == 2:228            from StringIO import StringIO229        else:230            from io import StringIO231        monkeypatch.setattr(sys, "stdin", StringIO(text))232233    click.echo("Echo to standard output")234    out, err = capfd.readouterr()235    assert out == "Echo to standard output\n"236    assert err == ""237238    click.echo("Echo to standard error", err=True)239    out, err = capfd.readouterr()240    assert out == ""241    assert err == "Echo to standard error\n"242243    emulate_input("asdlkj\n")244    click.prompt("Prompt to stdin")245    out, err = capfd.readouterr()246    assert out == "Prompt to stdin: "247    assert err == ""248249    emulate_input("asdlkj\n")250    click.prompt("Prompt to stderr", err=True)251    out, err = capfd.readouterr()252    assert out == ""253    assert err == "Prompt to stderr: "254255    emulate_input("y\n")256    click.confirm("Prompt to stdin")257    out, err = capfd.readouterr()258    assert out == "Prompt to stdin [y/N]: "259    assert err == ""260261    emulate_input("y\n")262    click.confirm("Prompt to stderr", err=True)263    out, err = capfd.readouterr()264    assert out == ""265    assert err == "Prompt to stderr [y/N]: "266267    monkeypatch.setattr(click.termui, "isatty", lambda x: True)268    monkeypatch.setattr(click.termui, "getchar", lambda: " ")269270    click.pause("Pause to stdout")271    out, err = capfd.readouterr()272    assert out == "Pause to stdout\n"273    assert err == ""274275    click.pause("Pause to stderr", err=True)276    out, err = capfd.readouterr()277    assert out == ""278    assert err == "Pause to stderr\n"279280281def test_open_file(runner):282    @click.command()283    @click.argument("filename")284    def cli(filename):285        with click.open_file(filename) as f:286            click.echo(f.read())287288        click.echo("meep")289290    with runner.isolated_filesystem():291        with open("hello.txt", "w") as f:292            f.write("Cool stuff")293294        result = runner.invoke(cli, ["hello.txt"])295        assert result.exception is None296        assert result.output == "Cool stuff\nmeep\n"297298        result = runner.invoke(cli, ["-"], input="foobar")299        assert result.exception is None300        assert result.output == "foobar\nmeep\n"301302303def test_open_file_ignore_errors_stdin(runner):304    @click.command()305    @click.argument("filename")306    def cli(filename):307        with click.open_file(filename, errors="ignore") as f:308            click.echo(f.read())309310    result = runner.invoke(cli, ["-"], input=os.urandom(16))311    assert result.exception is None312313314def test_open_file_respects_ignore(runner):315    with runner.isolated_filesystem():316        with open("test.txt", "w") as f:317            f.write("Hello world!")318319        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:320            assert f.errors == "ignore"321322323def test_open_file_ignore_invalid_utf8(runner):324    with runner.isolated_filesystem():325        with open("test.txt", "wb") as f:326            f.write(b"\xe2\x28\xa1")327328        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:329            f.read()330331332def test_open_file_ignore_no_encoding(runner):333    with runner.isolated_filesystem():334        with open("test.bin", "wb") as f:335            f.write(os.urandom(16))336337        with click.open_file("test.bin", errors="ignore") as f:338            f.read()339340341@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")342@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])343def test_open_file_atomic_permissions_existing_file(runner, permissions):344    with runner.isolated_filesystem():345        with open("existing.txt", "w") as f:346            f.write("content")347        os.chmod("existing.txt", permissions)348349        @click.command()350        @click.argument("filename")351        def cli(filename):352            click.open_file(filename, "w", atomic=True).close()353354        result = runner.invoke(cli, ["existing.txt"])355        assert result.exception is None356        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions357358359@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")360def test_open_file_atomic_permissions_new_file(runner):361    with runner.isolated_filesystem():362363        @click.command()364        @click.argument("filename")365        def cli(filename):366            click.open_file(filename, "w", atomic=True).close()367368        # Create a test file to get the expected permissions for new files369        # according to the current umask.370        with open("test.txt", "w"):371            pass372        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)373374        result = runner.invoke(cli, ["new.txt"])375        assert result.exception is None376        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions377378379def test_iter_keepopenfile(tmpdir):380    expected = list(map(str, range(10)))381    p = tmpdir.mkdir("testdir").join("testfile")382    p.write("\n".join(expected))383    with p.open() as f:384        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):385            assert e_line == a_line.strip()386387388def test_iter_lazyfile(tmpdir):389    expected = list(map(str, range(10)))390    p = tmpdir.mkdir("testdir").join("testfile")391    p.write("\n".join(expected))392    with p.open() as f:393        with click.utils.LazyFile(f.name) as lf:394            for e_line, a_line in zip(expected, lf):395                assert e_line == a_line.strip()