test_commands.py
This file
Path
tests/test_commands.py
255 lines · 6.9 KiB · Python
Last changed by
Removed deprecated functionality.Armin Ronacherbefore adoption0d9731e
History of this fileTake 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_forward(runner):23 cli = click.Group()2425 @cli.command()26 @click.option('--count', default=1)27 def test(count):28 click.echo('Count: %d' % count)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 re.search(62 r'Commands:\n\s+'63 r'long\s+This is a long text that is too long to show\.\.\.\n\s+'64 r'short\s+This is a short text\.\n\s+'65 r'special_chars\s+Login and store the token in ~/.netrc\.\s*',66 result.output) is not None676869def test_default_maps(runner):70 @click.group()71 def cli():72 pass7374 @cli.command()75 @click.option('--name', default='normal')76 def foo(name):77 click.echo(name)7879 result = runner.invoke(cli, ['foo'], default_map={80 'foo': {'name': 'changed'}81 })8283 assert not result.exception84 assert result.output == 'changed\n'858687def test_group_with_args(runner):88 @click.group()89 @click.argument('obj')90 def cli(obj):91 click.echo('obj=%s' % obj)9293 @cli.command()94 def move():95 click.echo('move')9697 result = runner.invoke(cli, [])98 assert result.exit_code == 099 assert 'Show this message and exit.' in result.output100101 result = runner.invoke(cli, ['obj1'])102 assert result.exit_code == 2103 assert 'Error: Missing command.' in result.output104105 result = runner.invoke(cli, ['obj1', '--help'])106 assert result.exit_code == 0107 assert 'Show this message and exit.' in result.output108109 result = runner.invoke(cli, ['obj1', 'move'])110 assert result.exit_code == 0111 assert result.output == 'obj=obj1\nmove\n'112113114def test_base_command(runner):115 import optparse116117 @click.group()118 def cli():119 pass120121 class OptParseCommand(click.BaseCommand):122123 def __init__(self, name, parser, callback):124 click.BaseCommand.__init__(self, name)125 self.parser = parser126 self.callback = callback127128 def parse_args(self, ctx, args):129 try:130 opts, args = parser.parse_args(args)131 except Exception as e:132 ctx.fail(str(e))133 ctx.args = args134 ctx.params = vars(opts)135136 def get_usage(self, ctx):137 return self.parser.get_usage()138139 def get_help(self, ctx):140 return self.parser.format_help()141142 def invoke(self, ctx):143 ctx.invoke(self.callback, ctx.args, **ctx.params)144145 parser = optparse.OptionParser(usage='Usage: foo test [OPTIONS]')146 parser.add_option("-f", "--file", dest="filename",147 help="write report to FILE", metavar="FILE")148 parser.add_option("-q", "--quiet",149 action="store_false", dest="verbose", default=True,150 help="don't print status messages to stdout")151152 def test_callback(args, filename, verbose):153 click.echo(' '.join(args))154 click.echo(filename)155 click.echo(verbose)156 cli.add_command(OptParseCommand('test', parser, test_callback))157158 result = runner.invoke(cli, ['test', '-f', 'test.txt', '-q',159 'whatever.txt', 'whateverelse.txt'])160 assert not result.exception161 assert result.output.splitlines() == [162 'whatever.txt whateverelse.txt',163 'test.txt',164 'False',165 ]166167 result = runner.invoke(cli, ['test', '--help'])168 assert not result.exception169 assert result.output.splitlines() == [170 'Usage: foo test [OPTIONS]',171 '',172 'Options:',173 ' -h, --help show this help message and exit',174 ' -f FILE, --file=FILE write report to FILE',175 ' -q, --quiet don\'t print status messages to stdout',176 ]177178179def test_object_propagation(runner):180 for chain in False, True:181 @click.group(chain=chain)182 @click.option('--debug/--no-debug', default=False)183 @click.pass_context184 def cli(ctx, debug):185 if ctx.obj is None:186 ctx.obj = {}187 ctx.obj['DEBUG'] = debug188189 @cli.command()190 @click.pass_context191 def sync(ctx):192 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))193194 result = runner.invoke(cli, ['sync'])195 assert result.exception is None196 assert result.output == 'Debug is off\n'197198199def test_other_command_invoke_with_defaults(runner):200 @click.command()201 @click.pass_context202 def cli(ctx):203 return ctx.invoke(other_cmd)204205 @click.command()206 @click.option('--foo', type=click.INT, default=42)207 @click.pass_context208 def other_cmd(ctx, foo):209 assert ctx.info_name == 'other_cmd'210 click.echo(foo)211212 result = runner.invoke(cli, [])213 assert not result.exception214 assert result.output == '42\n'215216217def test_invoked_subcommand(runner):218 @click.group(invoke_without_command=True)219 @click.pass_context220 def cli(ctx):221 if ctx.invoked_subcommand is None:222 click.echo('no subcommand, use default')223 ctx.invoke(sync)224 else:225 click.echo('invoke subcommand')226227 @cli.command()228 def sync():229 click.echo('in subcommand')230231 result = runner.invoke(cli, ['sync'])232 assert not result.exception233 assert result.output == 'invoke subcommand\nin subcommand\n'234235 result = runner.invoke(cli)236 assert not result.exception237 assert result.output == 'no subcommand, use default\nin subcommand\n'238239240def test_unprocessed_options(runner):241 @click.command(context_settings=dict(242 ignore_unknown_options=True243 ))244 @click.argument('args', nargs=-1, type=click.UNPROCESSED)245 @click.option('--verbose', '-v', count=True)246 def cli(verbose, args):247 click.echo('Verbosity: %s' % verbose)248 click.echo('Args: %s' % '|'.join(args))249250 result = runner.invoke(cli, ['-foo', '-vvvvx', '--muhaha', 'x', 'y', '-x'])251 assert not result.exception252 assert result.output.splitlines() == [253 'Verbosity: 4',254 'Args: -foo|-x|--muhaha|x|y|-x',255 ]