Skip to content
Myr

test_formatting.py

This file

Path

tests/test_formatting.py

435 lines · 11.3 KiB · Python

Last changed by

Use non-shadowed help option name in error hintKevin Deldyckebefore adoption1241aba

History of this file

Take it

1import pytest23import click456def test_basic_functionality(runner):7    @click.command()8    def cli():9        """First paragraph.1011        This is a very long second12        paragraph and not correctly13        wrapped but it will be rewrapped.1415        \b16        This is17        a paragraph18        without rewrapping.1920        \b21        122         223          32425        And this is a paragraph26        that will be rewrapped again.27        """2829    result = runner.invoke(cli, ["--help"], terminal_width=60)30    assert not result.exception31    assert result.output.splitlines() == [32        "Usage: cli [OPTIONS]",33        "",34        "  First paragraph.",35        "",36        "  This is a very long second paragraph and not correctly",37        "  wrapped but it will be rewrapped.",38        "",39        "  This is",40        "  a paragraph",41        "  without rewrapping.",42        "",43        "  1",44        "   2",45        "    3",46        "",47        "  And this is a paragraph that will be rewrapped again.",48        "",49        "Options:",50        "  --help  Show this message and exit.",51    ]525354def test_wrapping_long_options_strings(runner):55    @click.group()56    def cli():57        """Top level command"""5859    @cli.group()60    def a_very_long():61        """Second level"""6263    @a_very_long.command()64    @click.argument("first")65    @click.argument("second")66    @click.argument("third")67    @click.argument("fourth")68    @click.argument("fifth")69    @click.argument("sixth")70    def command():71        """A command."""7273    # 54 is chosen as a length where the second line is one character74    # longer than the maximum length.75    result = runner.invoke(cli, ["a-very-long", "command", "--help"], terminal_width=54)76    assert not result.exception77    assert result.output.splitlines() == [78        "Usage: cli a-very-long command [OPTIONS] FIRST SECOND",79        "                               THIRD FOURTH FIFTH",80        "                               SIXTH",81        "",82        "  A command.",83        "",84        "Options:",85        "  --help  Show this message and exit.",86    ]878889def test_wrapping_long_command_name(runner):90    @click.group()91    def cli():92        """Top level command"""9394    @cli.group()95    def a_very_very_very_long():96        """Second level"""9798    @a_very_very_very_long.command()99    @click.argument("first")100    @click.argument("second")101    @click.argument("third")102    @click.argument("fourth")103    @click.argument("fifth")104    @click.argument("sixth")105    def command():106        """A command."""107108    result = runner.invoke(109        cli, ["a-very-very-very-long", "command", "--help"], terminal_width=54110    )111    assert not result.exception112    assert result.output.splitlines() == [113        "Usage: cli a-very-very-very-long command ",114        "           [OPTIONS] FIRST SECOND THIRD FOURTH FIFTH",115        "           SIXTH",116        "",117        "  A command.",118        "",119        "Options:",120        "  --help  Show this message and exit.",121    ]122123124def test_formatting_empty_help_lines(runner):125    @click.command()126    def cli():127        # fmt: off128        """Top level command129130        """131        # fmt: on132133    result = runner.invoke(cli, ["--help"])134    assert not result.exception135    assert result.output.splitlines() == [136        "Usage: cli [OPTIONS]",137        "",138        "  Top level command",139        "",140        "",141        "",142        "Options:",143        "  --help  Show this message and exit.",144    ]145146147def test_formatting_usage_error(runner):148    @click.command()149    @click.argument("arg")150    def cmd(arg):151        click.echo(f"arg:{arg}")152153    result = runner.invoke(cmd, [])154    assert result.exit_code == 2155    assert result.output.splitlines() == [156        "Usage: cmd [OPTIONS] ARG",157        "Try 'cmd --help' for help.",158        "",159        "Error: Missing argument 'ARG'.",160    ]161162163def test_formatting_usage_error_metavar_missing_arg(runner):164    """165    :author: @r-m-n166    Including attribution to #612167    """168169    @click.command()170    @click.argument("arg", metavar="metavar")171    def cmd(arg):172        pass173174    result = runner.invoke(cmd, [])175    assert result.exit_code == 2176    assert result.output.splitlines() == [177        "Usage: cmd [OPTIONS] metavar",178        "Try 'cmd --help' for help.",179        "",180        "Error: Missing argument 'metavar'.",181    ]182183184def test_formatting_usage_error_metavar_bad_arg(runner):185    @click.command()186    @click.argument("arg", type=click.INT, metavar="metavar")187    def cmd(arg):188        pass189190    result = runner.invoke(cmd, ["3.14"])191    assert result.exit_code == 2192    assert result.output.splitlines() == [193        "Usage: cmd [OPTIONS] metavar",194        "Try 'cmd --help' for help.",195        "",196        "Error: Invalid value for 'metavar': '3.14' is not a valid integer.",197    ]198199200def test_formatting_usage_error_nested(runner):201    @click.group()202    def cmd():203        pass204205    @cmd.command()206    @click.argument("bar")207    def foo(bar):208        click.echo(f"foo:{bar}")209210    result = runner.invoke(cmd, ["foo"])211    assert result.exit_code == 2212    assert result.output.splitlines() == [213        "Usage: cmd foo [OPTIONS] BAR",214        "Try 'cmd foo --help' for help.",215        "",216        "Error: Missing argument 'BAR'.",217    ]218219220def test_formatting_usage_error_no_help(runner):221    @click.command(add_help_option=False)222    @click.argument("arg")223    def cmd(arg):224        click.echo(f"arg:{arg}")225226    result = runner.invoke(cmd, [])227    assert result.exit_code == 2228    assert result.output.splitlines() == [229        "Usage: cmd [OPTIONS] ARG",230        "",231        "Error: Missing argument 'ARG'.",232    ]233234235def test_formatting_usage_custom_help(runner):236    @click.command(context_settings=dict(help_option_names=["--man"]))237    @click.argument("arg")238    def cmd(arg):239        click.echo(f"arg:{arg}")240241    result = runner.invoke(cmd, [])242    assert result.exit_code == 2243    assert result.output.splitlines() == [244        "Usage: cmd [OPTIONS] ARG",245        "Try 'cmd --man' for help.",246        "",247        "Error: Missing argument 'ARG'.",248    ]249250251@pytest.mark.parametrize(252    ("help_names", "extra_options", "expected_hint"),253    [254        # No shadowing, longest name is picked.255        (["-h", "--help"], [], "Try 'cli foo --help' for help."),256        # -h shadowed by a subcommand option, --help still available.257        (258            ["-h", "--help"],259            [click.option("--host", "-h")],260            "Try 'cli foo --help' for help.",261        ),262        # --help shadowed, -h still available.263        (264            ["-h", "--help"],265            [click.option("--help-file", "--help")],266            "Try 'cli foo -h' for help.",267        ),268        # Both names shadowed: no hint line at all.269        (270            ["-h", "--help"],271            [click.option("--host", "-h"), click.option("--help-file", "--help")],272            None,273        ),274        # Single custom help name, not shadowed.275        (["--man"], [], "Try 'cli foo --man' for help."),276        # Three help names, one shadowed, longest survivor picked.277        (278            ["-h", "--help", "--info"],279            [click.option("--info-file", "--info")],280            "Try 'cli foo --help' for help.",281        ),282    ],283)284def test_formatting_usage_error_help_hint(285    runner, help_names, extra_options, expected_hint286):287    """The error hint should only show non-shadowed help option names,288    picking the longest for readability.289290    https://github.com/pallets/click/issues/2790291    """292293    @click.group(context_settings={"help_option_names": help_names})294    def cli():295        pass296297    @cli.command()298    @click.argument("required_arg")299    def foo(required_arg, **kwargs):300        pass301302    for option in extra_options:303        option(foo)304305    result = runner.invoke(cli, ["foo"])306    assert result.exit_code == 2307    lines = result.output.splitlines()308    assert lines[0] == "Usage: cli foo [OPTIONS] REQUIRED_ARG"309    assert lines[-1] == "Error: Missing argument 'REQUIRED_ARG'."310    if expected_hint is not None:311        assert expected_hint in lines312    else:313        assert not any(line.startswith("Try ") for line in lines)314315316def test_formatting_custom_type_metavar(runner):317    class MyType(click.ParamType):318        def get_metavar(self, param: click.Parameter, ctx: click.Context):319            return "MY_TYPE"320321    @click.command("foo")322    @click.help_option()323    @click.argument("param", type=MyType())324    def cmd(param):325        pass326327    result = runner.invoke(cmd, "--help")328    assert not result.exception329    assert result.output.splitlines() == [330        "Usage: foo [OPTIONS] MY_TYPE",331        "",332        "Options:",333        "  --help  Show this message and exit.",334    ]335336337def test_truncating_docstring(runner):338    @click.command()339    @click.pass_context340    def cli(ctx):341        """First paragraph.342343        This is a very long second344        paragraph and not correctly345        wrapped but it will be rewrapped.346        \f347348        :param click.core.Context ctx: Click context.349        """350351    result = runner.invoke(cli, ["--help"], terminal_width=60)352    assert not result.exception353    assert result.output.splitlines() == [354        "Usage: cli [OPTIONS]",355        "",356        "  First paragraph.",357        "",358        "  This is a very long second paragraph and not correctly",359        "  wrapped but it will be rewrapped.",360        "",361        "Options:",362        "  --help  Show this message and exit.",363    ]364365366def test_truncating_docstring_no_help(runner):367    @click.command()368    @click.pass_context369    def cli(ctx):370        """371        \f372373        This text should be truncated.374        """375376    result = runner.invoke(cli, ["--help"], terminal_width=60)377    assert not result.exception378    assert result.output.splitlines() == [379        "Usage: cli [OPTIONS]",380        "",381        "Options:",382        "  --help  Show this message and exit.",383    ]384385386def test_removing_multiline_marker(runner):387    @click.group()388    def cli():389        pass390391    @cli.command()392    def cmd1():393        """\b394        This is command with a multiline help text395        which should not be rewrapped.396        The output of the short help text should397        not contain the multiline marker.398        """399        pass400401    result = runner.invoke(cli, ["--help"])402    assert "\b" not in result.output403404405def test_global_show_default(runner):406    @click.command(context_settings=dict(show_default=True))407    @click.option("-f", "in_file", default="out.txt", help="Output file name")408    def cli():409        pass410411    result = runner.invoke(cli, ["--help"])412    # the default to "--help" is not shown because it is False413    assert result.output.splitlines() == [414        "Usage: cli [OPTIONS]",415        "",416        "Options:",417        "  -f TEXT  Output file name  [default: out.txt]",418        "  --help   Show this message and exit.",419    ]420421422def test_formatting_with_options_metavar_empty(runner):423    cli = click.Command("cli", options_metavar="", params=[click.Argument(["var"])])424    result = runner.invoke(cli, ["--help"])425    assert "Usage: cli VAR\n" in result.output426427428def test_help_formatter_write_text():429    text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"430    formatter = click.HelpFormatter(width=len("  Lorem ipsum dolor sit amet,"))431    formatter.current_indent = 2432    formatter.write_text(text)433    actual = formatter.getvalue()434    expected = "  Lorem ipsum dolor sit amet,\n  consectetur adipiscing elit\n"435    assert actual == expected