test_commands.py
This file
Path
tests/test_commands.py
352 lines · 9.3 KiB · Python
Last changed by
Merge branch '8.0.x'David Lordbefore adoption29df879
History of this fileTake it
The walk stopped after 200 commits: lines older than 567929f point at it.
Merge branch '7.x'David Lordbefore adoption567929f
lines 1–27why, one step back1import 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):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 28why, one step back28 click.echo(f"Count: {count:d}")Merge branch '7.x'David Lordbefore adoption567929f
lines 29–41why, one step back2930 @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"4041Merge pull request #1840 from MLH-Fellowship/context-forwardDavid Lordbefore adoptione3594e7
lines 42–63why, one step back42def test_forwarded_params_consistency(runner):43 cli = click.Group()4445 @cli.command()46 @click.option("-a")47 @click.pass_context48 def first(ctx, **kwargs):49 click.echo(f"{ctx.params}")5051 @cli.command()52 @click.option("-a")53 @click.option("-b")54 @click.pass_context55 def second(ctx, **kwargs):56 click.echo(f"{ctx.params}")57 ctx.forward(first)5859 result = runner.invoke(cli, ["second", "-a", "foo", "-b", "bar"])60 assert not result.exception61 assert result.output == "{'a': 'foo', 'b': 'bar'}\n{'a': 'foo', 'b': 'bar'}\n"6263Merge branch '7.x'David Lordbefore adoption567929f
lines 64–125why, one step back64def test_auto_shorthelp(runner):65 @click.group()66 def cli():67 pass6869 @cli.command()70 def short():71 """This is a short text."""7273 @cli.command()74 def special_chars():75 """Login and store the token in ~/.netrc."""7677 @cli.command()78 def long():79 """This is a long text that is too long to show as short help80 and will be truncated instead."""8182 result = runner.invoke(cli, ["--help"])83 assert (84 re.search(85 r"Commands:\n\s+"86 r"long\s+This is a long text that is too long to show as short help"87 r"\.\.\.\n\s+"88 r"short\s+This is a short text\.\n\s+"89 r"special-chars\s+Login and store the token in ~/.netrc\.\s*",90 result.output,91 )92 is not None93 )949596def test_no_args_is_help(runner):97 @click.command(no_args_is_help=True)98 def cli():99 pass100101 result = runner.invoke(cli, [])102 assert result.exit_code == 0103 assert "Show this message and exit." in result.output104105106def test_default_maps(runner):107 @click.group()108 def cli():109 pass110111 @cli.command()112 @click.option("--name", default="normal")113 def foo(name):114 click.echo(name)115116 result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})117118 assert not result.exception119 assert result.output == "changed\n"120121122def test_group_with_args(runner):123 @click.group()124 @click.argument("obj")125 def cli(obj):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 126why, one step back126 click.echo(f"obj={obj}")Merge branch '7.x'David Lordbefore adoption567929f
lines 127–157why, one step back127128 @cli.command()129 def move():130 click.echo("move")131132 result = runner.invoke(cli, [])133 assert result.exit_code == 0134 assert "Show this message and exit." in result.output135136 result = runner.invoke(cli, ["obj1"])137 assert result.exit_code == 2138 assert "Error: Missing command." in result.output139140 result = runner.invoke(cli, ["obj1", "--help"])141 assert result.exit_code == 0142 assert "Show this message and exit." in result.output143144 result = runner.invoke(cli, ["obj1", "move"])145 assert result.exit_code == 0146 assert result.output == "obj=obj1\nmove\n"147148149def test_base_command(runner):150 import optparse151152 @click.group()153 def cli():154 pass155156 class OptParseCommand(click.BaseCommand):157 def __init__(self, name, parser, callback):Merge pull request #938 from txomon/feature/make-extendableDavid Lordbefore adoptiond75ea33
line 158why, one step back158 super().__init__(name)Merge branch '7.x'David Lordbefore adoption567929f
lines 159–234why, one step back159 self.parser = parser160 self.callback = callback161162 def parse_args(self, ctx, args):163 try:164 opts, args = parser.parse_args(args)165 except Exception as e:166 ctx.fail(str(e))167 ctx.args = args168 ctx.params = vars(opts)169170 def get_usage(self, ctx):171 return self.parser.get_usage()172173 def get_help(self, ctx):174 return self.parser.format_help()175176 def invoke(self, ctx):177 ctx.invoke(self.callback, ctx.args, **ctx.params)178179 parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]")180 parser.add_option(181 "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"182 )183 parser.add_option(184 "-q",185 "--quiet",186 action="store_false",187 dest="verbose",188 default=True,189 help="don't print status messages to stdout",190 )191192 def test_callback(args, filename, verbose):193 click.echo(" ".join(args))194 click.echo(filename)195 click.echo(verbose)196197 cli.add_command(OptParseCommand("test", parser, test_callback))198199 result = runner.invoke(200 cli, ["test", "-f", "test.txt", "-q", "whatever.txt", "whateverelse.txt"]201 )202 assert not result.exception203 assert result.output.splitlines() == [204 "whatever.txt whateverelse.txt",205 "test.txt",206 "False",207 ]208209 result = runner.invoke(cli, ["test", "--help"])210 assert not result.exception211 assert result.output.splitlines() == [212 "Usage: foo test [OPTIONS]",213 "",214 "Options:",215 " -h, --help show this help message and exit",216 " -f FILE, --file=FILE write report to FILE",217 " -q, --quiet don't print status messages to stdout",218 ]219220221def test_object_propagation(runner):222 for chain in False, True:223224 @click.group(chain=chain)225 @click.option("--debug/--no-debug", default=False)226 @click.pass_context227 def cli(ctx, debug):228 if ctx.obj is None:229 ctx.obj = {}230 ctx.obj["DEBUG"] = debug231232 @cli.command()233 @click.pass_context234 def sync(ctx):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 235why, one step back235 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")Merge branch '7.x'David Lordbefore adoption567929f
lines 236–282why, one step back236237 result = runner.invoke(cli, ["sync"])238 assert result.exception is None239 assert result.output == "Debug is off\n"240241242def test_other_command_invoke_with_defaults(runner):243 @click.command()244 @click.pass_context245 def cli(ctx):246 return ctx.invoke(other_cmd)247248 @click.command()249 @click.option("--foo", type=click.INT, default=42)250 @click.pass_context251 def other_cmd(ctx, foo):252 assert ctx.info_name == "other-cmd"253 click.echo(foo)254255 result = runner.invoke(cli, [])256 assert not result.exception257 assert result.output == "42\n"258259260def test_invoked_subcommand(runner):261 @click.group(invoke_without_command=True)262 @click.pass_context263 def cli(ctx):264 if ctx.invoked_subcommand is None:265 click.echo("no subcommand, use default")266 ctx.invoke(sync)267 else:268 click.echo("invoke subcommand")269270 @cli.command()271 def sync():272 click.echo("in subcommand")273274 result = runner.invoke(cli, ["sync"])275 assert not result.exception276 assert result.output == "invoke subcommand\nin subcommand\n"277278 result = runner.invoke(cli)279 assert not result.exception280 assert result.output == "no subcommand, use default\nin subcommand\n"281282Merge pull request #1615 from MLH-Fellowship/issue1422David Lordbefore adoptionfb1ca91
lines 283–287why, one step back283def test_aliased_command_canonical_name(runner):284 class AliasedGroup(click.Group):285 def get_command(self, ctx, cmd_name):286 return push287Merge branch '8.0.x'David Lordbefore adoption29df879
lines 288–291why, one step back288 def resolve_command(self, ctx, args):289 _, command, args = super().resolve_command(ctx, args)290 return command.name, command, args291Merge pull request #1615 from MLH-Fellowship/issue1422David Lordbefore adoptionfb1ca91
lines 292–300why, one step back292 cli = AliasedGroup()293294 @cli.command()295 def push():296 click.echo("push command")297298 result = runner.invoke(cli, ["pu", "--help"])299 assert not result.exception300 assert result.output.startswith("Usage: root push [OPTIONS]")Merge branch '8.0.x'David Lordbefore adoption29df879
lines 301–310why, one step back301302303def test_group_add_command_name(runner):304 cli = click.Group("cli")305 cmd = click.Command("a", params=[click.Option(["-x"], required=True)])306 cli.add_command(cmd, "b")307 # Check that the command is accessed through the registered name,308 # not the original name.309 result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})310 assert result.exit_code == 0Merge pull request #1615 from MLH-Fellowship/issue1422David Lordbefore adoptionfb1ca91
lines 311–312why, one step back311312Merge branch '7.x'David Lordbefore adoption567929f
lines 313–317why, one step back313def test_unprocessed_options(runner):314 @click.command(context_settings=dict(ignore_unknown_options=True))315 @click.argument("args", nargs=-1, type=click.UNPROCESSED)316 @click.option("--verbose", "-v", count=True)317 def cli(verbose, args):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
lines 318–319why, one step back318 click.echo(f"Verbosity: {verbose}")319 click.echo(f"Args: {'|'.join(args)}")Merge branch '7.x'David Lordbefore adoption567929f
lines 320–335why, one step back320321 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])322 assert not result.exception323 assert result.output.splitlines() == [324 "Verbosity: 4",325 "Args: -foo|-x|--muhaha|x|y|-x",326 ]327328329def test_deprecated_in_help_messages(runner):330 @click.command(deprecated=True)331 def cmd_with_help():332 """CLI HELP"""333 pass334335 result = runner.invoke(cmd_with_help, ["--help"])Merge pull request #1816 from BALaka-18/fix-deprecation-noticeDavid Lordbefore adoption08583da
line 336why, one step back336 assert "(Deprecated)" in result.outputMerge branch '7.x'David Lordbefore adoption567929f
lines 337–342why, one step back337338 @click.command(deprecated=True)339 def cmd_without_help():340 pass341342 result = runner.invoke(cmd_without_help, ["--help"])Merge pull request #1816 from BALaka-18/fix-deprecation-noticeDavid Lordbefore adoption08583da
line 343why, one step back343 assert "(Deprecated)" in result.outputMerge branch '7.x'David Lordbefore adoption567929f
lines 344–352why, one step back344345346def test_deprecated_in_invocation(runner):347 @click.command(deprecated=True)348 def deprecated_cmd():349 pass350351 result = runner.invoke(deprecated_cmd)352 assert "DeprecationWarning:" in result.output