Skip to content
Myr

test_formatting.py

This file

Path

tests/test_formatting.py

632 lines · 17.9 KiB · Python

Last changed by

Strip all ANSI sequences (#3681)Rowlando13before adoption8c1a0a7

History of this file

Take it

1import pytest23import click4from click._compat import strip_ansi567def test_basic_functionality(runner):8    @click.command()9    def cli():10        """First paragraph.1112        This is a very long second13        paragraph and not correctly14        wrapped but it will be rewrapped.1516        \b17        This is18        a paragraph19        without rewrapping.2021        \b22        123         224          32526        And this is a paragraph27        that will be rewrapped again.28        """2930    result = runner.invoke(cli, ["--help"], terminal_width=60)31    assert not result.exception32    assert result.output.splitlines() == [33        "Usage: cli [OPTIONS]",34        "",35        "  First paragraph.",36        "",37        "  This is a very long second paragraph and not correctly",38        "  wrapped but it will be rewrapped.",39        "",40        "  This is",41        "  a paragraph",42        "  without rewrapping.",43        "",44        "  1",45        "   2",46        "    3",47        "",48        "  And this is a paragraph that will be rewrapped again.",49        "",50        "Options:",51        "  --help  Show this message and exit.",52    ]535455def test_wrapping_long_options_strings(runner):56    @click.group()57    def cli():58        """Top level command"""5960    @cli.group()61    def a_very_long():62        """Second level"""6364    @a_very_long.command()65    @click.argument("first")66    @click.argument("second")67    @click.argument("third")68    @click.argument("fourth")69    @click.argument("fifth")70    @click.argument("sixth")71    def command():72        """A command."""7374    # 54 is chosen as a length where the second line is one character75    # longer than the maximum length.76    result = runner.invoke(cli, ["a-very-long", "command", "--help"], terminal_width=54)77    assert not result.exception78    assert result.output.splitlines() == [79        "Usage: cli a-very-long command [OPTIONS] FIRST SECOND",80        "                               THIRD FOURTH FIFTH",81        "                               SIXTH",82        "",83        "  A command.",84        "",85        "Options:",86        "  --help  Show this message and exit.",87    ]888990def test_wrapping_long_command_name(runner):91    @click.group()92    def cli():93        """Top level command"""9495    @cli.group()96    def a_very_very_very_long():97        """Second level"""9899    @a_very_very_very_long.command()100    @click.argument("first")101    @click.argument("second")102    @click.argument("third")103    @click.argument("fourth")104    @click.argument("fifth")105    @click.argument("sixth")106    def command():107        """A command."""108109    result = runner.invoke(110        cli, ["a-very-very-very-long", "command", "--help"], terminal_width=54111    )112    assert not result.exception113    assert result.output.splitlines() == [114        "Usage: cli a-very-very-very-long command ",115        "           [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH",116        "           SIXTH",117        "",118        "  A command.",119        "",120        "Options:",121        "  --help  Show this message and exit.",122    ]123124125def test_formatting_empty_help_lines(runner):126    @click.command()127    def cli():128        # fmt: off129        """Top level command130131        """132        # fmt: on133134    result = runner.invoke(cli, ["--help"])135    assert not result.exception136    assert result.output.splitlines() == [137        "Usage: cli [OPTIONS]",138        "",139        "  Top level command",140        "",141        "",142        "",143        "Options:",144        "  --help  Show this message and exit.",145    ]146147148def test_formatting_usage_error(runner):149    @click.command()150    @click.argument("arg")151    def cmd(arg):152        click.echo(f"arg:{arg}")153154    result = runner.invoke(cmd, [])155    assert result.exit_code == 2156    assert result.output.splitlines() == [157        "Usage: cmd [OPTIONS] ARG",158        "Try 'cmd --help' for help.",159        "",160        "Error: Missing argument 'ARG'.",161    ]162163164def test_formatting_usage_error_metavar_missing_arg(runner):165    """166    :author: @r-m-n167    Including attribution to #612168    """169170    @click.command()171    @click.argument("arg", metavar="metavar")172    def cmd(arg):173        pass174175    result = runner.invoke(cmd, [])176    assert result.exit_code == 2177    assert result.output.splitlines() == [178        "Usage: cmd [OPTIONS] metavar",179        "Try 'cmd --help' for help.",180        "",181        "Error: Missing argument 'metavar'.",182    ]183184185def test_formatting_usage_error_metavar_bad_arg(runner):186    @click.command()187    @click.argument("arg", type=click.INT, metavar="metavar")188    def cmd(arg):189        pass190191    result = runner.invoke(cmd, ["3.14"])192    assert result.exit_code == 2193    assert result.output.splitlines() == [194        "Usage: cmd [OPTIONS] metavar",195        "Try 'cmd --help' for help.",196        "",197        "Error: Invalid value for 'metavar': '3.14' is not a valid integer.",198    ]199200201def test_formatting_usage_error_nested(runner):202    @click.group()203    def cmd():204        pass205206    @cmd.command()207    @click.argument("bar")208    def foo(bar):209        click.echo(f"foo:{bar}")210211    result = runner.invoke(cmd, ["foo"])212    assert result.exit_code == 2213    assert result.output.splitlines() == [214        "Usage: cmd foo [OPTIONS] BAR",215        "Try 'cmd foo --help' for help.",216        "",217        "Error: Missing argument 'BAR'.",218    ]219220221def test_formatting_usage_error_no_help(runner):222    @click.command(add_help_option=False)223    @click.argument("arg")224    def cmd(arg):225        click.echo(f"arg:{arg}")226227    result = runner.invoke(cmd, [])228    assert result.exit_code == 2229    assert result.output.splitlines() == [230        "Usage: cmd [OPTIONS] ARG",231        "",232        "Error: Missing argument 'ARG'.",233    ]234235236def test_formatting_usage_custom_help(runner):237    @click.command(context_settings=dict(help_option_names=["--man"]))238    @click.argument("arg")239    def cmd(arg):240        click.echo(f"arg:{arg}")241242    result = runner.invoke(cmd, [])243    assert result.exit_code == 2244    assert result.output.splitlines() == [245        "Usage: cmd [OPTIONS] ARG",246        "Try 'cmd --man' for help.",247        "",248        "Error: Missing argument 'ARG'.",249    ]250251252@pytest.mark.parametrize(253    ("help_names", "extra_options", "expected_hint"),254    [255        # No shadowing, longest name is picked.256        (["-h", "--help"], [], "Try 'cli foo --help' for help."),257        # -h shadowed by a subcommand option, --help still available.258        (259            ["-h", "--help"],260            [click.option("--host", "-h")],261            "Try 'cli foo --help' for help.",262        ),263        # --help shadowed, -h still available.264        (265            ["-h", "--help"],266            [click.option("--help-file", "--help")],267            "Try 'cli foo -h' for help.",268        ),269        # Both names shadowed: no hint line at all.270        (271            ["-h", "--help"],272            [click.option("--host", "-h"), click.option("--help-file", "--help")],273            None,274        ),275        # Single custom help name, not shadowed.276        (["--man"], [], "Try 'cli foo --man' for help."),277        # Three help names, one shadowed, longest survivor picked.278        (279            ["-h", "--help", "--info"],280            [click.option("--info-file", "--info")],281            "Try 'cli foo --help' for help.",282        ),283    ],284)285def test_formatting_usage_error_help_hint(286    runner, help_names, extra_options, expected_hint287):288    """The error hint should only show non-shadowed help option names,289    picking the longest for readability.290291    https://github.com/pallets/click/issues/2790292    """293294    @click.group(context_settings={"help_option_names": help_names})295    def cli():296        pass297298    @cli.command()299    @click.argument("required_arg")300    def foo(required_arg, **kwargs):301        pass302303    for option in extra_options:304        option(foo)305306    result = runner.invoke(cli, ["foo"])307    assert result.exit_code == 2308    lines = result.output.splitlines()309    assert lines[0] == "Usage: cli foo [OPTIONS] REQUIRED_ARG"310    assert lines[-1] == "Error: Missing argument 'REQUIRED_ARG'."311    if expected_hint is not None:312        assert expected_hint in lines313    else:314        assert not any(line.startswith("Try ") for line in lines)315316317def test_formatting_custom_type_metavar(runner):318    class MyType(click.ParamType):319        def get_metavar(self, param: click.Parameter, ctx: click.Context):320            return "MY_TYPE"321322    @click.command("foo")323    @click.help_option()324    @click.argument("param", type=MyType())325    def cmd(param):326        pass327328    result = runner.invoke(cmd, "--help")329    assert not result.exception330    assert result.output.splitlines() == [331        "Usage: foo [OPTIONS] MY_TYPE",332        "",333        "Options:",334        "  --help  Show this message and exit.",335    ]336337338def test_truncating_docstring(runner):339    @click.command()340    @click.pass_context341    def cli(ctx):342        """First paragraph.343344        This is a very long second345        paragraph and not correctly346        wrapped but it will be rewrapped.347        \f348349        :param click.core.Context ctx: Click context.350        """351352    result = runner.invoke(cli, ["--help"], terminal_width=60)353    assert not result.exception354    assert result.output.splitlines() == [355        "Usage: cli [OPTIONS]",356        "",357        "  First paragraph.",358        "",359        "  This is a very long second paragraph and not correctly",360        "  wrapped but it will be rewrapped.",361        "",362        "Options:",363        "  --help  Show this message and exit.",364    ]365366367def test_truncating_docstring_no_help(runner):368    @click.command()369    @click.pass_context370    def cli(ctx):371        """372        \f373374        This text should be truncated.375        """376377    result = runner.invoke(cli, ["--help"], terminal_width=60)378    assert not result.exception379    assert result.output.splitlines() == [380        "Usage: cli [OPTIONS]",381        "",382        "Options:",383        "  --help  Show this message and exit.",384    ]385386387def test_removing_multiline_marker(runner):388    @click.group()389    def cli():390        pass391392    @cli.command()393    def cmd1():394        """\b395        This is command with a multiline help text396        which should not be rewrapped.397        The output of the short help text should398        not contain the multiline marker.399        """400        pass401402    result = runner.invoke(cli, ["--help"])403    assert "\b" not in result.output404405406def test_global_show_default(runner):407    @click.command(context_settings=dict(show_default=True))408    @click.option("-f", "in_file", default="out.txt", help="Output file name")409    def cli():410        pass411412    result = runner.invoke(cli, ["--help"])413    # the default to "--help" is not shown because it is False414    assert result.output.splitlines() == [415        "Usage: cli [OPTIONS]",416        "",417        "Options:",418        "  -f TEXT  Output file name  [default: out.txt]",419        "  --help   Show this message and exit.",420    ]421422423def test_formatting_with_options_metavar_empty(runner):424    cli = click.Command("cli", options_metavar="", params=[click.Argument(["var"])])425    result = runner.invoke(cli, ["--help"])426    assert "Usage: cli VAR\n" in result.output427428429def test_help_formatter_write_text():430    text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"431    formatter = click.HelpFormatter(width=len("  Lorem ipsum dolor sit amet,"))432    formatter.current_indent = 2433    formatter.write_text(text)434    actual = formatter.getvalue()435    expected = "  Lorem ipsum dolor sit amet,\n  consectetur adipiscing elit\n"436    assert actual == expected437438439@pytest.mark.parametrize(440    ("body", "width", "initial_indent"),441    [442        # Styled ``initial_indent`` must be measured by visible width, so the443        # ``Usage:`` prefix shouldn't push ``[OPTIONS]`` to the second line.444        # Regression for the asymmetry between ``HelpFormatter.write_usage``445        # (which sized the prefix with ``term_len``) and ``wrap_text``446        # (which previously used raw ``len``).447        pytest.param(448            "[OPTIONS]",449            30,450            "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m ",451            id="styled-initial-indent-does-not-break-body",452        ),453        # Styled chunks in the body itself wrap on visible width.454        pytest.param(455            "\x1b[31malpha\x1b[0m \x1b[31mbeta\x1b[0m"456            " \x1b[31mgamma\x1b[0m \x1b[31mdelta\x1b[0m",457            15,458            "",459            id="styled-body-wraps-on-visible-width",460        ),461        # ``_handle_long_word`` cuts a styled token between visible462        # characters; the ANSI escape sequence must not be split.463        pytest.param(464            "\x1b[31mabcdefghij\x1b[0m",465            5,466            "",467            id="styled-long-word-breaks-on-visible-width",468        ),469        # Colon-delimited true-color (ISO 8613-6) escapes are excluded from the470        # width budget too.471        pytest.param(472            "\x1b[38:2:255:0:0malpha\x1b[0m \x1b[38:2:0:255:0mbeta\x1b[0m"473            " \x1b[38:2:0:0:255mgamma\x1b[0m \x1b[38:2:9:9:9mdelta\x1b[0m",474            15,475            "",476            id="colon-truecolor-body-wraps-on-visible-width",477        ),478        # A mouse-reporting sequence embedded mid-line is zero-width too.479        pytest.param(480            "\x1b[<0;1;1malpha beta gamma delta\x1b[<0;1;1m",481            15,482            "",483            id="mouse-sequence-is-zero-width",484        ),485    ],486)487def test_wrap_text_visible_width(body, width, initial_indent):488    """``wrap_text`` of styled input produces the same line layout as489    ``wrap_text`` of the ANSI-stripped input.490491    ANSI escape bytes must not count toward the width budget, regardless492    of whether they appear in the body, in ``initial_indent``, or when a493    styled token has to be broken in the middle.494    """495    styled = click.formatting.wrap_text(496        body, width=width, initial_indent=initial_indent497    )498    plain = click.formatting.wrap_text(499        strip_ansi(body), width=width, initial_indent=strip_ansi(initial_indent)500    )501502    styled_visible = [strip_ansi(line) for line in styled.splitlines()]503    assert styled_visible == plain.splitlines()504505506def test_write_usage_styled_prefix_keeps_options_on_one_line():507    """End-to-end: a downstream-styled ``Usage:`` prefix should not split508    ``[OPTIONS]`` across two lines.509    """510    styled_prefix = "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m "511512    formatter = click.HelpFormatter(width=40)513    formatter.write_usage("cli", "[OPTIONS]", prefix=styled_prefix)514    rendered = formatter.getvalue()515516    visible = strip_ansi(rendered)517    assert visible == "Usage: cli [OPTIONS]\n"518519520@pytest.mark.parametrize(521    ("formatter_kwargs", "current_indent", "prog", "args", "prefix", "expected"),522    [523        # Issue #3360: the default prefix used to emit only524        # a blank line because ``wrap_text("", initial_indent=usage_prefix)``525        # returned ``""`` and discarded the prefix.526        pytest.param(527            {},528            0,529            "Program",530            "",531            None,532            "Usage: Program\n",533            id="empty-args-default-prefix",534        ),535        # A caller-supplied prefix is preserved verbatim.536        pytest.param(537            {},538            0,539            "Program",540            "",541            "Run: ",542            "Run: Program\n",543            id="empty-args-custom-prefix",544        ),545        # ``current_indent`` is preserved even with no args to render.546        pytest.param(547            {},548            4,549            "Program",550            "",551            None,552            "Usage: Program\n",553            id="empty-args-indented",554        ),555        # Prog too long to share a line with args: the wrap branch must not556        # emit a second line.557        pytest.param(558            {"width": 20},559            0,560            "VeryLongProgramName",561            "",562            None,563            "Usage: VeryLongProgramName\n",564            id="empty-args-long-prog",565        ),566        # With non-empty args, the separator space between prog and args is preserved.567        pytest.param(568            {},569            0,570            "Program",571            "[OPTIONS]",572            None,573            "Usage: Program [OPTIONS]\n",574            id="with-args-default-prefix",575        ),576    ],577)578def test_help_formatter_write_usage(579    formatter_kwargs, current_indent, prog, args, prefix, expected580):581    """``HelpFormatter.write_usage`` renders a single usage line whose582    trailing separator tracks whether ``args`` is non-empty.583    """584    f = click.HelpFormatter(**formatter_kwargs)585    f.current_indent = current_indent586    if prefix is None:587        f.write_usage(prog, args)588    else:589        f.write_usage(prog, args, prefix=prefix)590    assert f.getvalue() == expected591592593def test_help_formatter_write_usage_without_args_styled_prefix():594    """A downstream-styled prefix is preserved when ``args`` is empty:595    the ANSI escape sequences survive, only the trailing separator is596    removed.597    """598    styled_prefix = "\x1b[38;2;38;139;210m\x1b[1mUsage:\x1b[0m "599    f = click.HelpFormatter()600    f.write_usage("cli", prefix=styled_prefix)601    rendered = f.getvalue()602    assert strip_ansi(rendered) == "Usage: cli\n"603    assert "\x1b[" in rendered604605606@pytest.mark.parametrize(607    ("command_kwargs", "expected_usage_line"),608    [609        # End-to-end regression for #3360: an empty ``options_metavar`` with610        # no parameters used to render a blank usage line.611        pytest.param(612            {"options_metavar": ""},613            "Usage: cli",614            id="empty-options-metavar-no-params",615        ),616        # End-to-end regression: ``options_metavar=None`` is the documented617        # way to suppress the ``[OPTIONS]`` slot entirely.618        pytest.param(619            {"options_metavar": None},620            "Usage: cli",621            id="none-options-metavar-no-params",622        ),623    ],624)625def test_command_write_usage_no_args(runner, command_kwargs, expected_usage_line):626    """End-to-end: a command with no parameters and an empty or absent627    ``options_metavar`` renders a usage line with just the program name,628    no trailing space.629    """630    cli = click.Command("cli", **command_kwargs)631    result = runner.invoke(cli, ["--help"])632    assert result.output.splitlines()[0] == expected_usage_line