Skip to content
Myr

test_commands.py

This file

Path

tests/test_commands.py

254 lines · 6.8 KiB · Python

Last changed by

Merge branch '3.x-maintenance'Armin Ronacherbefore adoption733d5fa

History of this file

Take it

1# -*- coding: utf-8 -*-2import re3import 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_invoke_invalid_custom_error(runner):23    @click.command()24    @click.pass_context25    def cli(ctx):26        return ctx.invoke(other_cmd, 42)2728    @click.command()29    @click.argument('arg', type=click.INT)30    def other_cmd(arg):31        click.echo(arg)3233    result = runner.invoke(cli, [])34    assert isinstance(result.exception, RuntimeError)35    assert 'upgrading-to-3.2' in str(result.exception)36    assert click.__version__ < '5.0'373839def test_other_command_forward(runner):40    cli = click.Group()4142    @cli.command()43    @click.option('--count', default=1)44    def test(count):45        click.echo('Count: %d' % count)4647    @cli.command()48    @click.option('--count', default=1)49    @click.pass_context50    def dist(ctx, count):51        ctx.forward(test)52        ctx.invoke(test, count=42)5354    result = runner.invoke(cli, ['dist'])55    assert not result.exception56    assert result.output == 'Count: 1\nCount: 42\n'575859def test_auto_shorthelp(runner):60    @click.group()61    def cli():62        pass6364    @cli.command()65    def short():66        """This is a short text."""6768    @cli.command()69    def special_chars():70        """Login and store the token in ~/.netrc."""7172    @cli.command()73    def long():74        """This is a long text that is too long to show as short help75        and will be truncated instead."""7677    result = runner.invoke(cli, ['--help'])78    assert re.search(79        r'Commands:\n\s+'80        r'long\s+This is a long text that is too long to show\.\.\.\n\s+'81        r'short\s+This is a short text\.\n\s+'82        r'special_chars\s+Login and store the token in ~/.netrc\.\s*',83        result.output) is not None848586def test_default_maps(runner):87    @click.group()88    def cli():89        pass9091    @cli.command()92    @click.option('--name', default='normal')93    def foo(name):94        click.echo(name)9596    result = runner.invoke(cli, ['foo'], default_map={97        'foo': {'name': 'changed'}98    })99100    assert not result.exception101    assert result.output == 'changed\n'102103104def test_group_with_args(runner):105    @click.group()106    @click.argument('obj')107    def cli(obj):108        click.echo('obj=%s' % obj)109110    @cli.command()111    def move():112        click.echo('move')113114    result = runner.invoke(cli, [])115    assert result.exit_code == 0116    assert 'Show this message and exit.' in result.output117118    result = runner.invoke(cli, ['obj1'])119    assert result.exit_code == 2120    assert 'Error: Missing command.' in result.output121122    result = runner.invoke(cli, ['obj1', '--help'])123    assert result.exit_code == 0124    assert 'Show this message and exit.' in result.output125126    result = runner.invoke(cli, ['obj1', 'move'])127    assert result.exit_code == 0128    assert result.output == 'obj=obj1\nmove\n'129130131def test_base_command(runner):132    import optparse133134    @click.group()135    def cli():136        pass137138    class OptParseCommand(click.BaseCommand):139140        def __init__(self, name, parser, callback):141            click.BaseCommand.__init__(self, name)142            self.parser = parser143            self.callback = callback144145        def parse_args(self, ctx, args):146            try:147                opts, args = parser.parse_args(args)148            except Exception as e:149                ctx.fail(str(e))150            ctx.args = args151            ctx.params = vars(opts)152153        def get_usage(self, ctx):154            return self.parser.get_usage()155156        def get_help(self, ctx):157            return self.parser.format_help()158159        def invoke(self, ctx):160            ctx.invoke(self.callback, ctx.args, **ctx.params)161162    parser = optparse.OptionParser(usage='Usage: foo test [OPTIONS]')163    parser.add_option("-f", "--file", dest="filename",164                      help="write report to FILE", metavar="FILE")165    parser.add_option("-q", "--quiet",166                      action="store_false", dest="verbose", default=True,167                      help="don't print status messages to stdout")168169    def test_callback(args, filename, verbose):170        click.echo(' '.join(args))171        click.echo(filename)172        click.echo(verbose)173    cli.add_command(OptParseCommand('test', parser, test_callback))174175    result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',176                                 'whatever.txt', 'whateverelse.txt'])177    assert not result.exception178    assert result.output.splitlines() == [179        'whatever.txt whateverelse.txt',180        'test.txt',181        'False',182    ]183184    result = runner.invoke(cli, ['test', '--help'])185    assert not result.exception186    assert result.output.splitlines() == [187        'Usage: foo test [OPTIONS]',188        '',189        'Options:',190        '  -h, --help            show this help message and exit',191        '  -f FILE, --file=FILE  write report to FILE',192        '  -q, --quiet           don\'t print status messages to stdout',193    ]194195196def test_object_propagation(runner):197    for chain in False, True:198        @click.group(chain=chain)199        @click.option('--debug/--no-debug', default=False)200        @click.pass_context201        def cli(ctx, debug):202            if ctx.obj is None:203                ctx.obj = {}204            ctx.obj['DEBUG'] = debug205206        @cli.command()207        @click.pass_context208        def sync(ctx):209            click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))210211        result = runner.invoke(cli, ['sync'])212        assert result.exception is None213        assert result.output == 'Debug is off\n'214215216def test_other_command_invoke_with_defaults(runner):217    @click.command()218    @click.pass_context219    def cli(ctx):220        return ctx.invoke(other_cmd)221222    @click.command()223    @click.option('--foo', type=click.INT, default=42)224    @click.pass_context225    def other_cmd(ctx, foo):226        assert ctx.info_name == 'other_cmd'227        click.echo(foo)228229    result = runner.invoke(cli, [])230    assert not result.exception231    assert result.output == '42\n'232233234def test_invoked_subcommand(runner):235    @click.group(invoke_without_command=True)236    @click.pass_context237    def cli(ctx):238        if ctx.invoked_subcommand is None:239            click.echo('no subcommand, use default')240            ctx.invoke(sync)241        else:242            click.echo('invoke subcommand')243244    @cli.command()245    def sync():246        click.echo('in subcommand')247248    result = runner.invoke(cli, ['sync'])249    assert not result.exception250    assert result.output == 'invoke subcommand\nin subcommand\n'251252    result = runner.invoke(cli)253    assert not result.exception254    assert result.output == 'no subcommand, use default\nin subcommand\n'