Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

510 lines · 16.0 KiB · Python

Last changed by

Use subprocess instead of os.system (#1477)John T. Wodder IIbefore adoption299efb8

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    f = StringIO()40    click.echo("hello", file=f)41    assert f.getvalue() == "hello\n"424344def test_echo_no_streams(monkeypatch, runner):45    """echo should not fail when stdout and stderr are None with pythonw on Windows."""46    with runner.isolation():47        sys.stdout = None48        sys.stderr = None49        click.echo("test")50        click.echo("test", err=True)515253@pytest.mark.parametrize(54    ("styles", "ref"),55    [56        ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),57        ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),58        ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),59        ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),60        ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),61        ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),62        ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),63        ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),64        ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),65        ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),66        ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),67        ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),68        ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),69        ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),70        ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),71        ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),72        ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),73        ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),74        ({"bold": True}, "\x1b[1mx y\x1b[0m"),75        ({"dim": True}, "\x1b[2mx y\x1b[0m"),76        ({"underline": True}, "\x1b[4mx y\x1b[0m"),77        ({"overline": True}, "\x1b[53mx y\x1b[0m"),78        ({"italic": True}, "\x1b[3mx y\x1b[0m"),79        ({"blink": True}, "\x1b[5mx y\x1b[0m"),80        ({"reverse": True}, "\x1b[7mx y\x1b[0m"),81        ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),82        ({"bold": False}, "\x1b[22mx y\x1b[0m"),83        ({"dim": False}, "\x1b[22mx y\x1b[0m"),84        ({"underline": False}, "\x1b[24mx y\x1b[0m"),85        ({"overline": False}, "\x1b[55mx y\x1b[0m"),86        ({"italic": False}, "\x1b[23mx y\x1b[0m"),87        ({"blink": False}, "\x1b[25mx y\x1b[0m"),88        ({"reverse": False}, "\x1b[27mx y\x1b[0m"),89        ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),90        ({"fg": "black", "reset": False}, "\x1b[30mx y"),91    ],92)93def test_styling(styles, ref):94    assert click.style("x y", **styles) == ref95    assert click.unstyle(ref) == "x y"969798@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])99def test_unstyle_other_ansi(text, expect):100    assert click.unstyle(text) == expect101102103def test_filename_formatting():104    assert click.format_filename(b"foo.txt") == "foo.txt"105    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"106    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"107    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"108    assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"109110111def test_prompts(runner):112    @click.command()113    def test():114        if click.confirm("Foo"):115            click.echo("yes!")116        else:117            click.echo("no :(")118119    result = runner.invoke(test, input="y\n")120    assert not result.exception121    assert result.output == "Foo [y/N]: y\nyes!\n"122123    result = runner.invoke(test, input="\n")124    assert not result.exception125    assert result.output == "Foo [y/N]: \nno :(\n"126127    result = runner.invoke(test, input="n\n")128    assert not result.exception129    assert result.output == "Foo [y/N]: n\nno :(\n"130131    @click.command()132    def test_no():133        if click.confirm("Foo", default=True):134            click.echo("yes!")135        else:136            click.echo("no :(")137138    result = runner.invoke(test_no, input="y\n")139    assert not result.exception140    assert result.output == "Foo [Y/n]: y\nyes!\n"141142    result = runner.invoke(test_no, input="\n")143    assert not result.exception144    assert result.output == "Foo [Y/n]: \nyes!\n"145146    result = runner.invoke(test_no, input="n\n")147    assert not result.exception148    assert result.output == "Foo [Y/n]: n\nno :(\n"149150151def test_confirm_repeat(runner):152    cli = click.Command(153        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]154    )155    result = runner.invoke(cli, input="\ny\n")156    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"157158159@pytest.mark.skipif(WIN, reason="Different behavior on windows.")160def test_prompts_abort(monkeypatch, capsys):161    def f(_):162        raise KeyboardInterrupt()163164    monkeypatch.setattr("click.termui.hidden_prompt_func", f)165166    try:167        click.prompt("Password", hide_input=True)168    except click.Abort:169        click.echo("interrupted")170171    out, err = capsys.readouterr()172    assert out == "Password:\ninterrupted\n"173174175def _test_gen_func():176    yield "a"177    yield "b"178    yield "c"179    yield "abc"180181182@pytest.mark.parametrize("cat", ["cat", "cat ", "cat "])183@pytest.mark.parametrize(184    "test",185    [186        # We need lambda here, because pytest will187        # reuse the parameters, and then the generators188        # are already used and will not yield anymore189        ("just text\n", lambda: "just text"),190        ("iterable\n", lambda: ["itera", "ble"]),191        ("abcabc\n", lambda: _test_gen_func),192        ("abcabc\n", lambda: _test_gen_func()),193        ("012345\n", lambda: (c for c in range(6))),194    ],195)196def test_echo_via_pager(monkeypatch, capfd, cat, test):197    monkeypatch.setitem(os.environ, "PAGER", cat)198    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)199200    expected_output = test[0]201    test_input = test[1]()202203    click.echo_via_pager(test_input)204205    out, err = capfd.readouterr()206    assert out == expected_output207208209def test_echo_color_flag(monkeypatch, capfd):210    isatty = True211    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)212213    text = "foo"214    styled_text = click.style(text, fg="red")215    assert styled_text == "\x1b[31mfoo\x1b[0m"216217    click.echo(styled_text, color=False)218    out, err = capfd.readouterr()219    assert out == f"{text}\n"220221    click.echo(styled_text, color=True)222    out, err = capfd.readouterr()223    assert out == f"{styled_text}\n"224225    isatty = True226    click.echo(styled_text)227    out, err = capfd.readouterr()228    assert out == f"{styled_text}\n"229230    isatty = False231    # Faking isatty() is not enough on Windows;232    # the implementation caches the colorama wrapped stream233    # so we have to use a new stream for each test234    stream = StringIO()235    click.echo(styled_text, file=stream)236    assert stream.getvalue() == f"{text}\n"237238    stream = StringIO()239    click.echo(styled_text, file=stream, color=True)240    assert stream.getvalue() == f"{styled_text}\n"241242243def test_prompt_cast_default(capfd, monkeypatch):244    monkeypatch.setattr(sys, "stdin", StringIO("\n"))245    value = click.prompt("value", default="100", type=int)246    capfd.readouterr()247    assert type(value) is int  # noqa E721248249250@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")251def test_echo_writing_to_standard_error(capfd, monkeypatch):252    def emulate_input(text):253        """Emulate keyboard input."""254        monkeypatch.setattr(sys, "stdin", StringIO(text))255256    click.echo("Echo to standard output")257    out, err = capfd.readouterr()258    assert out == "Echo to standard output\n"259    assert err == ""260261    click.echo("Echo to standard error", err=True)262    out, err = capfd.readouterr()263    assert out == ""264    assert err == "Echo to standard error\n"265266    emulate_input("asdlkj\n")267    click.prompt("Prompt to stdin")268    out, err = capfd.readouterr()269    assert out == "Prompt to stdin: "270    assert err == ""271272    emulate_input("asdlkj\n")273    click.prompt("Prompt to stderr", err=True)274    out, err = capfd.readouterr()275    assert out == " "276    assert err == "Prompt to stderr:"277278    emulate_input("y\n")279    click.confirm("Prompt to stdin")280    out, err = capfd.readouterr()281    assert out == "Prompt to stdin [y/N]: "282    assert err == ""283284    emulate_input("y\n")285    click.confirm("Prompt to stderr", err=True)286    out, err = capfd.readouterr()287    assert out == " "288    assert err == "Prompt to stderr [y/N]:"289290    monkeypatch.setattr(click.termui, "isatty", lambda x: True)291    monkeypatch.setattr(click.termui, "getchar", lambda: " ")292293    click.pause("Pause to stdout")294    out, err = capfd.readouterr()295    assert out == "Pause to stdout\n"296    assert err == ""297298    click.pause("Pause to stderr", err=True)299    out, err = capfd.readouterr()300    assert out == ""301    assert err == "Pause to stderr\n"302303304def test_echo_with_capsys(capsys):305    click.echo("Capture me.")306    out, err = capsys.readouterr()307    assert out == "Capture me.\n"308309310def test_open_file(runner):311    @click.command()312    @click.argument("filename")313    def cli(filename):314        with click.open_file(filename) as f:315            click.echo(f.read())316317        click.echo("meep")318319    with runner.isolated_filesystem():320        with open("hello.txt", "w") as f:321            f.write("Cool stuff")322323        result = runner.invoke(cli, ["hello.txt"])324        assert result.exception is None325        assert result.output == "Cool stuff\nmeep\n"326327        result = runner.invoke(cli, ["-"], input="foobar")328        assert result.exception is None329        assert result.output == "foobar\nmeep\n"330331332def test_open_file_pathlib_dash(runner):333    @click.command()334    @click.argument(335        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)336    )337    def cli(filename):338        click.echo(str(type(filename)))339340        with click.open_file(filename) as f:341            click.echo(f.read())342343        result = runner.invoke(cli, ["-"], input="value")344        assert result.exception is None345        assert result.output == "pathlib.Path\nvalue\n"346347348def test_open_file_ignore_errors_stdin(runner):349    @click.command()350    @click.argument("filename")351    def cli(filename):352        with click.open_file(filename, errors="ignore") as f:353            click.echo(f.read())354355    result = runner.invoke(cli, ["-"], input=os.urandom(16))356    assert result.exception is None357358359def test_open_file_respects_ignore(runner):360    with runner.isolated_filesystem():361        with open("test.txt", "w") as f:362            f.write("Hello world!")363364        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:365            assert f.errors == "ignore"366367368def test_open_file_ignore_invalid_utf8(runner):369    with runner.isolated_filesystem():370        with open("test.txt", "wb") as f:371            f.write(b"\xe2\x28\xa1")372373        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:374            f.read()375376377def test_open_file_ignore_no_encoding(runner):378    with runner.isolated_filesystem():379        with open("test.bin", "wb") as f:380            f.write(os.urandom(16))381382        with click.open_file("test.bin", errors="ignore") as f:383            f.read()384385386@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")387@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])388def test_open_file_atomic_permissions_existing_file(runner, permissions):389    with runner.isolated_filesystem():390        with open("existing.txt", "w") as f:391            f.write("content")392        os.chmod("existing.txt", permissions)393394        @click.command()395        @click.argument("filename")396        def cli(filename):397            click.open_file(filename, "w", atomic=True).close()398399        result = runner.invoke(cli, ["existing.txt"])400        assert result.exception is None401        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions402403404@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")405def test_open_file_atomic_permissions_new_file(runner):406    with runner.isolated_filesystem():407408        @click.command()409        @click.argument("filename")410        def cli(filename):411            click.open_file(filename, "w", atomic=True).close()412413        # Create a test file to get the expected permissions for new files414        # according to the current umask.415        with open("test.txt", "w"):416            pass417        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)418419        result = runner.invoke(cli, ["new.txt"])420        assert result.exception is None421        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions422423424def test_iter_keepopenfile(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        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f)):430            assert e_line == a_line.strip()431432433def test_iter_lazyfile(tmpdir):434    expected = list(map(str, range(10)))435    p = tmpdir.mkdir("testdir").join("testfile")436    p.write("\n".join(expected))437    with p.open() as f:438        with click.utils.LazyFile(f.name) as lf:439            for e_line, a_line in zip(expected, lf):440                assert e_line == a_line.strip()441442443class MockMain:444    __slots__ = "__package__"445446    def __init__(self, package_name):447        self.__package__ = package_name448449450@pytest.mark.parametrize(451    ("path", "main", "expected"),452    [453        ("example.py", None, "example.py"),454        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),455        ("example", None, "example"),456        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),457        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),458        (str(pathlib.Path("./example")), "", "example"),459    ],460)461def test_detect_program_name(path, main, expected):462    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected463464465def test_expand_args(monkeypatch):466    user = os.path.expanduser("~")467    assert user in click.utils._expand_args(["~"])468    monkeypatch.setenv("CLICK_TEST", "hello")469    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])470    assert "pyproject.toml" in click.utils._expand_args(["*.toml"])471    assert os.path.join("docs", "conf.py") in click.utils._expand_args(["**/conf.py"])472    assert "*.not-found" in click.utils._expand_args(["*.not-found"])473    # a bad glob pattern, such as a pytest identifier, should return itself474    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"475476477@pytest.mark.parametrize(478    ("value", "max_length", "expect"),479    [480        pytest.param("", 10, "", id="empty"),481        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),482        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),483        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),484        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),485        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),486        pytest.param(487            "token in ~/.netrc ciao ciao",488            20,489            "token in ~/.netrc...",490            id="ignore dot in word",491        ),492    ],493)494@pytest.mark.parametrize(495    "alter",496    [497        pytest.param(None, id=""),498        pytest.param(499            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"500        ),501    ],502)503def test_make_default_short_help(value, max_length, alter, expect):504    assert len(expect) <= max_length505506    if alter:507        value = alter(value)508509    out = click.utils.make_default_short_help(value, max_length)510    assert out == expect