Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

482 lines · 14.6 KiB · Python

Last changed by

Merge pull request #1850 from janLuke/fix/make-default-short-helpDavid Lordbefore adoption82a83fd

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[55mx y\x1b[0m"),71        ({"italic": True}, "\x1b[23mx 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        ({"fg": "black", "reset": False}, "\x1b[30mx y"),76    ],77)78def test_styling(styles, ref):79    assert click.style("x y", **styles) == ref80    assert click.unstyle(ref) == "x y"818283@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])84def test_unstyle_other_ansi(text, expect):85    assert click.unstyle(text) == expect868788def test_filename_formatting():89    assert click.format_filename(b"foo.txt") == "foo.txt"90    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"91    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"92    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"9394    # filesystem encoding on windows permits this.95    if not WIN:96        assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\udcff.txt"979899def test_prompts(runner):100    @click.command()101    def test():102        if click.confirm("Foo"):103            click.echo("yes!")104        else:105            click.echo("no :(")106107    result = runner.invoke(test, input="y\n")108    assert not result.exception109    assert result.output == "Foo [y/N]: y\nyes!\n"110111    result = runner.invoke(test, input="\n")112    assert not result.exception113    assert result.output == "Foo [y/N]: \nno :(\n"114115    result = runner.invoke(test, input="n\n")116    assert not result.exception117    assert result.output == "Foo [y/N]: n\nno :(\n"118119    @click.command()120    def test_no():121        if click.confirm("Foo", default=True):122            click.echo("yes!")123        else:124            click.echo("no :(")125126    result = runner.invoke(test_no, input="y\n")127    assert not result.exception128    assert result.output == "Foo [Y/n]: y\nyes!\n"129130    result = runner.invoke(test_no, input="\n")131    assert not result.exception132    assert result.output == "Foo [Y/n]: \nyes!\n"133134    result = runner.invoke(test_no, input="n\n")135    assert not result.exception136    assert result.output == "Foo [Y/n]: n\nno :(\n"137138139def test_confirm_repeat(runner):140    cli = click.Command(141        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]142    )143    result = runner.invoke(cli, input="\ny\n")144    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"145146147@pytest.mark.skipif(WIN, reason="Different behavior on windows.")148def test_prompts_abort(monkeypatch, capsys):149    def f(_):150        raise KeyboardInterrupt()151152    monkeypatch.setattr("click.termui.hidden_prompt_func", f)153154    try:155        click.prompt("Password", hide_input=True)156    except click.Abort:157        click.echo("interrupted")158159    out, err = capsys.readouterr()160    assert out == "Password:\ninterrupted\n"161162163def _test_gen_func():164    yield "a"165    yield "b"166    yield "c"167    yield "abc"168169170@pytest.mark.skipif(WIN, reason="Different behavior on windows.")171@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])172@pytest.mark.parametrize(173    "test",174    [175        # We need lambda here, because pytest will176        # reuse the parameters, and then the generators177        # are already used and will not yield anymore178        ("just text\n", lambda: "just text"),179        ("iterable\n", lambda: ["itera", "ble"]),180        ("abcabc\n", lambda: _test_gen_func),181        ("abcabc\n", lambda: _test_gen_func()),182        ("012345\n", lambda: (c for c in range(6))),183    ],184)185def test_echo_via_pager(monkeypatch, capfd, cat, test):186    monkeypatch.setitem(os.environ, "PAGER", cat)187    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)188189    expected_output = test[0]190    test_input = test[1]()191192    click.echo_via_pager(test_input)193194    out, err = capfd.readouterr()195    assert out == expected_output196197198@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")199def test_echo_color_flag(monkeypatch, capfd):200    isatty = True201    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)202203    text = "foo"204    styled_text = click.style(text, fg="red")205    assert styled_text == "\x1b[31mfoo\x1b[0m"206207    click.echo(styled_text, color=False)208    out, err = capfd.readouterr()209    assert out == f"{text}\n"210211    click.echo(styled_text, color=True)212    out, err = capfd.readouterr()213    assert out == f"{styled_text}\n"214215    isatty = True216    click.echo(styled_text)217    out, err = capfd.readouterr()218    assert out == f"{styled_text}\n"219220    isatty = False221    click.echo(styled_text)222    out, err = capfd.readouterr()223    assert out == f"{text}\n"224225226def test_prompt_cast_default(capfd, monkeypatch):227    monkeypatch.setattr(sys, "stdin", StringIO("\n"))228    value = click.prompt("value", default="100", type=int)229    capfd.readouterr()230    assert type(value) is int231232233@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")234def test_echo_writing_to_standard_error(capfd, monkeypatch):235    def emulate_input(text):236        """Emulate keyboard input."""237        monkeypatch.setattr(sys, "stdin", StringIO(text))238239    click.echo("Echo to standard output")240    out, err = capfd.readouterr()241    assert out == "Echo to standard output\n"242    assert err == ""243244    click.echo("Echo to standard error", err=True)245    out, err = capfd.readouterr()246    assert out == ""247    assert err == "Echo to standard error\n"248249    emulate_input("asdlkj\n")250    click.prompt("Prompt to stdin")251    out, err = capfd.readouterr()252    assert out == "Prompt to stdin: "253    assert err == ""254255    emulate_input("asdlkj\n")256    click.prompt("Prompt to stderr", err=True)257    out, err = capfd.readouterr()258    assert out == " "259    assert err == "Prompt to stderr:"260261    emulate_input("y\n")262    click.confirm("Prompt to stdin")263    out, err = capfd.readouterr()264    assert out == "Prompt to stdin [y/N]: "265    assert err == ""266267    emulate_input("y\n")268    click.confirm("Prompt to stderr", err=True)269    out, err = capfd.readouterr()270    assert out == ""271    assert err == "Prompt to stderr [y/N]: "272273    monkeypatch.setattr(click.termui, "isatty", lambda x: True)274    monkeypatch.setattr(click.termui, "getchar", lambda: " ")275276    click.pause("Pause to stdout")277    out, err = capfd.readouterr()278    assert out == "Pause to stdout\n"279    assert err == ""280281    click.pause("Pause to stderr", err=True)282    out, err = capfd.readouterr()283    assert out == ""284    assert err == "Pause to stderr\n"285286287def test_echo_with_capsys(capsys):288    click.echo("Capture me.")289    out, err = capsys.readouterr()290    assert out == "Capture me.\n"291292293def test_open_file(runner):294    @click.command()295    @click.argument("filename")296    def cli(filename):297        with click.open_file(filename) as f:298            click.echo(f.read())299300        click.echo("meep")301302    with runner.isolated_filesystem():303        with open("hello.txt", "w") as f:304            f.write("Cool stuff")305306        result = runner.invoke(cli, ["hello.txt"])307        assert result.exception is None308        assert result.output == "Cool stuff\nmeep\n"309310        result = runner.invoke(cli, ["-"], input="foobar")311        assert result.exception is None312        assert result.output == "foobar\nmeep\n"313314315def test_open_file_ignore_errors_stdin(runner):316    @click.command()317    @click.argument("filename")318    def cli(filename):319        with click.open_file(filename, errors="ignore") as f:320            click.echo(f.read())321322    result = runner.invoke(cli, ["-"], input=os.urandom(16))323    assert result.exception is None324325326def test_open_file_respects_ignore(runner):327    with runner.isolated_filesystem():328        with open("test.txt", "w") as f:329            f.write("Hello world!")330331        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:332            assert f.errors == "ignore"333334335def test_open_file_ignore_invalid_utf8(runner):336    with runner.isolated_filesystem():337        with open("test.txt", "wb") as f:338            f.write(b"\xe2\x28\xa1")339340        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:341            f.read()342343344def test_open_file_ignore_no_encoding(runner):345    with runner.isolated_filesystem():346        with open("test.bin", "wb") as f:347            f.write(os.urandom(16))348349        with click.open_file("test.bin", errors="ignore") as f:350            f.read()351352353@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")354@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])355def test_open_file_atomic_permissions_existing_file(runner, permissions):356    with runner.isolated_filesystem():357        with open("existing.txt", "w") as f:358            f.write("content")359        os.chmod("existing.txt", permissions)360361        @click.command()362        @click.argument("filename")363        def cli(filename):364            click.open_file(filename, "w", atomic=True).close()365366        result = runner.invoke(cli, ["existing.txt"])367        assert result.exception is None368        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions369370371@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")372def test_open_file_atomic_permissions_new_file(runner):373    with runner.isolated_filesystem():374375        @click.command()376        @click.argument("filename")377        def cli(filename):378            click.open_file(filename, "w", atomic=True).close()379380        # Create a test file to get the expected permissions for new files381        # according to the current umask.382        with open("test.txt", "w"):383            pass384        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)385386        result = runner.invoke(cli, ["new.txt"])387        assert result.exception is None388        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions389390391def test_iter_keepopenfile(tmpdir):392    expected = list(map(str, range(10)))393    p = tmpdir.mkdir("testdir").join("testfile")394    p.write("\n".join(expected))395    with p.open() as f:396        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):397            assert e_line == a_line.strip()398399400def test_iter_lazyfile(tmpdir):401    expected = list(map(str, range(10)))402    p = tmpdir.mkdir("testdir").join("testfile")403    p.write("\n".join(expected))404    with p.open() as f:405        with click.utils.LazyFile(f.name) as lf:406            for e_line, a_line in zip(expected, lf):407                assert e_line == a_line.strip()408409410class MockMain:411    __slots__ = "__package__"412413    def __init__(self, package_name):414        self.__package__ = package_name415416417@pytest.mark.parametrize(418    ("path", "main", "expected"),419    [420        ("example.py", None, "example.py"),421        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),422        ("example", None, "example"),423        (424            str(pathlib.Path("example/__main__.py")),425            MockMain(".example"),426            "python -m example",427        ),428        (429            str(pathlib.Path("example/cli.py")),430            MockMain(".example"),431            "python -m example.cli",432        ),433    ],434)435def test_detect_program_name(path, main, expected):436    assert click.utils._detect_program_name(path, _main=main) == expected437438439def test_expand_args(monkeypatch):440    user = os.path.expanduser("~")441    assert user in click.utils._expand_args(["~"])442    monkeypatch.setenv("CLICK_TEST", "hello")443    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])444    assert "setup.cfg" in click.utils._expand_args(["*.cfg"])445    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])446    assert "*.not-found" in click.utils._expand_args(["*.not-found"])447448449@pytest.mark.parametrize(450    ("value", "max_length", "expect"),451    [452        pytest.param("", 10, "", id="empty"),453        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),454        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),455        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),456        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),457        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),458        pytest.param(459            "token in ~/.netrc ciao ciao",460            20,461            "token in ~/.netrc...",462            id="ignore dot in word",463        ),464    ],465)466@pytest.mark.parametrize(467    "alter",468    [469        pytest.param(None, id=""),470        pytest.param(471            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"472        ),473    ],474)475def test_make_default_short_help(value, max_length, alter, expect):476    assert len(expect) <= max_length477478    if alter:479        value = alter(value)480481    out = click.utils.make_default_short_help(value, max_length)482    assert out == expect