Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

414 lines · 12.2 KiB · Python

Last changed by

Merge pull request #1609 from MLH-Fellowship/program-name-detectionDavid Lordbefore adoption6c1eaba

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        ({"blink": True}, "\x1b[5mx y\x1b[0m"),66        ({"underline": True}, "\x1b[4mx y\x1b[0m"),67        ({"bold": True}, "\x1b[1mx y\x1b[0m"),68        ({"dim": True}, "\x1b[2mx y\x1b[0m"),69    ],70)71def test_styling(styles, ref):72    assert click.style("x y", **styles) == ref73    assert click.unstyle(ref) == "x y"747576@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])77def test_unstyle_other_ansi(text, expect):78    assert click.unstyle(text) == expect798081def test_filename_formatting():82    assert click.format_filename(b"foo.txt") == "foo.txt"83    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"84    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"85    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"8687    # filesystem encoding on windows permits this.88    if not WIN:89        assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\ufffd.txt"909192def test_prompts(runner):93    @click.command()94    def test():95        if click.confirm("Foo"):96            click.echo("yes!")97        else:98            click.echo("no :(")99100    result = runner.invoke(test, input="y\n")101    assert not result.exception102    assert result.output == "Foo [y/N]: y\nyes!\n"103104    result = runner.invoke(test, input="\n")105    assert not result.exception106    assert result.output == "Foo [y/N]: \nno :(\n"107108    result = runner.invoke(test, input="n\n")109    assert not result.exception110    assert result.output == "Foo [y/N]: n\nno :(\n"111112    @click.command()113    def test_no():114        if click.confirm("Foo", default=True):115            click.echo("yes!")116        else:117            click.echo("no :(")118119    result = runner.invoke(test_no, input="y\n")120    assert not result.exception121    assert result.output == "Foo [Y/n]: y\nyes!\n"122123    result = runner.invoke(test_no, input="\n")124    assert not result.exception125    assert result.output == "Foo [Y/n]: \nyes!\n"126127    result = runner.invoke(test_no, input="n\n")128    assert not result.exception129    assert result.output == "Foo [Y/n]: n\nno :(\n"130131132@pytest.mark.skipif(WIN, reason="Different behavior on windows.")133def test_prompts_abort(monkeypatch, capsys):134    def f(_):135        raise KeyboardInterrupt()136137    monkeypatch.setattr("click.termui.hidden_prompt_func", f)138139    try:140        click.prompt("Password", hide_input=True)141    except click.Abort:142        click.echo("Screw you.")143144    out, err = capsys.readouterr()145    assert out == "Password: \nScrew you.\n"146147148def _test_gen_func():149    yield "a"150    yield "b"151    yield "c"152    yield "abc"153154155@pytest.mark.skipif(WIN, reason="Different behavior on windows.")156@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])157@pytest.mark.parametrize(158    "test",159    [160        # We need lambda here, because pytest will161        # reuse the parameters, and then the generators162        # are already used and will not yield anymore163        ("just text\n", lambda: "just text"),164        ("iterable\n", lambda: ["itera", "ble"]),165        ("abcabc\n", lambda: _test_gen_func),166        ("abcabc\n", lambda: _test_gen_func()),167        ("012345\n", lambda: (c for c in range(6))),168    ],169)170def test_echo_via_pager(monkeypatch, capfd, cat, test):171    monkeypatch.setitem(os.environ, "PAGER", cat)172    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)173174    expected_output = test[0]175    test_input = test[1]()176177    click.echo_via_pager(test_input)178179    out, err = capfd.readouterr()180    assert out == expected_output181182183@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")184def test_echo_color_flag(monkeypatch, capfd):185    isatty = True186    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)187188    text = "foo"189    styled_text = click.style(text, fg="red")190    assert styled_text == "\x1b[31mfoo\x1b[0m"191192    click.echo(styled_text, color=False)193    out, err = capfd.readouterr()194    assert out == f"{text}\n"195196    click.echo(styled_text, color=True)197    out, err = capfd.readouterr()198    assert out == f"{styled_text}\n"199200    isatty = True201    click.echo(styled_text)202    out, err = capfd.readouterr()203    assert out == f"{styled_text}\n"204205    isatty = False206    click.echo(styled_text)207    out, err = capfd.readouterr()208    assert out == f"{text}\n"209210211@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")212def test_echo_writing_to_standard_error(capfd, monkeypatch):213    def emulate_input(text):214        """Emulate keyboard input."""215        monkeypatch.setattr(sys, "stdin", StringIO(text))216217    click.echo("Echo to standard output")218    out, err = capfd.readouterr()219    assert out == "Echo to standard output\n"220    assert err == ""221222    click.echo("Echo to standard error", err=True)223    out, err = capfd.readouterr()224    assert out == ""225    assert err == "Echo to standard error\n"226227    emulate_input("asdlkj\n")228    click.prompt("Prompt to stdin")229    out, err = capfd.readouterr()230    assert out == "Prompt to stdin: "231    assert err == ""232233    emulate_input("asdlkj\n")234    click.prompt("Prompt to stderr", err=True)235    out, err = capfd.readouterr()236    assert out == ""237    assert err == "Prompt to stderr: "238239    emulate_input("y\n")240    click.confirm("Prompt to stdin")241    out, err = capfd.readouterr()242    assert out == "Prompt to stdin [y/N]: "243    assert err == ""244245    emulate_input("y\n")246    click.confirm("Prompt to stderr", err=True)247    out, err = capfd.readouterr()248    assert out == ""249    assert err == "Prompt to stderr [y/N]: "250251    monkeypatch.setattr(click.termui, "isatty", lambda x: True)252    monkeypatch.setattr(click.termui, "getchar", lambda: " ")253254    click.pause("Pause to stdout")255    out, err = capfd.readouterr()256    assert out == "Pause to stdout\n"257    assert err == ""258259    click.pause("Pause to stderr", err=True)260    out, err = capfd.readouterr()261    assert out == ""262    assert err == "Pause to stderr\n"263264265def test_echo_with_capsys(capsys):266    click.echo("Capture me.")267    out, err = capsys.readouterr()268    assert out == "Capture me.\n"269270271def test_open_file(runner):272    @click.command()273    @click.argument("filename")274    def cli(filename):275        with click.open_file(filename) as f:276            click.echo(f.read())277278        click.echo("meep")279280    with runner.isolated_filesystem():281        with open("hello.txt", "w") as f:282            f.write("Cool stuff")283284        result = runner.invoke(cli, ["hello.txt"])285        assert result.exception is None286        assert result.output == "Cool stuff\nmeep\n"287288        result = runner.invoke(cli, ["-"], input="foobar")289        assert result.exception is None290        assert result.output == "foobar\nmeep\n"291292293def test_open_file_ignore_errors_stdin(runner):294    @click.command()295    @click.argument("filename")296    def cli(filename):297        with click.open_file(filename, errors="ignore") as f:298            click.echo(f.read())299300    result = runner.invoke(cli, ["-"], input=os.urandom(16))301    assert result.exception is None302303304def test_open_file_respects_ignore(runner):305    with runner.isolated_filesystem():306        with open("test.txt", "w") as f:307            f.write("Hello world!")308309        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:310            assert f.errors == "ignore"311312313def test_open_file_ignore_invalid_utf8(runner):314    with runner.isolated_filesystem():315        with open("test.txt", "wb") as f:316            f.write(b"\xe2\x28\xa1")317318        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:319            f.read()320321322def test_open_file_ignore_no_encoding(runner):323    with runner.isolated_filesystem():324        with open("test.bin", "wb") as f:325            f.write(os.urandom(16))326327        with click.open_file("test.bin", errors="ignore") as f:328            f.read()329330331@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")332@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])333def test_open_file_atomic_permissions_existing_file(runner, permissions):334    with runner.isolated_filesystem():335        with open("existing.txt", "w") as f:336            f.write("content")337        os.chmod("existing.txt", permissions)338339        @click.command()340        @click.argument("filename")341        def cli(filename):342            click.open_file(filename, "w", atomic=True).close()343344        result = runner.invoke(cli, ["existing.txt"])345        assert result.exception is None346        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions347348349@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")350def test_open_file_atomic_permissions_new_file(runner):351    with runner.isolated_filesystem():352353        @click.command()354        @click.argument("filename")355        def cli(filename):356            click.open_file(filename, "w", atomic=True).close()357358        # Create a test file to get the expected permissions for new files359        # according to the current umask.360        with open("test.txt", "w"):361            pass362        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)363364        result = runner.invoke(cli, ["new.txt"])365        assert result.exception is None366        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions367368369def test_iter_keepopenfile(tmpdir):370    expected = list(map(str, range(10)))371    p = tmpdir.mkdir("testdir").join("testfile")372    p.write("\n".join(expected))373    with p.open() as f:374        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):375            assert e_line == a_line.strip()376377378def test_iter_lazyfile(tmpdir):379    expected = list(map(str, range(10)))380    p = tmpdir.mkdir("testdir").join("testfile")381    p.write("\n".join(expected))382    with p.open() as f:383        with click.utils.LazyFile(f.name) as lf:384            for e_line, a_line in zip(expected, lf):385                assert e_line == a_line.strip()386387388class MockMain:389    __slots__ = "__package__"390391    def __init__(self, package_name):392        self.__package__ = package_name393394395@pytest.mark.parametrize(396    ("path", "main", "expected"),397    [398        ("example.py", None, "example.py"),399        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),400        ("example", None, "example"),401        (402            str(pathlib.Path("example/__main__.py")),403            MockMain(".example"),404            "python -m example",405        ),406        (407            str(pathlib.Path("example/cli.py")),408            MockMain(".example"),409            "python -m example.cli",410        ),411    ],412)413def test_detect_program_name(path, main, expected):414    assert click.utils._detect_program_name(path, _main=main) == expected