Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

416 lines · 12.3 KiB · Python

Last changed by

Merge pull request #1429 from lmjohns3/masterDavid Lordbefore adoption0d43812

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"132133134@pytest.mark.skipif(WIN, reason="Different behavior on windows.")135def test_prompts_abort(monkeypatch, capsys):136    def f(_):137        raise KeyboardInterrupt()138139    monkeypatch.setattr("click.termui.hidden_prompt_func", f)140141    try:142        click.prompt("Password", hide_input=True)143    except click.Abort:144        click.echo("Screw you.")145146    out, err = capsys.readouterr()147    assert out == "Password: \nScrew you.\n"148149150def _test_gen_func():151    yield "a"152    yield "b"153    yield "c"154    yield "abc"155156157@pytest.mark.skipif(WIN, reason="Different behavior on windows.")158@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])159@pytest.mark.parametrize(160    "test",161    [162        # We need lambda here, because pytest will163        # reuse the parameters, and then the generators164        # are already used and will not yield anymore165        ("just text\n", lambda: "just text"),166        ("iterable\n", lambda: ["itera", "ble"]),167        ("abcabc\n", lambda: _test_gen_func),168        ("abcabc\n", lambda: _test_gen_func()),169        ("012345\n", lambda: (c for c in range(6))),170    ],171)172def test_echo_via_pager(monkeypatch, capfd, cat, test):173    monkeypatch.setitem(os.environ, "PAGER", cat)174    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)175176    expected_output = test[0]177    test_input = test[1]()178179    click.echo_via_pager(test_input)180181    out, err = capfd.readouterr()182    assert out == expected_output183184185@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")186def test_echo_color_flag(monkeypatch, capfd):187    isatty = True188    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)189190    text = "foo"191    styled_text = click.style(text, fg="red")192    assert styled_text == "\x1b[31mfoo\x1b[0m"193194    click.echo(styled_text, color=False)195    out, err = capfd.readouterr()196    assert out == f"{text}\n"197198    click.echo(styled_text, color=True)199    out, err = capfd.readouterr()200    assert out == f"{styled_text}\n"201202    isatty = True203    click.echo(styled_text)204    out, err = capfd.readouterr()205    assert out == f"{styled_text}\n"206207    isatty = False208    click.echo(styled_text)209    out, err = capfd.readouterr()210    assert out == f"{text}\n"211212213@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")214def test_echo_writing_to_standard_error(capfd, monkeypatch):215    def emulate_input(text):216        """Emulate keyboard input."""217        monkeypatch.setattr(sys, "stdin", StringIO(text))218219    click.echo("Echo to standard output")220    out, err = capfd.readouterr()221    assert out == "Echo to standard output\n"222    assert err == ""223224    click.echo("Echo to standard error", err=True)225    out, err = capfd.readouterr()226    assert out == ""227    assert err == "Echo to standard error\n"228229    emulate_input("asdlkj\n")230    click.prompt("Prompt to stdin")231    out, err = capfd.readouterr()232    assert out == "Prompt to stdin: "233    assert err == ""234235    emulate_input("asdlkj\n")236    click.prompt("Prompt to stderr", err=True)237    out, err = capfd.readouterr()238    assert out == ""239    assert err == "Prompt to stderr: "240241    emulate_input("y\n")242    click.confirm("Prompt to stdin")243    out, err = capfd.readouterr()244    assert out == "Prompt to stdin [y/N]: "245    assert err == ""246247    emulate_input("y\n")248    click.confirm("Prompt to stderr", err=True)249    out, err = capfd.readouterr()250    assert out == ""251    assert err == "Prompt to stderr [y/N]: "252253    monkeypatch.setattr(click.termui, "isatty", lambda x: True)254    monkeypatch.setattr(click.termui, "getchar", lambda: " ")255256    click.pause("Pause to stdout")257    out, err = capfd.readouterr()258    assert out == "Pause to stdout\n"259    assert err == ""260261    click.pause("Pause to stderr", err=True)262    out, err = capfd.readouterr()263    assert out == ""264    assert err == "Pause to stderr\n"265266267def test_echo_with_capsys(capsys):268    click.echo("Capture me.")269    out, err = capsys.readouterr()270    assert out == "Capture me.\n"271272273def test_open_file(runner):274    @click.command()275    @click.argument("filename")276    def cli(filename):277        with click.open_file(filename) as f:278            click.echo(f.read())279280        click.echo("meep")281282    with runner.isolated_filesystem():283        with open("hello.txt", "w") as f:284            f.write("Cool stuff")285286        result = runner.invoke(cli, ["hello.txt"])287        assert result.exception is None288        assert result.output == "Cool stuff\nmeep\n"289290        result = runner.invoke(cli, ["-"], input="foobar")291        assert result.exception is None292        assert result.output == "foobar\nmeep\n"293294295def test_open_file_ignore_errors_stdin(runner):296    @click.command()297    @click.argument("filename")298    def cli(filename):299        with click.open_file(filename, errors="ignore") as f:300            click.echo(f.read())301302    result = runner.invoke(cli, ["-"], input=os.urandom(16))303    assert result.exception is None304305306def test_open_file_respects_ignore(runner):307    with runner.isolated_filesystem():308        with open("test.txt", "w") as f:309            f.write("Hello world!")310311        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:312            assert f.errors == "ignore"313314315def test_open_file_ignore_invalid_utf8(runner):316    with runner.isolated_filesystem():317        with open("test.txt", "wb") as f:318            f.write(b"\xe2\x28\xa1")319320        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:321            f.read()322323324def test_open_file_ignore_no_encoding(runner):325    with runner.isolated_filesystem():326        with open("test.bin", "wb") as f:327            f.write(os.urandom(16))328329        with click.open_file("test.bin", errors="ignore") as f:330            f.read()331332333@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")334@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])335def test_open_file_atomic_permissions_existing_file(runner, permissions):336    with runner.isolated_filesystem():337        with open("existing.txt", "w") as f:338            f.write("content")339        os.chmod("existing.txt", permissions)340341        @click.command()342        @click.argument("filename")343        def cli(filename):344            click.open_file(filename, "w", atomic=True).close()345346        result = runner.invoke(cli, ["existing.txt"])347        assert result.exception is None348        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions349350351@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")352def test_open_file_atomic_permissions_new_file(runner):353    with runner.isolated_filesystem():354355        @click.command()356        @click.argument("filename")357        def cli(filename):358            click.open_file(filename, "w", atomic=True).close()359360        # Create a test file to get the expected permissions for new files361        # according to the current umask.362        with open("test.txt", "w"):363            pass364        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)365366        result = runner.invoke(cli, ["new.txt"])367        assert result.exception is None368        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions369370371def test_iter_keepopenfile(tmpdir):372    expected = list(map(str, range(10)))373    p = tmpdir.mkdir("testdir").join("testfile")374    p.write("\n".join(expected))375    with p.open() as f:376        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):377            assert e_line == a_line.strip()378379380def test_iter_lazyfile(tmpdir):381    expected = list(map(str, range(10)))382    p = tmpdir.mkdir("testdir").join("testfile")383    p.write("\n".join(expected))384    with p.open() as f:385        with click.utils.LazyFile(f.name) as lf:386            for e_line, a_line in zip(expected, lf):387                assert e_line == a_line.strip()388389390class MockMain:391    __slots__ = "__package__"392393    def __init__(self, package_name):394        self.__package__ = package_name395396397@pytest.mark.parametrize(398    ("path", "main", "expected"),399    [400        ("example.py", None, "example.py"),401        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),402        ("example", None, "example"),403        (404            str(pathlib.Path("example/__main__.py")),405            MockMain(".example"),406            "python -m example",407        ),408        (409            str(pathlib.Path("example/cli.py")),410            MockMain(".example"),411            "python -m example.cli",412        ),413    ],414)415def test_detect_program_name(path, main, expected):416    assert click.utils._detect_program_name(path, _main=main) == expected