Skip to content
Myr

test_commands.py

This file

Path

tests/test_commands.py

316 lines · 8.2 KiB · Python

Last changed by

Merge pull request #1615 from MLH-Fellowship/issue1422David Lordbefore adoptionfb1ca91

History of this file

Take it

1import re23import click456def test_other_command_invoke(runner):7    @click.command()8    @click.pass_context9    def cli(ctx):10        return ctx.invoke(other_cmd, arg=42)1112    @click.command()13    @click.argument("arg", type=click.INT)14    def other_cmd(arg):15        click.echo(arg)1617    result = runner.invoke(cli, [])18    assert not result.exception19    assert result.output == "42\n"202122def test_other_command_forward(runner):23    cli = click.Group()2425    @cli.command()26    @click.option("--count", default=1)27    def test(count):28        click.echo(f"Count: {count:d}")2930    @cli.command()31    @click.option("--count", default=1)32    @click.pass_context33    def dist(ctx, count):34        ctx.forward(test)35        ctx.invoke(test, count=42)3637    result = runner.invoke(cli, ["dist"])38    assert not result.exception39    assert result.output == "Count: 1\nCount: 42\n"404142def test_auto_shorthelp(runner):43    @click.group()44    def cli():45        pass4647    @cli.command()48    def short():49        """This is a short text."""5051    @cli.command()52    def special_chars():53        """Login and store the token in ~/.netrc."""5455    @cli.command()56    def long():57        """This is a long text that is too long to show as short help58        and will be truncated instead."""5960    result = runner.invoke(cli, ["--help"])61    assert (62        re.search(63            r"Commands:\n\s+"64            r"long\s+This is a long text that is too long to show as short help"65            r"\.\.\.\n\s+"66            r"short\s+This is a short text\.\n\s+"67            r"special-chars\s+Login and store the token in ~/.netrc\.\s*",68            result.output,69        )70        is not None71    )727374def test_no_args_is_help(runner):75    @click.command(no_args_is_help=True)76    def cli():77        pass7879    result = runner.invoke(cli, [])80    assert result.exit_code == 081    assert "Show this message and exit." in result.output828384def test_default_maps(runner):85    @click.group()86    def cli():87        pass8889    @cli.command()90    @click.option("--name", default="normal")91    def foo(name):92        click.echo(name)9394    result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})9596    assert not result.exception97    assert result.output == "changed\n"9899100def test_group_with_args(runner):101    @click.group()102    @click.argument("obj")103    def cli(obj):104        click.echo(f"obj={obj}")105106    @cli.command()107    def move():108        click.echo("move")109110    result = runner.invoke(cli, [])111    assert result.exit_code == 0112    assert "Show this message and exit." in result.output113114    result = runner.invoke(cli, ["obj1"])115    assert result.exit_code == 2116    assert "Error: Missing command." in result.output117118    result = runner.invoke(cli, ["obj1", "--help"])119    assert result.exit_code == 0120    assert "Show this message and exit." in result.output121122    result = runner.invoke(cli, ["obj1", "move"])123    assert result.exit_code == 0124    assert result.output == "obj=obj1\nmove\n"125126127def test_base_command(runner):128    import optparse129130    @click.group()131    def cli():132        pass133134    class OptParseCommand(click.BaseCommand):135        def __init__(self, name, parser, callback):136            click.BaseCommand.__init__(self, name)137            self.parser = parser138            self.callback = callback139140        def parse_args(self, ctx, args):141            try:142                opts, args = parser.parse_args(args)143            except Exception as e:144                ctx.fail(str(e))145            ctx.args = args146            ctx.params = vars(opts)147148        def get_usage(self, ctx):149            return self.parser.get_usage()150151        def get_help(self, ctx):152            return self.parser.format_help()153154        def invoke(self, ctx):155            ctx.invoke(self.callback, ctx.args, **ctx.params)156157    parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]")158    parser.add_option(159        "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"160    )161    parser.add_option(162        "-q",163        "--quiet",164        action="store_false",165        dest="verbose",166        default=True,167        help="don't print status messages to stdout",168    )169170    def test_callback(args, filename, verbose):171        click.echo(" ".join(args))172        click.echo(filename)173        click.echo(verbose)174175    cli.add_command(OptParseCommand("test", parser, test_callback))176177    result = runner.invoke(178        cli, ["test", "-f", "test.txt", "-q", "whatever.txt", "whateverelse.txt"]179    )180    assert not result.exception181    assert result.output.splitlines() == [182        "whatever.txt whateverelse.txt",183        "test.txt",184        "False",185    ]186187    result = runner.invoke(cli, ["test", "--help"])188    assert not result.exception189    assert result.output.splitlines() == [190        "Usage: foo test [OPTIONS]",191        "",192        "Options:",193        "  -h, --help            show this help message and exit",194        "  -f FILE, --file=FILE  write report to FILE",195        "  -q, --quiet           don't print status messages to stdout",196    ]197198199def test_object_propagation(runner):200    for chain in False, True:201202        @click.group(chain=chain)203        @click.option("--debug/--no-debug", default=False)204        @click.pass_context205        def cli(ctx, debug):206            if ctx.obj is None:207                ctx.obj = {}208            ctx.obj["DEBUG"] = debug209210        @cli.command()211        @click.pass_context212        def sync(ctx):213            click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")214215        result = runner.invoke(cli, ["sync"])216        assert result.exception is None217        assert result.output == "Debug is off\n"218219220def test_other_command_invoke_with_defaults(runner):221    @click.command()222    @click.pass_context223    def cli(ctx):224        return ctx.invoke(other_cmd)225226    @click.command()227    @click.option("--foo", type=click.INT, default=42)228    @click.pass_context229    def other_cmd(ctx, foo):230        assert ctx.info_name == "other-cmd"231        click.echo(foo)232233    result = runner.invoke(cli, [])234    assert not result.exception235    assert result.output == "42\n"236237238def test_invoked_subcommand(runner):239    @click.group(invoke_without_command=True)240    @click.pass_context241    def cli(ctx):242        if ctx.invoked_subcommand is None:243            click.echo("no subcommand, use default")244            ctx.invoke(sync)245        else:246            click.echo("invoke subcommand")247248    @cli.command()249    def sync():250        click.echo("in subcommand")251252    result = runner.invoke(cli, ["sync"])253    assert not result.exception254    assert result.output == "invoke subcommand\nin subcommand\n"255256    result = runner.invoke(cli)257    assert not result.exception258    assert result.output == "no subcommand, use default\nin subcommand\n"259260261def test_aliased_command_canonical_name(runner):262    class AliasedGroup(click.Group):263        def get_command(self, ctx, cmd_name):264            return push265266    cli = AliasedGroup()267268    @cli.command()269    def push():270        click.echo("push command")271272    result = runner.invoke(cli, ["pu", "--help"])273    assert not result.exception274    assert result.output.startswith("Usage: root push [OPTIONS]")275276277def test_unprocessed_options(runner):278    @click.command(context_settings=dict(ignore_unknown_options=True))279    @click.argument("args", nargs=-1, type=click.UNPROCESSED)280    @click.option("--verbose", "-v", count=True)281    def cli(verbose, args):282        click.echo(f"Verbosity: {verbose}")283        click.echo(f"Args: {'|'.join(args)}")284285    result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])286    assert not result.exception287    assert result.output.splitlines() == [288        "Verbosity: 4",289        "Args: -foo|-x|--muhaha|x|y|-x",290    ]291292293def test_deprecated_in_help_messages(runner):294    @click.command(deprecated=True)295    def cmd_with_help():296        """CLI HELP"""297        pass298299    result = runner.invoke(cmd_with_help, ["--help"])300    assert "(DEPRECATED)" in result.output301302    @click.command(deprecated=True)303    def cmd_without_help():304        pass305306    result = runner.invoke(cmd_without_help, ["--help"])307    assert "(DEPRECATED)" in result.output308309310def test_deprecated_in_invocation(runner):311    @click.command(deprecated=True)312    def deprecated_cmd():313        pass314315    result = runner.invoke(deprecated_cmd)316    assert "DeprecationWarning:" in result.output