Skip to content
Myr

test_utils.py

This file

Path

tests/test_utils.py

782 lines · 24.5 KiB · Python

Last changed by

Fix readline backspace/line-wrapping on linux (#2969)Yorickbefore adoption2468b70

History of this file

Take it

1import os2import pathlib3import stat4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import StringIO12from unittest.mock import patch1314import pytest1516import click._termui_impl17import click.utils18from click._compat import WIN19from click._utils import UNSET202122def test_unset_sentinel():23    value = UNSET2425    assert value26    assert value is UNSET27    assert value == UNSET28    assert repr(value) == "Sentinel.UNSET"29    assert str(value) == "Sentinel.UNSET"30    assert bool(value) is True3132    # Try all native Python values that can be falsy or truthy.33    # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing34    real_values = (35        None,36        True,37        False,38        0,39        1,40        0.0,41        1.0,42        0j,43        1j,44        Decimal(0),45        Decimal(1),46        Fraction(0, 1),47        Fraction(1, 1),48        "",49        "a",50        "UNSET",51        "Sentinel.UNSET",52        [1],53        (1),54        {1: "a"},55        set(),56        set([1]),57        frozenset(),58        frozenset([1]),59        range(0),60        range(1),61    )6263    for real_value in real_values:64        assert value != real_value65        assert value is not real_value6667    assert value not in real_values686970def test_echo(runner):71    with runner.isolation() as outstreams:72        click.echo("\N{SNOWMAN}")73        click.echo(b"\x44\x44")74        click.echo(42, nl=False)75        click.echo(b"a", nl=False)76        click.echo("\x1b[31mx\x1b[39m", nl=False)77        bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")78        assert bytes == b"\xe2\x98\x83\nDD\n42ax"7980    # if wrapped, we expect bytes to survive.81    @click.command()82    def cli():83        click.echo(b"\xf6")8485    result = runner.invoke(cli, [])86    assert result.stdout_bytes == b"\xf6\n"8788    # Ensure we do not strip for bytes.89    with runner.isolation() as outstreams:90        click.echo(bytearray(b"\x1b[31mx\x1b[39m"), nl=False)91        assert outstreams[0].getvalue() == b"\x1b[31mx\x1b[39m"929394def test_echo_custom_file():95    f = StringIO()96    click.echo("hello", file=f)97    assert f.getvalue() == "hello\n"9899100def test_echo_no_streams(monkeypatch, runner):101    """echo should not fail when stdout and stderr are None with pythonw on Windows."""102    with runner.isolation():103        sys.stdout = None104        sys.stderr = None105        click.echo("test")106        click.echo("test", err=True)107108109@pytest.mark.parametrize(110    ("styles", "ref"),111    [112        ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),113        ({"fg": "red"}, "\x1b[31mx y\x1b[0m"),114        ({"fg": "green"}, "\x1b[32mx y\x1b[0m"),115        ({"fg": "yellow"}, "\x1b[33mx y\x1b[0m"),116        ({"fg": "blue"}, "\x1b[34mx y\x1b[0m"),117        ({"fg": "magenta"}, "\x1b[35mx y\x1b[0m"),118        ({"fg": "cyan"}, "\x1b[36mx y\x1b[0m"),119        ({"fg": "white"}, "\x1b[37mx y\x1b[0m"),120        ({"bg": "black"}, "\x1b[40mx y\x1b[0m"),121        ({"bg": "red"}, "\x1b[41mx y\x1b[0m"),122        ({"bg": "green"}, "\x1b[42mx y\x1b[0m"),123        ({"bg": "yellow"}, "\x1b[43mx y\x1b[0m"),124        ({"bg": "blue"}, "\x1b[44mx y\x1b[0m"),125        ({"bg": "magenta"}, "\x1b[45mx y\x1b[0m"),126        ({"bg": "cyan"}, "\x1b[46mx y\x1b[0m"),127        ({"bg": "white"}, "\x1b[47mx y\x1b[0m"),128        ({"bg": 91}, "\x1b[48;5;91mx y\x1b[0m"),129        ({"bg": (135, 0, 175)}, "\x1b[48;2;135;0;175mx y\x1b[0m"),130        ({"bold": True}, "\x1b[1mx y\x1b[0m"),131        ({"dim": True}, "\x1b[2mx y\x1b[0m"),132        ({"underline": True}, "\x1b[4mx y\x1b[0m"),133        ({"overline": True}, "\x1b[53mx y\x1b[0m"),134        ({"italic": True}, "\x1b[3mx y\x1b[0m"),135        ({"blink": True}, "\x1b[5mx y\x1b[0m"),136        ({"reverse": True}, "\x1b[7mx y\x1b[0m"),137        ({"strikethrough": True}, "\x1b[9mx y\x1b[0m"),138        ({"bold": False}, "\x1b[22mx y\x1b[0m"),139        ({"dim": False}, "\x1b[22mx y\x1b[0m"),140        ({"underline": False}, "\x1b[24mx y\x1b[0m"),141        ({"overline": False}, "\x1b[55mx y\x1b[0m"),142        ({"italic": False}, "\x1b[23mx y\x1b[0m"),143        ({"blink": False}, "\x1b[25mx y\x1b[0m"),144        ({"reverse": False}, "\x1b[27mx y\x1b[0m"),145        ({"strikethrough": False}, "\x1b[29mx y\x1b[0m"),146        ({"fg": "black", "reset": False}, "\x1b[30mx y"),147    ],148)149def test_styling(styles, ref):150    assert click.style("x y", **styles) == ref151    assert click.unstyle(ref) == "x y"152153154@pytest.mark.parametrize(("text", "expect"), [("\x1b[?25lx y\x1b[?25h", "x y")])155def test_unstyle_other_ansi(text, expect):156    assert click.unstyle(text) == expect157158159def test_filename_formatting():160    assert click.format_filename(b"foo.txt") == "foo.txt"161    assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"162    assert click.format_filename("/x/foo.txt") == "/x/foo.txt"163    assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"164    assert click.format_filename("/x/\ufffd.txt", shorten=True) == "�.txt"165166167def test_prompts(runner):168    @click.command()169    def test():170        if click.confirm("Foo"):171            click.echo("yes!")172        else:173            click.echo("no :(")174175    result = runner.invoke(test, input="y\n")176    assert not result.exception177    assert result.output == "Foo [y/N]: y\nyes!\n"178179    result = runner.invoke(test, input="\n")180    assert not result.exception181    assert result.output == "Foo [y/N]: \nno :(\n"182183    result = runner.invoke(test, input="n\n")184    assert not result.exception185    assert result.output == "Foo [y/N]: n\nno :(\n"186187    @click.command()188    def test_no():189        if click.confirm("Foo", default=True):190            click.echo("yes!")191        else:192            click.echo("no :(")193194    result = runner.invoke(test_no, input="y\n")195    assert not result.exception196    assert result.output == "Foo [Y/n]: y\nyes!\n"197198    result = runner.invoke(test_no, input="\n")199    assert not result.exception200    assert result.output == "Foo [Y/n]: \nyes!\n"201202    result = runner.invoke(test_no, input="n\n")203    assert not result.exception204    assert result.output == "Foo [Y/n]: n\nno :(\n"205206207def test_confirm_repeat(runner):208    cli = click.Command(209        "cli", params=[click.Option(["--a/--no-a"], default=None, prompt=True)]210    )211    result = runner.invoke(cli, input="\ny\n")212    assert result.output == "A [y/n]: \nError: invalid input\nA [y/n]: y\n"213214215@pytest.mark.skipif(WIN, reason="Different behavior on windows.")216def test_prompts_abort(monkeypatch, capsys):217    def f(_):218        raise KeyboardInterrupt()219220    monkeypatch.setattr("click.termui.hidden_prompt_func", f)221222    try:223        click.prompt("Password", hide_input=True)224    except click.Abort:225        click.echo("interrupted")226227    out, err = capsys.readouterr()228    # On non-Windows, prompt is passed directly to getpass, not echoed separately229    assert out == "\ninterrupted\n"230231232@pytest.mark.skipif(WIN, reason="Different behavior on windows.")233@pytest.mark.parametrize(234    ("call", "expected_prompt"),235    [236        (lambda: click.prompt("Name"), "Name: "),237        (lambda: click.prompt("Pw", hide_input=True), "Pw: "),238        (lambda: click.prompt("IP", prompt_suffix="."), "IP."),239        (lambda: click.confirm("OK"), "OK [y/N]: "),240    ],241    ids=["prompt", "prompt-hidden", "prompt-custom-suffix", "confirm"],242)243def test_full_prompt_passed_to_readline(monkeypatch, call, expected_prompt):244    """On non-Windows, prompt and confirm pass the full prompt text to the245    underlying prompt function so readline handles editing correctly.246247    https://github.com/pallets/click/issues/2968248    https://github.com/pallets/click/pull/2969249    """250    received = []251252    def capture(text):253        received.append(text)254        return "y"255256    monkeypatch.setattr("click.termui.visible_prompt_func", capture)257    monkeypatch.setattr("click.termui.hidden_prompt_func", capture)258    call()259    assert received == [expected_prompt]260261262def test_prompts_eof(runner):263    """If too few lines of input are given, prompt should exit, not hang."""264265    @click.command266    def echo():267        for _ in range(3):268            click.echo(click.prompt("", type=int))269270    # only provide two lines of input for three prompts271    result = runner.invoke(echo, input="1\n2\n")272    assert result.exit_code == 1273274275def _test_gen_func():276    yield "a"277    yield "b"278    yield "c"279    yield "abc"280281282def _test_gen_func_fails():283    yield "test"284    raise RuntimeError("This is a test.")285286287def _test_gen_func_echo(file=None):288    yield "test"289    click.echo("hello", file=file)290    yield "test"291292293def _test_simulate_keyboard_interrupt(file=None):294    yield "output_before_keyboard_interrupt"295    raise KeyboardInterrupt()296297298EchoViaPagerTest = namedtuple(299    "EchoViaPagerTest",300    (301        "description",302        "test_input",303        "expected_pager",304        "expected_stdout",305        "expected_stderr",306        "expected_error",307    ),308)309310311@pytest.mark.skipif(WIN, reason="Different behavior on windows.")312@pytest.mark.parametrize(313    "pager_cmd", ["cat", "cat ", " cat ", "less", " less", " less "]314)315@pytest.mark.parametrize(316    "test",317    [318        # We need to pass a parameter function instead of a plain param319        # as pytest.mark.parametrize will reuse the parameters causing the320        # generators to be used up so they will not yield anymore321        EchoViaPagerTest(322            description="Plain string argument",323            test_input=lambda: "just text",324            expected_pager="just text\n",325            expected_stdout="",326            expected_stderr="",327            expected_error=None,328        ),329        EchoViaPagerTest(330            description="Iterable argument",331            test_input=lambda: ["itera", "ble"],332            expected_pager="iterable\n",333            expected_stdout="",334            expected_stderr="",335            expected_error=None,336        ),337        EchoViaPagerTest(338            description="Generator function argument",339            test_input=lambda: _test_gen_func,340            expected_pager="abcabc\n",341            expected_stdout="",342            expected_stderr="",343            expected_error=None,344        ),345        EchoViaPagerTest(346            description="String generator argument",347            test_input=lambda: _test_gen_func(),348            expected_pager="abcabc\n",349            expected_stdout="",350            expected_stderr="",351            expected_error=None,352        ),353        EchoViaPagerTest(354            description="Number generator expression argument",355            test_input=lambda: (c for c in range(6)),356            expected_pager="012345\n",357            expected_stdout="",358            expected_stderr="",359            expected_error=None,360        ),361        EchoViaPagerTest(362            description="Exception in generator function argument",363            test_input=lambda: _test_gen_func_fails,364            # Because generator throws early on, the pager did not have365            # a chance yet to write the file.366            expected_pager="",367            expected_stdout="",368            expected_stderr="",369            expected_error=RuntimeError,370        ),371        EchoViaPagerTest(372            description="Exception in generator argument",373            test_input=lambda: _test_gen_func_fails,374            # Because generator throws early on, the pager did not have a375            # chance yet to write the file.376            expected_pager="",377            expected_stdout="",378            expected_stderr="",379            expected_error=RuntimeError,380        ),381        EchoViaPagerTest(382            description="Keyboard interrupt should not terminate the pager",383            test_input=lambda: _test_simulate_keyboard_interrupt(),384            # Due to the keyboard interrupt during pager execution, click program385            # should abort, but the pager should stay open.386            # This allows users to cancel the program and search in the pager387            # output, before they decide to terminate the pager.388            expected_pager="output_before_keyboard_interrupt",389            expected_stdout="",390            expected_stderr="",391            expected_error=KeyboardInterrupt,392        ),393        EchoViaPagerTest(394            description="Writing to stdout during generator execution",395            test_input=lambda: _test_gen_func_echo(),396            expected_pager="testtest\n",397            expected_stdout="hello\n",398            expected_stderr="",399            expected_error=None,400        ),401        EchoViaPagerTest(402            description="Writing to stderr during generator execution",403            test_input=lambda: _test_gen_func_echo(file=sys.stderr),404            expected_pager="testtest\n",405            expected_stdout="",406            expected_stderr="hello\n",407            expected_error=None,408        ),409    ],410)411def test_echo_via_pager(monkeypatch, capfd, pager_cmd, test, tmp_path):412    monkeypatch.setitem(os.environ, "PAGER", pager_cmd)413    monkeypatch.setattr(click._termui_impl, "isatty", lambda x: True)414415    test_input = test.test_input()416    expected_pager = test.expected_pager417    expected_stdout = test.expected_stdout418    expected_stderr = test.expected_stderr419    expected_error = test.expected_error420421    check_raise = pytest.raises(expected_error) if expected_error else nullcontext()422423    pager_out_tmp = tmp_path / "pager_out.txt"424    with pager_out_tmp.open("w") as f:425        force_subprocess_stdout = patch.object(426            subprocess,427            "Popen",428            partial(subprocess.Popen, stdout=f),429        )430        with force_subprocess_stdout:431            with check_raise:432                click.echo_via_pager(test_input)433434    out, err = capfd.readouterr()435436    pager = pager_out_tmp.read_text()437438    assert pager == expected_pager, (439        f"Unexpected pager output in test case '{test.description}'"440    )441    assert out == expected_stdout, (442        f"Unexpected stdout in test case '{test.description}'"443    )444    assert err == expected_stderr, (445        f"Unexpected stderr in test case '{test.description}'"446    )447448449def test_echo_color_flag(monkeypatch, capfd):450    isatty = True451    monkeypatch.setattr(click._compat, "isatty", lambda x: isatty)452453    text = "foo"454    styled_text = click.style(text, fg="red")455    assert styled_text == "\x1b[31mfoo\x1b[0m"456457    click.echo(styled_text, color=False)458    out, err = capfd.readouterr()459    assert out == f"{text}\n"460461    click.echo(styled_text, color=True)462    out, err = capfd.readouterr()463    assert out == f"{styled_text}\n"464465    isatty = True466    click.echo(styled_text)467    out, err = capfd.readouterr()468    assert out == f"{styled_text}\n"469470    isatty = False471    # Faking isatty() is not enough on Windows;472    # the implementation caches the colorama wrapped stream473    # so we have to use a new stream for each test474    stream = StringIO()475    click.echo(styled_text, file=stream)476    assert stream.getvalue() == f"{text}\n"477478    stream = StringIO()479    click.echo(styled_text, file=stream, color=True)480    assert stream.getvalue() == f"{styled_text}\n"481482483def test_prompt_cast_default(capfd, monkeypatch):484    monkeypatch.setattr(sys, "stdin", StringIO("\n"))485    value = click.prompt("value", default="100", type=int)486    capfd.readouterr()487    assert isinstance(value, int)488489490@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")491def test_echo_writing_to_standard_error(capfd, monkeypatch):492    def emulate_input(text):493        """Emulate keyboard input."""494        monkeypatch.setattr(sys, "stdin", StringIO(text))495496    click.echo("Echo to standard output")497    out, err = capfd.readouterr()498    assert out == "Echo to standard output\n"499    assert err == ""500501    click.echo("Echo to standard error", err=True)502    out, err = capfd.readouterr()503    assert out == ""504    assert err == "Echo to standard error\n"505506    emulate_input("asdlkj\n")507    click.prompt("Prompt to stdin")508    out, err = capfd.readouterr()509    assert out == "Prompt to stdin: "510    assert err == ""511512    emulate_input("asdlkj\n")513    click.prompt("Prompt to stdin with no suffix", prompt_suffix="")514    out, err = capfd.readouterr()515    assert out == "Prompt to stdin with no suffix"516    assert err == ""517518    # On non-Windows the full prompt goes through redirect_stdout so519    # nothing leaks to stdout when err=True.520    # https://github.com/pallets/click/issues/2968521    emulate_input("asdlkj\n")522    click.prompt("Prompt to stderr", err=True)523    out, err = capfd.readouterr()524    assert out == ""525    assert err == "Prompt to stderr: "526527    # https://github.com/pallets/click/issues/3019528    emulate_input("asdlkj\n")529    click.prompt("Prompt to stderr with no suffix", prompt_suffix="", err=True)530    out, err = capfd.readouterr()531    assert out == ""532    assert err == "Prompt to stderr with no suffix"533534    emulate_input("y\n")535    click.confirm("Prompt to stdin")536    out, err = capfd.readouterr()537    assert out == "Prompt to stdin [y/N]: "538    assert err == ""539540    emulate_input("y\n")541    click.confirm("Prompt to stdin with no suffix", prompt_suffix="")542    out, err = capfd.readouterr()543    assert out == "Prompt to stdin with no suffix [y/N]"544    assert err == ""545546    # https://github.com/pallets/click/issues/2968547    emulate_input("y\n")548    click.confirm("Prompt to stderr", err=True)549    out, err = capfd.readouterr()550    assert out == ""551    assert err == "Prompt to stderr [y/N]: "552553    # https://github.com/pallets/click/issues/3019554    emulate_input("y\n")555    click.confirm("Prompt to stderr with no suffix", prompt_suffix="", err=True)556    out, err = capfd.readouterr()557    assert out == ""558    assert err == "Prompt to stderr with no suffix [y/N]"559560    monkeypatch.setattr(click.termui, "isatty", lambda x: True)561    monkeypatch.setattr(click.termui, "getchar", lambda: " ")562563    click.pause("Pause to stdout")564    out, err = capfd.readouterr()565    assert out == "Pause to stdout\n"566    assert err == ""567568    click.pause("Pause to stderr", err=True)569    out, err = capfd.readouterr()570    assert out == ""571    assert err == "Pause to stderr\n"572573574def test_echo_with_capsys(capsys):575    click.echo("Capture me.")576    out, err = capsys.readouterr()577    assert out == "Capture me.\n"578579580def test_open_file(runner):581    @click.command()582    @click.argument("filename")583    def cli(filename):584        with click.open_file(filename) as f:585            click.echo(f.read())586587        click.echo("meep")588589    with runner.isolated_filesystem():590        with open("hello.txt", "w") as f:591            f.write("Cool stuff")592593        result = runner.invoke(cli, ["hello.txt"])594        assert result.exception is None595        assert result.output == "Cool stuff\nmeep\n"596597        result = runner.invoke(cli, ["-"], input="foobar")598        assert result.exception is None599        assert result.output == "foobar\nmeep\n"600601602def test_open_file_pathlib_dash(runner):603    @click.command()604    @click.argument(605        "filename", type=click.Path(allow_dash=True, path_type=pathlib.Path)606    )607    def cli(filename):608        click.echo(str(type(filename)))609610        with click.open_file(filename) as f:611            click.echo(f.read())612613        result = runner.invoke(cli, ["-"], input="value")614        assert result.exception is None615        assert result.output == "pathlib.Path\nvalue\n"616617618def test_open_file_ignore_errors_stdin(runner):619    @click.command()620    @click.argument("filename")621    def cli(filename):622        with click.open_file(filename, errors="ignore") as f:623            click.echo(f.read())624625    result = runner.invoke(cli, ["-"], input=os.urandom(16))626    assert result.exception is None627628629def test_open_file_respects_ignore(runner):630    with runner.isolated_filesystem():631        with open("test.txt", "w") as f:632            f.write("Hello world!")633634        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:635            assert f.errors == "ignore"636637638def test_open_file_ignore_invalid_utf8(runner):639    with runner.isolated_filesystem():640        with open("test.txt", "wb") as f:641            f.write(b"\xe2\x28\xa1")642643        with click.open_file("test.txt", encoding="utf8", errors="ignore") as f:644            f.read()645646647def test_open_file_ignore_no_encoding(runner):648    with runner.isolated_filesystem():649        with open("test.bin", "wb") as f:650            f.write(os.urandom(16))651652        with click.open_file("test.bin", errors="ignore") as f:653            f.read()654655656@pytest.mark.skipif(WIN, reason="os.chmod() is not fully supported on Windows.")657@pytest.mark.parametrize("permissions", [0o400, 0o444, 0o600, 0o644])658def test_open_file_atomic_permissions_existing_file(runner, permissions):659    with runner.isolated_filesystem():660        with open("existing.txt", "w") as f:661            f.write("content")662        os.chmod("existing.txt", permissions)663664        @click.command()665        @click.argument("filename")666        def cli(filename):667            click.open_file(filename, "w", atomic=True).close()668669        result = runner.invoke(cli, ["existing.txt"])670        assert result.exception is None671        assert stat.S_IMODE(os.stat("existing.txt").st_mode) == permissions672673674@pytest.mark.skipif(WIN, reason="os.stat() is not fully supported on Windows.")675def test_open_file_atomic_permissions_new_file(runner):676    with runner.isolated_filesystem():677678        @click.command()679        @click.argument("filename")680        def cli(filename):681            click.open_file(filename, "w", atomic=True).close()682683        # Create a test file to get the expected permissions for new files684        # according to the current umask.685        with open("test.txt", "w"):686            pass687        permissions = stat.S_IMODE(os.stat("test.txt").st_mode)688689        result = runner.invoke(cli, ["new.txt"])690        assert result.exception is None691        assert stat.S_IMODE(os.stat("new.txt").st_mode) == permissions692693694def test_iter_keepopenfile(tmpdir):695    expected = list(map(str, range(10)))696    p = tmpdir.mkdir("testdir").join("testfile")697    p.write("\n".join(expected))698    with p.open() as f:699        for e_line, a_line in zip(expected, click.utils.KeepOpenFile(f), strict=False):700            assert e_line == a_line.strip()701702703def test_iter_lazyfile(tmpdir):704    expected = list(map(str, range(10)))705    p = tmpdir.mkdir("testdir").join("testfile")706    p.write("\n".join(expected))707    with p.open() as f:708        with click.utils.LazyFile(f.name) as lf:709            for e_line, a_line in zip(expected, lf, strict=False):710                assert e_line == a_line.strip()711712713class MockMain:714    __slots__ = "__package__"715716    def __init__(self, package_name):717        self.__package__ = package_name718719720@pytest.mark.parametrize(721    ("path", "main", "expected"),722    [723        ("example.py", None, "example.py"),724        (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),725        ("example", None, "example"),726        (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),727        (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),728        (str(pathlib.Path("./example")), "", "example"),729    ],730)731def test_detect_program_name(path, main, expected):732    assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected733734735def test_expand_args(monkeypatch):736    user = os.path.expanduser("~")737    assert user in click.utils._expand_args(["~"])738    monkeypatch.setenv("CLICK_TEST", "hello")739    assert "hello" in click.utils._expand_args(["$CLICK_TEST"])740    assert "pyproject.toml" in click.utils._expand_args(["*.toml"])741    assert os.path.join("tests", "conftest.py") in click.utils._expand_args(742        ["**/conftest.py"]743    )744    assert "*.not-found" in click.utils._expand_args(["*.not-found"])745    # a bad glob pattern, such as a pytest identifier, should return itself746    assert click.utils._expand_args(["test.py::test_bad"])[0] == "test.py::test_bad"747748749@pytest.mark.parametrize(750    ("value", "max_length", "expect"),751    [752        pytest.param("", 10, "", id="empty"),753        pytest.param("123 567 90", 10, "123 567 90", id="equal length, no dot"),754        pytest.param("123 567 9. aaaa bbb", 10, "123 567 9.", id="sentence < max"),755        pytest.param("123 567\n\n 9. aaaa bbb", 10, "123 567", id="paragraph < max"),756        pytest.param("123 567 90123.", 10, "123 567...", id="truncate"),757        pytest.param("123 5678 xxxxxx", 10, "123...", id="length includes suffix"),758        pytest.param(759            "token in ~/.netrc ciao ciao",760            20,761            "token in ~/.netrc...",762            id="ignore dot in word",763        ),764    ],765)766@pytest.mark.parametrize(767    "alter",768    [769        pytest.param(None, id=""),770        pytest.param(771            lambda text: "\n\b\n" + "  ".join(text.split(" ")) + "\n", id="no-wrap mark"772        ),773    ],774)775def test_make_default_short_help(value, max_length, alter, expect):776    assert len(expect) <= max_length777778    if alter:779        value = alter(value)780781    out = click.utils.make_default_short_help(value, max_length)782    assert out == expect