Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

490 lines · 15.0 KiB · Python

Last changed by

Merge pull request #2058 from jap/improve-copy-pasteDavid Lordbefore adoption6bb518f

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        ({"bold": True}, "\x1b[1mx y\x1b[0m"),68        ({"dim": True}, "\x1b[2mx y\x1b[0m"),69        ({"underline": True}, "\x1b[4mx y\x1b[0m"),70        ({"overline": True}, "\x1b[53mx y\x1b[0m"),71        ({"italic": True}, "\x1b[3mx y\x1b[0m"),72        ({"blink": True}, "\x1b[5mx y\x1b[0m"),73        ({"reverse": True}, "\x1b[7mx y\x1b[0m"),74        ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),75        ({"bold": False}, "\x1b[22mx y\x1b[0m"),76        ({"dim": False}, "\x1b[22mx y\x1b[0m"),77        ({"underline": False}, "\x1b[24mx y\x1b[0m"),78        ({"overline": False}, "\x1b[55mx y\x1b[0m"),79        ({"italic": False}, "\x1b[23mx y\x1b[0m"),80        ({"blink": False}, "\x1b[25mx y\x1b[0m"),81        ({"reverse": False}, "\x1b[27mx y\x1b[0m"),82        ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),83        ({"fg": "black", "reset": False}, "\x1b[30mx y"),84    ],85)86def test_styling(styles, ref):87    assert click.style("x y", **styles) == ref88    assert click.unstyle(ref) == "x y"899091@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])92def test_unstyle_other_ansi(text, expect):93    assert click.unstyle(text) == expect949596def test_filename_formatting():97    assert click.format_filename(b"foo.txt") == "foo.txt"98    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"99    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"100    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"101102    # filesystem encoding on windows permits this.103    if not WIN:104        assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\udcff.txt"105106107def test_prompts(runner):108    @click.command()109    def test():110        if click.confirm("Foo"):111            click.echo("yes!")112        else:113            click.echo("no :(")114115    result = runner.invoke(test, input="y\n")116    assert not result.exception117    assert result.output == "Foo [y/N]: y\nyes!\n"118119    result = runner.invoke(test, input="\n")120    assert not result.exception121    assert result.output == "Foo [y/N]: \nno :(\n"122123    result = runner.invoke(test, input="n\n")124    assert not result.exception125    assert result.output == "Foo [y/N]: n\nno :(\n"126127    @click.command()128    def test_no():129        if click.confirm("Foo", default=True):130            click.echo("yes!")131        else:132            click.echo("no :(")133134    result = runner.invoke(test_no, input="y\n")135    assert not result.exception136    assert result.output == "Foo [Y/n]: y\nyes!\n"137138    result = runner.invoke(test_no, input="\n")139    assert not result.exception140    assert result.output == "Foo [Y/n]: \nyes!\n"141142    result = runner.invoke(test_no, input="n\n")143    assert not result.exception144    assert result.output == "Foo [Y/n]: n\nno :(\n"145146147def test_confirm_repeat(runner):148    cli = click.Command(149        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]150    )151    result = runner.invoke(cli, input="\ny\n")152    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"153154155@pytest.mark.skipif(WIN, reason="Different behavior on windows.")156def test_prompts_abort(monkeypatch, capsys):157    def f(_):158        raise KeyboardInterrupt()159160    monkeypatch.setattr("click.termui.hidden_prompt_func", f)161162    try:163        click.prompt("Password", hide_input=True)164    except click.Abort:165        click.echo("interrupted")166167    out, err = capsys.readouterr()168    assert out == "Password:\ninterrupted\n"169170171def _test_gen_func():172    yield "a"173    yield "b"174    yield "c"175    yield "abc"176177178@pytest.mark.skipif(WIN, reason="Different behavior on windows.")179@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])180@pytest.mark.parametrize(181    "test",182    [183        # We need lambda here, because pytest will184        # reuse the parameters, and then the generators185        # are already used and will not yield anymore186        ("just text\n", lambda: "just text"),187        ("iterable\n", lambda: ["itera", "ble"]),188        ("abcabc\n", lambda: _test_gen_func),189        ("abcabc\n", lambda: _test_gen_func()),190        ("012345\n", lambda: (c for c in range(6))),191    ],192)193def test_echo_via_pager(monkeypatch, capfd, cat, test):194    monkeypatch.setitem(os.environ, "PAGER", cat)195    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)196197    expected_output = test[0]198    test_input = test[1]()199200    click.echo_via_pager(test_input)201202    out, err = capfd.readouterr()203    assert out == expected_output204205206@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")207def test_echo_color_flag(monkeypatch, capfd):208    isatty = True209    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)210211    text = "foo"212    styled_text = click.style(text, fg="red")213    assert styled_text == "\x1b[31mfoo\x1b[0m"214215    click.echo(styled_text, color=False)216    out, err = capfd.readouterr()217    assert out == f"{text}\n"218219    click.echo(styled_text, color=True)220    out, err = capfd.readouterr()221    assert out == f"{styled_text}\n"222223    isatty = True224    click.echo(styled_text)225    out, err = capfd.readouterr()226    assert out == f"{styled_text}\n"227228    isatty = False229    click.echo(styled_text)230    out, err = capfd.readouterr()231    assert out == f"{text}\n"232233234def test_prompt_cast_default(capfd, monkeypatch):235    monkeypatch.setattr(sys, "stdin", StringIO("\n"))236    value = click.prompt("value", default="100", type=int)237    capfd.readouterr()238    assert type(value) is int239240241@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")242def test_echo_writing_to_standard_error(capfd, monkeypatch):243    def emulate_input(text):244        """Emulate keyboard input."""245        monkeypatch.setattr(sys, "stdin", StringIO(text))246247    click.echo("Echo to standard output")248    out, err = capfd.readouterr()249    assert out == "Echo to standard output\n"250    assert err == ""251252    click.echo("Echo to standard error", err=True)253    out, err = capfd.readouterr()254    assert out == ""255    assert err == "Echo to standard error\n"256257    emulate_input("asdlkj\n")258    click.prompt("Prompt to stdin")259    out, err = capfd.readouterr()260    assert out == "Prompt to stdin: "261    assert err == ""262263    emulate_input("asdlkj\n")264    click.prompt("Prompt to stderr", err=True)265    out, err = capfd.readouterr()266    assert out == " "267    assert err == "Prompt to stderr:"268269    emulate_input("y\n")270    click.confirm("Prompt to stdin")271    out, err = capfd.readouterr()272    assert out == "Prompt to stdin [y/N]: "273    assert err == ""274275    emulate_input("y\n")276    click.confirm("Prompt to stderr", err=True)277    out, err = capfd.readouterr()278    assert out == ""279    assert err == "Prompt to stderr [y/N]: "280281    monkeypatch.setattr(click.termui, "isatty", lambda x: True)282    monkeypatch.setattr(click.termui, "getchar", lambda: " ")283284    click.pause("Pause to stdout")285    out, err = capfd.readouterr()286    assert out == "Pause to stdout\n"287    assert err == ""288289    click.pause("Pause to stderr", err=True)290    out, err = capfd.readouterr()291    assert out == ""292    assert err == "Pause to stderr\n"293294295def test_echo_with_capsys(capsys):296    click.echo("Capture me.")297    out, err = capsys.readouterr()298    assert out == "Capture me.\n"299300301def test_open_file(runner):302    @click.command()303    @click.argument("filename")304    def cli(filename):305        with click.open_file(filename) as f:306            click.echo(f.read())307308        click.echo("meep")309310    with runner.isolated_filesystem():311        with open("hello.txt", "w") as f:312            f.write("Cool stuff")313314        result = runner.invoke(cli, ["hello.txt"])315        assert result.exception is None316        assert result.output == "Cool stuff\nmeep\n"317318        result = runner.invoke(cli, ["-"], input="foobar")319        assert result.exception is None320        assert result.output == "foobar\nmeep\n"321322323def test_open_file_ignore_errors_stdin(runner):324    @click.command()325    @click.argument("filename")326    def cli(filename):327        with click.open_file(filename, errors="ignore") as f:328            click.echo(f.read())329330    result = runner.invoke(cli, ["-"], input=os.urandom(16))331    assert result.exception is None332333334def test_open_file_respects_ignore(runner):335    with runner.isolated_filesystem():336        with open("test.txt", "w") as f:337            f.write("Hello world!")338339        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:340            assert f.errors == "ignore"341342343def test_open_file_ignore_invalid_utf8(runner):344    with runner.isolated_filesystem():345        with open("test.txt", "wb") as f:346            f.write(b"\xe2\x28\xa1")347348        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:349            f.read()350351352def test_open_file_ignore_no_encoding(runner):353    with runner.isolated_filesystem():354        with open("test.bin", "wb") as f:355            f.write(os.urandom(16))356357        with click.open_file("test.bin", errors="ignore") as f:358            f.read()359360361@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")362@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])363def test_open_file_atomic_permissions_existing_file(runner, permissions):364    with runner.isolated_filesystem():365        with open("existing.txt", "w") as f:366            f.write("content")367        os.chmod("existing.txt", permissions)368369        @click.command()370        @click.argument("filename")371        def cli(filename):372            click.open_file(filename, "w", atomic=True).close()373374        result = runner.invoke(cli, ["existing.txt"])375        assert result.exception is None376        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions377378379@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")380def test_open_file_atomic_permissions_new_file(runner):381    with runner.isolated_filesystem():382383        @click.command()384        @click.argument("filename")385        def cli(filename):386            click.open_file(filename, "w", atomic=True).close()387388        # Create a test file to get the expected permissions for new files389        # according to the current umask.390        with open("test.txt", "w"):391            pass392        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)393394        result = runner.invoke(cli, ["new.txt"])395        assert result.exception is None396        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions397398399def test_iter_keepopenfile(tmpdir):400    expected = list(map(str, range(10)))401    p = tmpdir.mkdir("testdir").join("testfile")402    p.write("\n".join(expected))403    with p.open() as f:404        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):405            assert e_line == a_line.strip()406407408def test_iter_lazyfile(tmpdir):409    expected = list(map(str, range(10)))410    p = tmpdir.mkdir("testdir").join("testfile")411    p.write("\n".join(expected))412    with p.open() as f:413        with click.utils.LazyFile(f.name) as lf:414            for e_line, a_line in zip(expected, lf):415                assert e_line == a_line.strip()416417418class MockMain:419    __slots__ = "__package__"420421    def __init__(self, package_name):422        self.__package__ = package_name423424425@pytest.mark.parametrize(426    ("path", "main", "expected"),427    [428        ("example.py", None, "example.py"),429        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),430        ("example", None, "example"),431        (432            str(pathlib.Path("example/__main__.py")),433            MockMain(".example"),434            "python -m example",435        ),436        (437            str(pathlib.Path("example/cli.py")),438            MockMain(".example"),439            "python -m example.cli",440        ),441    ],442)443def test_detect_program_name(path, main, expected):444    assert click.utils._detect_program_name(path, _main=main) == expected445446447def test_expand_args(monkeypatch):448    user = os.path.expanduser("~")449    assert user in click.utils._expand_args(["~"])450    monkeypatch.setenv("CLICK_TEST", "hello")451    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])452    assert "setup.cfg" in click.utils._expand_args(["*.cfg"])453    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])454    assert "*.not-found" in click.utils._expand_args(["*.not-found"])455456457@pytest.mark.parametrize(458    ("value", "max_length", "expect"),459    [460        pytest.param("", 10, "", id="empty"),461        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),462        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),463        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),464        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),465        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),466        pytest.param(467            "token in ~/.netrc ciao ciao",468            20,469            "token in ~/.netrc...",470            id="ignore dot in word",471        ),472    ],473)474@pytest.mark.parametrize(475    "alter",476    [477        pytest.param(None, id=""),478        pytest.param(479            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"480        ),481    ],482)483def test_make_default_short_help(value, max_length, alter, expect):484    assert len(expect) <= max_length485486    if alter:487        value = alter(value)488489    out = click.utils.make_default_short_help(value, max_length)490    assert out == expect