Debian Codegraph @

tests/test_commands.py

raw
1 import re
2
3 import pytest
4
5 import click
6
7
8 def test_other_command_invoke(runner):
9 @click.command()
10 @click.pass_context
11 def cli(ctx):
12 return ctx.invoke(other_cmd, arg=42)
13
14 @click.command()
15 @click.argument("arg", type=click.INT)
16 def other_cmd(arg):
17 click.echo(arg)
18
19 result = runner.invoke(cli, [])
20 assert not result.exception
21 assert result.output == "42\n"
22
23
24 def test_other_command_forward(runner):
25 cli = click.Group()
26
27 @cli.command()
28 @click.option("--count", default=1)
29 def test(count):
30 click.echo(f"Count: {count:d}")
31
32 @cli.command()
33 @click.option("--count", default=1)
34 @click.pass_context
35 def dist(ctx, count):
36 ctx.forward(test)
37 ctx.invoke(test, count=42)
38
39 result = runner.invoke(cli, ["dist"])
40 assert not result.exception
41 assert result.output == "Count: 1\nCount: 42\n"
42
43
44 def test_forwarded_params_consistency(runner):
45 cli = click.Group()
46
47 @cli.command()
48 @click.option("-a")
49 @click.pass_context
50 def first(ctx, **kwargs):
51 click.echo(f"{ctx.params}")
52
53 @cli.command()
54 @click.option("-a")
55 @click.option("-b")
56 @click.pass_context
57 def second(ctx, **kwargs):
58 click.echo(f"{ctx.params}")
59 ctx.forward(first)
60
61 result = runner.invoke(cli, ["second", "-a", "foo", "-b", "bar"])
62 assert not result.exception
63 assert result.output == "{'a': 'foo', 'b': 'bar'}\n{'a': 'foo', 'b': 'bar'}\n"
64
65
66 def test_auto_shorthelp(runner):
67 @click.group()
68 def cli():
69 pass
70
71 @cli.command()
72 def short():
73 """This is a short text."""
74
75 @cli.command()
76 def special_chars():
77 """Login and store the token in ~/.netrc."""
78
79 @cli.command()
80 def long():
81 """This is a long text that is too long to show as short help
82 and will be truncated instead."""
83
84 result = runner.invoke(cli, ["--help"])
85 assert (
86 re.search(
87 r"Commands:\n\s+"
88 r"long\s+This is a long text that is too long to show as short help"
89 r"\.\.\.\n\s+"
90 r"short\s+This is a short text\.\n\s+"
91 r"special-chars\s+Login and store the token in ~/.netrc\.\s*",
92 result.output,
93 )
94 is not None
95 )
96
97
98 def test_command_no_args_is_help(runner):
99 result = runner.invoke(click.Command("test", no_args_is_help=True))
100 assert result.exit_code == 2
101 assert "Show this message and exit." in result.output
102
103
104 def test_default_maps(runner):
105 @click.group()
106 def cli():
107 pass
108
109 @cli.command()
110 @click.option("--name", default="normal")
111 def foo(name):
112 click.echo(name)
113
114 result = runner.invoke(cli, ["foo"], default_map={"foo": {"name": "changed"}})
115
116 assert not result.exception
117 assert result.output == "changed\n"
118
119
120 @pytest.mark.parametrize(
121 ("args", "exit_code", "expect"),
122 [
123 (["obj1"], 2, "Error: Missing command."),
124 (["obj1", "--help"], 0, "Show this message and exit."),
125 (["obj1", "move"], 0, "obj=obj1\nmove\n"),
126 ([], 2, "Show this message and exit."),
127 ],
128 )
129 def test_group_with_args(runner, args, exit_code, expect):
130 @click.group()
131 @click.argument("obj")
132 def cli(obj):
133 click.echo(f"obj={obj}")
134
135 @cli.command()
136 def move():
137 click.echo("move")
138
139 result = runner.invoke(cli, args)
140 assert result.exit_code == exit_code
141 assert expect in result.output
142
143
144 def test_custom_parser(runner):
145 import optparse
146
147 @click.group()
148 def cli():
149 pass
150
151 class OptParseCommand(click.Command):
152 def __init__(self, name, parser, callback):
153 super().__init__(name)
154 self.parser = parser
155 self.callback = callback
156
157 def parse_args(self, ctx, args):
158 try:
159 opts, args = parser.parse_args(args)
160 except Exception as e:
161 ctx.fail(str(e))
162 ctx.args = args
163 ctx.params = vars(opts)
164
165 def get_usage(self, ctx):
166 return self.parser.get_usage()
167
168 def get_help(self, ctx):
169 return self.parser.format_help()
170
171 def invoke(self, ctx):
172 ctx.invoke(self.callback, ctx.args, **ctx.params)
173
174 parser = optparse.OptionParser(usage="Usage: foo test [OPTIONS]")
175 parser.add_option(
176 "-f", "--file", dest="filename", help="write report to FILE", metavar="FILE"
177 )
178 parser.add_option(
179 "-q",
180 "--quiet",
181 action="store_false",
182 dest="verbose",
183 default=True,
184 help="don't print status messages to stdout",
185 )
186
187 def test_callback(args, filename, verbose):
188 click.echo(" ".join(args))
189 click.echo(filename)
190 click.echo(verbose)
191
192 cli.add_command(OptParseCommand("test", parser, test_callback))
193
194 result = runner.invoke(cli, ["test", "-f", "f.txt", "-q", "q1.txt", "q2.txt"])
195 assert result.exception is None
196 assert result.output.splitlines() == ["q1.txt q2.txt", "f.txt", "False"]
197
198 result = runner.invoke(cli, ["test", "--help"])
199 assert result.exception is None
200 assert result.output.splitlines() == [
201 "Usage: foo test [OPTIONS]",
202 "",
203 "Options:",
204 " -h, --help show this help message and exit",
205 " -f FILE, --file=FILE write report to FILE",
206 " -q, --quiet don't print status messages to stdout",
207 ]
208
209
210 def test_object_propagation(runner):
211 for chain in False, True:
212
213 @click.group(chain=chain)
214 @click.option("--debug/--no-debug", default=False)
215 @click.pass_context
216 def cli(ctx, debug):
217 if ctx.obj is None:
218 ctx.obj = {}
219 ctx.obj["DEBUG"] = debug
220
221 @cli.command()
222 @click.pass_context
223 def sync(ctx):
224 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")
225
226 result = runner.invoke(cli, ["sync"])
227 assert result.exception is None
228 assert result.output == "Debug is off\n"
229
230
231 @pytest.mark.parametrize(
232 ("opt_params", "expected"),
233 (
234 # Original tests.
235 ({"type": click.INT, "default": 42}, 42),
236 ({"type": click.INT, "default": "15"}, 15),
237 ({"multiple": True}, ()),
238 # SENTINEL value tests.
239 ({"default": None}, None),
240 ({"type": click.STRING}, None), # No default specified, should be None.
241 ({"type": click.BOOL, "default": False}, False),
242 ({"type": click.BOOL, "default": True}, True),
243 ({"type": click.FLOAT, "default": 3.14}, 3.14),
244 # Multiple with default.
245 ({"multiple": True, "default": [1, 2, 3]}, (1, 2, 3)),
246 ({"multiple": True, "default": ()}, ()),
247 # Required option without value should use SENTINEL behavior.
248 ({"required": False}, None),
249 # Choice type with default.
250 ({"type": click.Choice(["a", "b", "c"]), "default": "b"}, "b"),
251 # Path type with default.
252 ({"type": click.Path(), "default": "/tmp"}, "/tmp"),
253 # Flag options.
254 ({"is_flag": True, "default": False}, False),
255 ({"is_flag": True, "default": True}, True),
256 # Count option.
257 ({"count": True}, 0),
258 # Hidden option.
259 ({"hidden": True, "default": "secret"}, "secret"),
260 ),
261 )
262 def test_other_command_invoke_with_defaults(runner, opt_params, expected):
263 @click.command()
264 @click.pass_context
265 def cli(ctx):
266 return ctx.invoke(other_cmd)
267
268 @click.command()
269 @click.option("-a", **opt_params)
270 @click.pass_context
271 def other_cmd(ctx, a):
272 return ctx.info_name, a
273
274 result = runner.invoke(cli, standalone_mode=False)
275
276 assert result.return_value == ("other", expected)
277
278
279 def test_invoked_subcommand(runner):
280 @click.group(invoke_without_command=True)
281 @click.pass_context
282 def cli(ctx):
283 if ctx.invoked_subcommand is None:
284 click.echo("no subcommand, use default")
285 ctx.invoke(sync)
286 else:
287 click.echo("invoke subcommand")
288
289 @cli.command()
290 def sync():
291 click.echo("in subcommand")
292
293 result = runner.invoke(cli, ["sync"])
294 assert not result.exception
295 assert result.output == "invoke subcommand\nin subcommand\n"
296
297 result = runner.invoke(cli)
298 assert not result.exception
299 assert result.output == "no subcommand, use default\nin subcommand\n"
300
301
302 def test_aliased_command_canonical_name(runner):
303 class AliasedGroup(click.Group):
304 def get_command(self, ctx, cmd_name):
305 return push
306
307 def resolve_command(self, ctx, args):
308 _, command, args = super().resolve_command(ctx, args)
309 return command.name, command, args
310
311 cli = AliasedGroup()
312
313 @cli.command()
314 def push():
315 click.echo("push command")
316
317 result = runner.invoke(cli, ["pu", "--help"])
318 assert not result.exception
319 assert result.output.startswith("Usage: root push [OPTIONS]")
320
321
322 def test_group_add_command_name(runner):
323 cli = click.Group("cli")
324 cmd = click.Command("a", params=[click.Option(["-x"], required=True)])
325 cli.add_command(cmd, "b")
326 # Check that the command is accessed through the registered name,
327 # not the original name.
328 result = runner.invoke(cli, ["b"], default_map={"b": {"x": 3}})
329 assert result.exit_code == 0
330
331
332 @pytest.mark.parametrize(
333 ("invocation_order", "declaration_order", "expected_order"),
334 [
335 # Non-eager options.
336 ([], ["-a"], ["-a"]),
337 (["-a"], ["-a"], ["-a"]),
338 ([], ["-a", "-c"], ["-a", "-c"]),
339 (["-a"], ["-a", "-c"], ["-a", "-c"]),
340 (["-c"], ["-a", "-c"], ["-c", "-a"]),
341 ([], ["-c", "-a"], ["-c", "-a"]),
342 (["-a"], ["-c", "-a"], ["-a", "-c"]),
343 (["-c"], ["-c", "-a"], ["-c", "-a"]),
344 (["-a", "-c"], ["-a", "-c"], ["-a", "-c"]),
345 (["-c", "-a"], ["-a", "-c"], ["-c", "-a"]),
346 # Eager options.
347 ([], ["-b"], ["-b"]),
348 (["-b"], ["-b"], ["-b"]),
349 ([], ["-b", "-d"], ["-b", "-d"]),
350 (["-b"], ["-b", "-d"], ["-b", "-d"]),
351 (["-d"], ["-b", "-d"], ["-d", "-b"]),
352 ([], ["-d", "-b"], ["-d", "-b"]),
353 (["-b"], ["-d", "-b"], ["-b", "-d"]),
354 (["-d"], ["-d", "-b"], ["-d", "-b"]),
355 (["-b", "-d"], ["-b", "-d"], ["-b", "-d"]),
356 (["-d", "-b"], ["-b", "-d"], ["-d", "-b"]),
357 # Mixed options.
358 ([], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),
359 (["-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),
360 (["-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),
361 (["-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-c", "-a"]),
362 (["-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-a", "-c"]),
363 (["-a", "-b"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),
364 (["-b", "-a"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),
365 (["-d", "-c"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),
366 (["-c", "-d"], ["-a", "-b", "-c", "-d"], ["-d", "-b", "-c", "-a"]),
367 (["-a", "-b", "-c", "-d"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),
368 (["-b", "-d", "-a", "-c"], ["-a", "-b", "-c", "-d"], ["-b", "-d", "-a", "-c"]),
369 ([], ["-b", "-d", "-e", "-a", "-c"], ["-b", "-d", "-e", "-a", "-c"]),
370 (["-a", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-a", "-c"]),
371 (["-c", "-d"], ["-b", "-d", "-e", "-a", "-c"], ["-d", "-b", "-e", "-c", "-a"]),
372 ],
373 )
374 def test_iter_params_for_processing(
375 invocation_order, declaration_order, expected_order
376 ):
377 parameters = {
378 "-a": click.Option(["-a"]),
379 "-b": click.Option(["-b"], is_eager=True),
380 "-c": click.Option(["-c"]),
381 "-d": click.Option(["-d"], is_eager=True),
382 "-e": click.Option(["-e"], is_eager=True),
383 }
384
385 invocation_params = [parameters[opt_id] for opt_id in invocation_order]
386 declaration_params = [parameters[opt_id] for opt_id in declaration_order]
387 expected_params = [parameters[opt_id] for opt_id in expected_order]
388
389 assert (
390 click.core.iter_params_for_processing(invocation_params, declaration_params)
391 == expected_params
392 )
393
394
395 def test_help_param_priority(runner):
396 """Cover the edge-case in which the eagerness of help option was not
397 respected, because it was internally generated multiple times.
398
399 See: https://github.com/pallets/click/pull/2811
400 """
401
402 def print_and_exit(ctx, param, value):
403 if value:
404 click.echo(f"Value of {param.name} is: {value}")
405 ctx.exit()
406
407 @click.command(context_settings={"help_option_names": ("--my-help",)})
408 @click.option("-a", is_flag=True, expose_value=False, callback=print_and_exit)
409 @click.option(
410 "-b", is_flag=True, expose_value=False, callback=print_and_exit, is_eager=True
411 )
412 def cli():
413 pass
414
415 # --my-help is properly called and stop execution.
416 result = runner.invoke(cli, ["--my-help"])
417 assert "Value of a is: True" not in result.stdout
418 assert "Value of b is: True" not in result.stdout
419 assert "--my-help" in result.stdout
420 assert result.exit_code == 0
421
422 # -a is properly called and stop execution.
423 result = runner.invoke(cli, ["-a"])
424 assert "Value of a is: True" in result.stdout
425 assert "Value of b is: True" not in result.stdout
426 assert "--my-help" not in result.stdout
427 assert result.exit_code == 0
428
429 # -a takes precedence over -b and stop execution.
430 result = runner.invoke(cli, ["-a", "-b"])
431 assert "Value of a is: True" not in result.stdout
432 assert "Value of b is: True" in result.stdout
433 assert "--my-help" not in result.stdout
434 assert result.exit_code == 0
435
436 # --my-help is eager by default so takes precedence over -a and stop
437 # execution, whatever the order.
438 for args in [["-a", "--my-help"], ["--my-help", "-a"]]:
439 result = runner.invoke(cli, args)
440 assert "Value of a is: True" not in result.stdout
441 assert "Value of b is: True" not in result.stdout
442 assert "--my-help" in result.stdout
443 assert result.exit_code == 0
444
445 # Both -b and --my-help are eager so they're called in the order they're
446 # invoked by the user.
447 result = runner.invoke(cli, ["-b", "--my-help"])
448 assert "Value of a is: True" not in result.stdout
449 assert "Value of b is: True" in result.stdout
450 assert "--my-help" not in result.stdout
451 assert result.exit_code == 0
452
453 # But there was a bug when --my-help is called before -b, because the
454 # --my-help option created by click via help_option_names is internally
455 # created twice and is not the same object, breaking the priority order
456 # produced by iter_params_for_processing.
457 result = runner.invoke(cli, ["--my-help", "-b"])
458 assert "Value of a is: True" not in result.stdout
459 assert "Value of b is: True" not in result.stdout
460 assert "--my-help" in result.stdout
461 assert result.exit_code == 0
462
463
464 def test_unprocessed_options(runner):
465 @click.command(context_settings=dict(ignore_unknown_options=True))
466 @click.argument("args", nargs=-1, type=click.UNPROCESSED)
467 @click.option("--verbose", "-v", count=True)
468 def cli(verbose, args):
469 click.echo(f"Verbosity: {verbose}")
470 click.echo(f"Args: {'|'.join(args)}")
471
472 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])
473 assert not result.exception
474 assert result.output.splitlines() == [
475 "Verbosity: 4",
476 "Args: -foo|-x|--muhaha|x|y|-x",
477 ]
478
479
480 @pytest.mark.parametrize("doc", ["CLI HELP", None])
481 @pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])
482 def test_deprecated_in_help_messages(runner, doc, deprecated):
483 @click.command(deprecated=deprecated, help=doc)
484 def cli():
485 pass
486
487 result = runner.invoke(cli, ["--help"])
488 assert "(DEPRECATED" in result.output
489
490 if isinstance(deprecated, str):
491 assert deprecated in result.output
492
493
494 @pytest.mark.parametrize("deprecated", [True, "USE OTHER COMMAND INSTEAD"])
495 def test_deprecated_in_invocation(runner, deprecated):
496 @click.command(deprecated=deprecated)
497 def deprecated_cmd():
498 pass
499
500 result = runner.invoke(deprecated_cmd)
501 assert "DeprecationWarning:" in result.output
502
503 if isinstance(deprecated, str):
504 assert deprecated in result.output
505
506
507 def test_command_parse_args_collects_option_prefixes():
508 @click.command()
509 @click.option("+p", is_flag=True)
510 @click.option("!e", is_flag=True)
511 def test(p, e):
512 pass
513
514 ctx = click.Context(test)
515 test.parse_args(ctx, [])
516
517 assert ctx._opt_prefixes == {"-", "--", "+", "!"}
518
519
520 def test_group_parse_args_collects_base_option_prefixes():
521 @click.group()
522 @click.option("~t", is_flag=True)
523 def group(t):
524 pass
525
526 @group.command()
527 @click.option("+p", is_flag=True)
528 def command1(p):
529 pass
530
531 @group.command()
532 @click.option("!e", is_flag=True)
533 def command2(e):
534 pass
535
536 ctx = click.Context(group)
537 group.parse_args(ctx, ["command1", "+p"])
538
539 assert ctx._opt_prefixes == {"-", "--", "~"}
540
541
542 def test_group_invoke_collects_used_option_prefixes(runner):
543 opt_prefixes = set()
544
545 @click.group()
546 @click.option("~t", is_flag=True)
547 def group(t):
548 pass
549
550 @group.command()
551 @click.option("+p", is_flag=True)
552 @click.pass_context
553 def command1(ctx, p):
554 nonlocal opt_prefixes
555 opt_prefixes = ctx._opt_prefixes
556
557 @group.command()
558 @click.option("!e", is_flag=True)
559 def command2(e):
560 pass
561
562 runner.invoke(group, ["command1"])
563 assert opt_prefixes == {"-", "--", "~", "+"}
564
565
566 @pytest.mark.parametrize("exc", (EOFError, KeyboardInterrupt))
567 def test_abort_exceptions_with_disabled_standalone_mode(runner, exc):
568 @click.command()
569 def cli():
570 raise exc("catch me!")
571
572 rv = runner.invoke(cli, standalone_mode=False)
573 assert rv.exit_code == 1
574 assert isinstance(rv.exception.__cause__, exc)
575 assert rv.exception.__cause__.args == ("catch me!",)