Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

498 lines · 15.5 KiB · Python

Last changed by

`format_filename` replaces invalid bytes (#2553)David Lordbefore adoptionaf1e8d4

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"101    assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"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"142143144def test_confirm_repeat(runner):145    cli = click.Command(146        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]147    )148    result = runner.invoke(cli, input="\ny\n")149    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"150151152@pytest.mark.skipif(WIN, reason="Different behavior on windows.")153def test_prompts_abort(monkeypatch, capsys):154    def f(_):155        raise KeyboardInterrupt()156157    monkeypatch.setattr("click.termui.hidden_prompt_func", f)158159    try:160        click.prompt("Password", hide_input=True)161    except click.Abort:162        click.echo("interrupted")163164    out, err = capsys.readouterr()165    assert out == "Password:\ninterrupted\n"166167168def _test_gen_func():169    yield "a"170    yield "b"171    yield "c"172    yield "abc"173174175@pytest.mark.skipif(WIN, reason="Different behavior on windows.")176@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])177@pytest.mark.parametrize(178    "test",179    [180        # We need lambda here, because pytest will181        # reuse the parameters, and then the generators182        # are already used and will not yield anymore183        ("just text\n", lambda: "just text"),184        ("iterable\n", lambda: ["itera", "ble"]),185        ("abcabc\n", lambda: _test_gen_func),186        ("abcabc\n", lambda: _test_gen_func()),187        ("012345\n", lambda: (c for c in range(6))),188    ],189)190def test_echo_via_pager(monkeypatch, capfd, cat, test):191    monkeypatch.setitem(os.environ, "PAGER", cat)192    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)193194    expected_output = test[0]195    test_input = test[1]()196197    click.echo_via_pager(test_input)198199    out, err = capfd.readouterr()200    assert out == expected_output201202203@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")204def test_echo_color_flag(monkeypatch, capfd):205    isatty = True206    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)207208    text = "foo"209    styled_text = click.style(text, fg="red")210    assert styled_text == "\x1b[31mfoo\x1b[0m"211212    click.echo(styled_text, color=False)213    out, err = capfd.readouterr()214    assert out == f"{text}\n"215216    click.echo(styled_text, color=True)217    out, err = capfd.readouterr()218    assert out == f"{styled_text}\n"219220    isatty = True221    click.echo(styled_text)222    out, err = capfd.readouterr()223    assert out == f"{styled_text}\n"224225    isatty = False226    click.echo(styled_text)227    out, err = capfd.readouterr()228    assert out == f"{text}\n"229230231def test_prompt_cast_default(capfd, monkeypatch):232    monkeypatch.setattr(sys, "stdin", StringIO("\n"))233    value = click.prompt("value", default="100", type=int)234    capfd.readouterr()235    assert type(value) is int236237238@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")239def test_echo_writing_to_standard_error(capfd, monkeypatch):240    def emulate_input(text):241        """Emulate keyboard input."""242        monkeypatch.setattr(sys, "stdin", StringIO(text))243244    click.echo("Echo to standard output")245    out, err = capfd.readouterr()246    assert out == "Echo to standard output\n"247    assert err == ""248249    click.echo("Echo to standard error", err=True)250    out, err = capfd.readouterr()251    assert out == ""252    assert err == "Echo to standard error\n"253254    emulate_input("asdlkj\n")255    click.prompt("Prompt to stdin")256    out, err = capfd.readouterr()257    assert out == "Prompt to stdin: "258    assert err == ""259260    emulate_input("asdlkj\n")261    click.prompt("Prompt to stderr", err=True)262    out, err = capfd.readouterr()263    assert out == " "264    assert err == "Prompt to stderr:"265266    emulate_input("y\n")267    click.confirm("Prompt to stdin")268    out, err = capfd.readouterr()269    assert out == "Prompt to stdin [y/N]: "270    assert err == ""271272    emulate_input("y\n")273    click.confirm("Prompt to stderr", err=True)274    out, err = capfd.readouterr()275    assert out == " "276    assert err == "Prompt to stderr [y/N]:"277278    monkeypatch.setattr(click.termui, "isatty", lambda x: True)279    monkeypatch.setattr(click.termui, "getchar", lambda: " ")280281    click.pause("Pause to stdout")282    out, err = capfd.readouterr()283    assert out == "Pause to stdout\n"284    assert err == ""285286    click.pause("Pause to stderr", err=True)287    out, err = capfd.readouterr()288    assert out == ""289    assert err == "Pause to stderr\n"290291292def test_echo_with_capsys(capsys):293    click.echo("Capture me.")294    out, err = capsys.readouterr()295    assert out == "Capture me.\n"296297298def test_open_file(runner):299    @click.command()300    @click.argument("filename")301    def cli(filename):302        with click.open_file(filename) as f:303            click.echo(f.read())304305        click.echo("meep")306307    with runner.isolated_filesystem():308        with open("hello.txt", "w") as f:309            f.write("Cool stuff")310311        result = runner.invoke(cli, ["hello.txt"])312        assert result.exception is None313        assert result.output == "Cool stuff\nmeep\n"314315        result = runner.invoke(cli, ["-"], input="foobar")316        assert result.exception is None317        assert result.output == "foobar\nmeep\n"318319320def test_open_file_pathlib_dash(runner):321    @click.command()322    @click.argument(323        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)324    )325    def cli(filename):326        click.echo(str(type(filename)))327328        with click.open_file(filename) as f:329            click.echo(f.read())330331        result = runner.invoke(cli, ["-"], input="value")332        assert result.exception is None333        assert result.output == "pathlib.Path\nvalue\n"334335336def test_open_file_ignore_errors_stdin(runner):337    @click.command()338    @click.argument("filename")339    def cli(filename):340        with click.open_file(filename, errors="ignore") as f:341            click.echo(f.read())342343    result = runner.invoke(cli, ["-"], input=os.urandom(16))344    assert result.exception is None345346347def test_open_file_respects_ignore(runner):348    with runner.isolated_filesystem():349        with open("test.txt", "w") as f:350            f.write("Hello world!")351352        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:353            assert f.errors == "ignore"354355356def test_open_file_ignore_invalid_utf8(runner):357    with runner.isolated_filesystem():358        with open("test.txt", "wb") as f:359            f.write(b"\xe2\x28\xa1")360361        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:362            f.read()363364365def test_open_file_ignore_no_encoding(runner):366    with runner.isolated_filesystem():367        with open("test.bin", "wb") as f:368            f.write(os.urandom(16))369370        with click.open_file("test.bin", errors="ignore") as f:371            f.read()372373374@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")375@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])376def test_open_file_atomic_permissions_existing_file(runner, permissions):377    with runner.isolated_filesystem():378        with open("existing.txt", "w") as f:379            f.write("content")380        os.chmod("existing.txt", permissions)381382        @click.command()383        @click.argument("filename")384        def cli(filename):385            click.open_file(filename, "w", atomic=True).close()386387        result = runner.invoke(cli, ["existing.txt"])388        assert result.exception is None389        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions390391392@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")393def test_open_file_atomic_permissions_new_file(runner):394    with runner.isolated_filesystem():395396        @click.command()397        @click.argument("filename")398        def cli(filename):399            click.open_file(filename, "w", atomic=True).close()400401        # Create a test file to get the expected permissions for new files402        # according to the current umask.403        with open("test.txt", "w"):404            pass405        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)406407        result = runner.invoke(cli, ["new.txt"])408        assert result.exception is None409        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions410411412def test_iter_keepopenfile(tmpdir):413    expected = list(map(str, range(10)))414    p = tmpdir.mkdir("testdir").join("testfile")415    p.write("\n".join(expected))416    with p.open() as f:417        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):418            assert e_line == a_line.strip()419420421def test_iter_lazyfile(tmpdir):422    expected = list(map(str, range(10)))423    p = tmpdir.mkdir("testdir").join("testfile")424    p.write("\n".join(expected))425    with p.open() as f:426        with click.utils.LazyFile(f.name) as lf:427            for e_line, a_line in zip(expected, lf):428                assert e_line == a_line.strip()429430431class MockMain:432    __slots__ = "__package__"433434    def __init__(self, package_name):435        self.__package__ = package_name436437438@pytest.mark.parametrize(439    ("path", "main", "expected"),440    [441        ("example.py", None, "example.py"),442        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),443        ("example", None, "example"),444        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),445        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),446        (str(pathlib.Path("./example")), "", "example"),447    ],448)449def test_detect_program_name(path, main, expected):450    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected451452453def test_expand_args(monkeypatch):454    user = os.path.expanduser("~")455    assert user in click.utils._expand_args(["~"])456    monkeypatch.setenv("CLICK_TEST", "hello")457    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])458    assert "setup.cfg" in click.utils._expand_args(["*.cfg"])459    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])460    assert "*.not-found" in click.utils._expand_args(["*.not-found"])461    # a bad glob pattern, such as a pytest identifier, should return itself462    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"463464465@pytest.mark.parametrize(466    ("value", "max_length", "expect"),467    [468        pytest.param("", 10, "", id="empty"),469        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),470        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),471        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),472        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),473        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),474        pytest.param(475            "token in ~/.netrc ciao ciao",476            20,477            "token in ~/.netrc...",478            id="ignore dot in word",479        ),480    ],481)482@pytest.mark.parametrize(483    "alter",484    [485        pytest.param(None, id=""),486        pytest.param(487            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"488        ),489    ],490)491def test_make_default_short_help(value, max_length, alter, expect):492    assert len(expect) <= max_length493494    if alter:495        value = alter(value)496497    out = click.utils.make_default_short_help(value, max_length)498    assert out == expect