Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

500 lines · 15.5 KiB · Python

Last changed by

Merge pull request #2215 from adriangb/fix-anyioDavid Lordbefore adoptionbf9da48

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_pathlib_dash(runner):324    @click.command()325    @click.argument(326        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)327    )328    def cli(filename):329        click.echo(str(type(filename)))330331        with click.open_file(filename) as f:332            click.echo(f.read())333334        result = runner.invoke(cli, ["-"], input="value")335        assert result.exception is None336        assert result.output == "pathlib.Path\nvalue\n"337338339def test_open_file_ignore_errors_stdin(runner):340    @click.command()341    @click.argument("filename")342    def cli(filename):343        with click.open_file(filename, errors="ignore") as f:344            click.echo(f.read())345346    result = runner.invoke(cli, ["-"], input=os.urandom(16))347    assert result.exception is None348349350def test_open_file_respects_ignore(runner):351    with runner.isolated_filesystem():352        with open("test.txt", "w") as f:353            f.write("Hello world!")354355        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:356            assert f.errors == "ignore"357358359def test_open_file_ignore_invalid_utf8(runner):360    with runner.isolated_filesystem():361        with open("test.txt", "wb") as f:362            f.write(b"\xe2\x28\xa1")363364        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:365            f.read()366367368def test_open_file_ignore_no_encoding(runner):369    with runner.isolated_filesystem():370        with open("test.bin", "wb") as f:371            f.write(os.urandom(16))372373        with click.open_file("test.bin", errors="ignore") as f:374            f.read()375376377@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")378@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])379def test_open_file_atomic_permissions_existing_file(runner, permissions):380    with runner.isolated_filesystem():381        with open("existing.txt", "w") as f:382            f.write("content")383        os.chmod("existing.txt", permissions)384385        @click.command()386        @click.argument("filename")387        def cli(filename):388            click.open_file(filename, "w", atomic=True).close()389390        result = runner.invoke(cli, ["existing.txt"])391        assert result.exception is None392        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions393394395@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")396def test_open_file_atomic_permissions_new_file(runner):397    with runner.isolated_filesystem():398399        @click.command()400        @click.argument("filename")401        def cli(filename):402            click.open_file(filename, "w", atomic=True).close()403404        # Create a test file to get the expected permissions for new files405        # according to the current umask.406        with open("test.txt", "w"):407            pass408        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)409410        result = runner.invoke(cli, ["new.txt"])411        assert result.exception is None412        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions413414415def test_iter_keepopenfile(tmpdir):416    expected = list(map(str, range(10)))417    p = tmpdir.mkdir("testdir").join("testfile")418    p.write("\n".join(expected))419    with p.open() as f:420        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):421            assert e_line == a_line.strip()422423424def test_iter_lazyfile(tmpdir):425    expected = list(map(str, range(10)))426    p = tmpdir.mkdir("testdir").join("testfile")427    p.write("\n".join(expected))428    with p.open() as f:429        with click.utils.LazyFile(f.name) as lf:430            for e_line, a_line in zip(expected, lf):431                assert e_line == a_line.strip()432433434class MockMain:435    __slots__ = "__package__"436437    def __init__(self, package_name):438        self.__package__ = package_name439440441@pytest.mark.parametrize(442    ("path", "main", "expected"),443    [444        ("example.py", None, "example.py"),445        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),446        ("example", None, "example"),447        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),448        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),449    ],450)451def test_detect_program_name(path, main, expected):452    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected453454455def test_expand_args(monkeypatch):456    user = os.path.expanduser("~")457    assert user in click.utils._expand_args(["~"])458    monkeypatch.setenv("CLICK_TEST", "hello")459    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])460    assert "setup.cfg" in click.utils._expand_args(["*.cfg"])461    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])462    assert "*.not-found" in click.utils._expand_args(["*.not-found"])463    # a bad glob pattern, such as a pytest identifier, should return itself464    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"465466467@pytest.mark.parametrize(468    ("value", "max_length", "expect"),469    [470        pytest.param("", 10, "", id="empty"),471        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),472        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),473        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),474        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),475        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),476        pytest.param(477            "token in ~/.netrc ciao ciao",478            20,479            "token in ~/.netrc...",480            id="ignore dot in word",481        ),482    ],483)484@pytest.mark.parametrize(485    "alter",486    [487        pytest.param(None, id=""),488        pytest.param(489            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"490        ),491    ],492)493def test_make_default_short_help(value, max_length, alter, expect):494    assert len(expect) <= max_length495496    if alter:497        value = alter(value)498499    out = click.utils.make_default_short_help(value, max_length)500    assert out == expect