Skip to content
Myr

test_commands.py

This file

Path

tests/test_commands.py

293 lines · 7.8 KiB · Python

Last changed by

Merge pull request #1167 from sirosen/no-args-help-commandDavid Lordbefore adoption43eb54d

History of this file

Take it

1# -*- coding: utf-8 -*-2import re34import click5import pytest678def test_other_command_invoke(runner):9    @click.command()10    @click.pass_context11    def cli(ctx):12        return ctx.invoke(other_cmd, arg=42)1314    @click.command()15    @click.argument('arg', type=click.INT)16    def other_cmd(arg):17        click.echo(arg)1819    result = runner.invoke(cli, [])20    assert not result.exception21    assert result.output == '42\n'222324def test_other_command_forward(runner):25    cli = click.Group()2627    @cli.command()28    @click.option('--count', default=1)29    def test(count):30        click.echo('Count: %d' % count)3132    @cli.command()33    @click.option('--count', default=1)34    @click.pass_context35    def dist(ctx, count):36        ctx.forward(test)37        ctx.invoke(test, count=42)3839    result = runner.invoke(cli, ['dist'])40    assert not result.exception41    assert result.output == 'Count: 1\nCount: 42\n'424344def test_auto_shorthelp(runner):45    @click.group()46    def cli():47        pass4849    @cli.command()50    def short():51        """This is a short text."""5253    @cli.command()54    def special_chars():55        """Login and store the token in ~/.netrc."""5657    @cli.command()58    def long():59        """This is a long text that is too long to show as short help60        and will be truncated instead."""6162    result = runner.invoke(cli, ['--help'])63    assert re.search(64        r'Commands:\n\s+'65        r'long\s+This is a long text that is too long to show as short help\.\.\.\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) is not None697071def test_no_args_is_help(runner):72    @click.command(no_args_is_help=True)73    def cli():74        pass7576    result = runner.invoke(cli, [])77    assert result.exit_code == 078    assert 'Show this message and exit.' in result.output798081def test_default_maps(runner):82    @click.group()83    def cli():84        pass8586    @cli.command()87    @click.option('--name', default='normal')88    def foo(name):89        click.echo(name)9091    result = runner.invoke(cli, ['foo'], default_map={92        'foo': {'name': 'changed'}93    })9495    assert not result.exception96    assert result.output == 'changed\n'979899def test_group_with_args(runner):100    @click.group()101    @click.argument('obj')102    def cli(obj):103        click.echo('obj=%s' % obj)104105    @cli.command()106    def move():107        click.echo('move')108109    result = runner.invoke(cli, [])110    assert result.exit_code == 0111    assert 'Show this message and exit.' in result.output112113    result = runner.invoke(cli, ['obj1'])114    assert result.exit_code == 2115    assert 'Error: Missing command.' in result.output116117    result = runner.invoke(cli, ['obj1', '--help'])118    assert result.exit_code == 0119    assert 'Show this message and exit.' in result.output120121    result = runner.invoke(cli, ['obj1', 'move'])122    assert result.exit_code == 0123    assert result.output == 'obj=obj1\nmove\n'124125126def test_base_command(runner):127    import optparse128129    @click.group()130    def cli():131        pass132133    class OptParseCommand(click.BaseCommand):134135        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("-f", "--file", dest="filename",159                      help="write report to FILE", metavar="FILE")160    parser.add_option("-q", "--quiet",161                      action="store_false", dest="verbose", default=True,162                      help="don't print status messages to stdout")163164    def test_callback(args, filename, verbose):165        click.echo(' '.join(args))166        click.echo(filename)167        click.echo(verbose)168    cli.add_command(OptParseCommand('test', parser, test_callback))169170    result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',171                                 'whatever.txt', 'whateverelse.txt'])172    assert not result.exception173    assert result.output.splitlines() == [174        'whatever.txt whateverelse.txt',175        'test.txt',176        'False',177    ]178179    result = runner.invoke(cli, ['test', '--help'])180    assert not result.exception181    assert result.output.splitlines() == [182        'Usage: foo test [OPTIONS]',183        '',184        'Options:',185        '  -h, --help            show this help message and exit',186        '  -f FILE, --file=FILE  write report to FILE',187        '  -q, --quiet           don\'t print status messages to stdout',188    ]189190191def test_object_propagation(runner):192    for chain in False, True:193        @click.group(chain=chain)194        @click.option('--debug/--no-debug', default=False)195        @click.pass_context196        def cli(ctx, debug):197            if ctx.obj is None:198                ctx.obj = {}199            ctx.obj['DEBUG'] = debug200201        @cli.command()202        @click.pass_context203        def sync(ctx):204            click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))205206        result = runner.invoke(cli, ['sync'])207        assert result.exception is None208        assert result.output == 'Debug is off\n'209210211def test_other_command_invoke_with_defaults(runner):212    @click.command()213    @click.pass_context214    def cli(ctx):215        return ctx.invoke(other_cmd)216217    @click.command()218    @click.option('--foo', type=click.INT, default=42)219    @click.pass_context220    def other_cmd(ctx, foo):221        assert ctx.info_name == 'other-cmd'222        click.echo(foo)223224    result = runner.invoke(cli, [])225    assert not result.exception226    assert result.output == '42\n'227228229def test_invoked_subcommand(runner):230    @click.group(invoke_without_command=True)231    @click.pass_context232    def cli(ctx):233        if ctx.invoked_subcommand is None:234            click.echo('no subcommand, use default')235            ctx.invoke(sync)236        else:237            click.echo('invoke subcommand')238239    @cli.command()240    def sync():241        click.echo('in subcommand')242243    result = runner.invoke(cli, ['sync'])244    assert not result.exception245    assert result.output == 'invoke subcommand\nin subcommand\n'246247    result = runner.invoke(cli)248    assert not result.exception249    assert result.output == 'no subcommand, use default\nin subcommand\n'250251252def test_unprocessed_options(runner):253    @click.command(context_settings=dict(254        ignore_unknown_options=True255    ))256    @click.argument('args', nargs=-1, type=click.UNPROCESSED)257    @click.option('--verbose', '-v', count=True)258    def cli(verbose, args):259        click.echo('Verbosity: %s' % verbose)260        click.echo('Args: %s' % '|'.join(args))261262    result = runner.invoke(cli, ['-foo', '-vvvvx', '--muhaha', 'x', 'y', '-x'])263    assert not result.exception264    assert result.output.splitlines() == [265        'Verbosity: 4',266        'Args: -foo|-x|--muhaha|x|y|-x',267    ]268269270def test_deprecated_in_help_messages(runner):271    @click.command(deprecated=True)272    def cmd_with_help():273        """CLI HELP"""274        pass275276    result = runner.invoke(cmd_with_help, ['--help'])277    assert '(DEPRECATED)' in result.output278279    @click.command(deprecated=True)280    def cmd_without_help():281        pass282283    result = runner.invoke(cmd_without_help, ['--help'])284    assert '(DEPRECATED)' in result.output285286287def test_deprecated_in_invocation(runner):288    @click.command(deprecated=True)289    def deprecated_cmd():290        debug()291292    result = runner.invoke(deprecated_cmd)293    assert 'DeprecationWarning:' in result.output