Debian Codegraph @

tests/test_basic.py

raw ◀ ▶
1 Debian patch touch this file
1 from __future__ import annotations
2
3 import enum
4 import os
5
6 import pytest
7
8 import click
9 from click._utils import UNSET
10
11
12 def test_basic_functionality(runner):
13 @click.command()
14 def cli():
15 """Hello World!"""
16 click.echo("I EXECUTED")
17
18 result = runner.invoke(cli, ["--help"])
19 assert not result.exception
20 assert "Hello World!" in result.output
21 assert "Show this message and exit." in result.output
22 assert result.exit_code == 0
23 assert "I EXECUTED" not in result.output
24
25 result = runner.invoke(cli, [])
26 assert not result.exception
27 assert "I EXECUTED" in result.output
28 assert result.exit_code == 0
29
30
31 def test_repr():
32 @click.command()
33 def command():
34 pass
35
36 @click.group()
37 def group():
38 pass
39
40 @group.command()
41 def subcommand():
42 pass
43
44 assert repr(command) == "<Command command>"
45 assert repr(group) == "<Group group>"
46 assert repr(subcommand) == "<Command subcommand>"
47
48
49 def test_return_values():
50 @click.command()
51 def cli():
52 return 42
53
54 with cli.make_context("foo", []) as ctx:
55 rv = cli.invoke(ctx)
56 assert rv == 42
57
58
59 def test_basic_group(runner):
60 @click.group()
61 def cli():
62 """This is the root."""
63 click.echo("ROOT EXECUTED")
64
65 @cli.command()
66 def subcommand():
67 """This is a subcommand."""
68 click.echo("SUBCOMMAND EXECUTED")
69
70 result = runner.invoke(cli, ["--help"])
71 assert not result.exception
72 assert "COMMAND [ARGS]..." in result.output
73 assert "This is the root" in result.output
74 assert "This is a subcommand." in result.output
75 assert result.exit_code == 0
76 assert "ROOT EXECUTED" not in result.output
77
78 result = runner.invoke(cli, ["subcommand"])
79 assert not result.exception
80 assert result.exit_code == 0
81 assert "ROOT EXECUTED" in result.output
82 assert "SUBCOMMAND EXECUTED" in result.output
83
84
85 def test_group_commands_dict(runner):
86 """A Group can be built with a dict of commands."""
87
88 @click.command()
89 def sub():
90 click.echo("sub", nl=False)
91
92 cli = click.Group(commands={"other": sub})
93 result = runner.invoke(cli, ["other"])
94 assert result.output == "sub"
95
96
97 def test_group_from_list(runner):
98 """A Group can be built with a list of commands."""
99
100 @click.command()
101 def sub():
102 click.echo("sub", nl=False)
103
104 cli = click.Group(commands=[sub])
105 result = runner.invoke(cli, ["sub"])
106 assert result.output == "sub"
107
108
109 @pytest.mark.parametrize(
110 ("args", "expect"),
111 [
112 ([], "S:[no value]"),
113 (["--s=42"], "S:[42]"),
114 (["--s"], "Error: Option '--s' requires an argument."),
115 (["--s="], "S:[]"),
116 (["--s=\N{SNOWMAN}"], "S:[\N{SNOWMAN}]"),
117 ],
118 )
119 def test_string_option(runner, args, expect):
120 @click.command()
121 @click.option("--s", default="no value")
122 def cli(s):
123 click.echo(f"S:[{s}]")
124
125 result = runner.invoke(cli, args)
126 assert expect in result.output
127
128 if expect.startswith("Error:"):
129 assert result.exception is not None
130 else:
131 assert result.exception is None
132
133
134 @pytest.mark.parametrize(
135 ("args", "expect"),
136 [
137 ([], "I:[84]"),
138 (["--i=23"], "I:[46]"),
139 (["--i=x"], "Error: Invalid value for '--i': 'x' is not a valid integer."),
140 ],
141 )
142 def test_int_option(runner, args, expect):
143 @click.command()
144 @click.option("--i", default=42)
145 def cli(i):
146 click.echo(f"I:[{i * 2}]")
147
148 result = runner.invoke(cli, args)
149 assert expect in result.output
150
151 if expect.startswith("Error:"):
152 assert result.exception is not None
153 else:
154 assert result.exception is None
155
156
157 @pytest.mark.parametrize(
158 ("args", "expect"),
159 [
160 ([], "U:[ba122011-349f-423b-873b-9d6a79c688ab]"),
161 (
162 ["--u=821592c1-c50e-4971-9cd6-e89dc6832f86"],
163 "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]",
164 ),
165 (["--u=x"], "Error: Invalid value for '--u': 'x' is not a valid UUID."),
166 ],
167 )
168 def test_uuid_option(runner, args, expect):
169 @click.command()
170 @click.option(
171 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID
172 )
173 def cli(u):
174 click.echo(f"U:[{u}]")
175
176 result = runner.invoke(cli, args)
177 assert expect in result.output
178
179 if expect.startswith("Error:"):
180 assert result.exception is not None
181 else:
182 assert result.exception is None
183
184
185 @pytest.mark.parametrize(
186 ("args", "expect"),
187 [
188 ([], "F:[42.0]"),
189 ("--f=23.5", "F:[23.5]"),
190 ("--f=x", "Error: Invalid value for '--f': 'x' is not a valid float."),
191 ],
192 )
193 def test_float_option(runner, args, expect):
194 @click.command()
195 @click.option("--f", default=42.0)
196 def cli(f):
197 click.echo(f"F:[{f}]")
198
199 result = runner.invoke(cli, args)
200 assert expect in result.output
201
202 if expect.startswith("Error:"):
203 assert result.exception is not None
204 else:
205 assert result.exception is None
206
207
208 @pytest.mark.parametrize(
209 ("args", "default", "expect"),
210 [
211 (["--on"], True, True),
212 (["--on"], False, True),
213 (["--on"], None, True),
214 (["--on"], UNSET, True),
215 (["--off"], True, False),
216 (["--off"], False, False),
217 (["--off"], None, False),
218 (["--off"], UNSET, False),
219 ([], True, True),
220 ([], False, False),
221 ([], None, None),
222 ([], UNSET, False),
223 ],
224 )
225 def test_boolean_switch(runner, args, default, expect):
226 @click.command()
227 @click.option("--on/--off", default=default)
228 def cli(on):
229 return on
230
231 result = runner.invoke(cli, args, standalone_mode=False)
232 assert result.return_value is expect
233
234
235 @pytest.mark.parametrize(
236 ("default", "args", "expect"),
237 (
238 (True, ["--f"], True),
239 (True, [], True),
240 (False, ["--f"], True),
241 (False, [], False),
242 # Boolean flags have a 3-states logic.
243 # See: https://github.com/pallets/click/issues/3024#issue-3285556668
244 (None, ["--f"], True),
245 (None, [], None),
246 ),
247 )
248 def test_boolean_flag(runner, default, args, expect):
249 @click.command()
250 @click.option("--f", is_flag=True, default=default)
251 def cli(f):
252 return f
253
254 result = runner.invoke(cli, args, standalone_mode=False)
255 assert result.return_value is expect
256
257
258 @pytest.mark.parametrize(
259 ("value", "expect"),
•260 [
261 *((x, "True") for x in ("1", "true", "t", "yes", "y", "on")),
262 *((x, "False") for x in ("0", "false", "f", "no", "n", "off")),
263 ],
264 )
265 def test_boolean_conversion(runner, value, expect):
266 @click.command()
267 @click.option("--flag", type=bool)
268 def cli(flag):
269 click.echo(flag, nl=False)
270
271 result = runner.invoke(cli, ["--flag", value])
272 assert result.output == expect
273
274 result = runner.invoke(cli, ["--flag", value.title()])
275 assert result.output == expect
276
277
278 @pytest.mark.parametrize(
279 ("default", "args", "expected"),
280 # These test cases are similar to the ones in
281 # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.
282 (
283 # Each option is returning its own flag_value, whatever the default is.
284 (True, ["--upper"], "upper"),
285 (True, ["--lower"], "lower"),
286 (False, ["--upper"], "upper"),
287 (False, ["--lower"], "lower"),
288 (None, ["--upper"], "upper"),
289 (None, ["--lower"], "lower"),
290 (UNSET, ["--upper"], "upper"),
291 (UNSET, ["--lower"], "lower"),
292 # Check that the last option wins when both are specified.
293 (True, ["--upper", "--lower"], "lower"),
294 (True, ["--lower", "--upper"], "upper"),
295 # Check that the default is returned as-is when no option is specified.
296 ("upper", [], "upper"),
297 ("lower", [], "lower"),
298 ("uPPer", [], "uPPer"),
299 ("lOwEr", [], "lOwEr"),
300 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),
301 (None, [], None),
302 # Default is normalized to None if it is UNSET.
303 (UNSET, [], None),
304 # Special case: if default=True and flag_value is set, the value returned is the
305 # flag_value, not the True Python value itself.
306 (True, [], "upper"),
307 # Non-string defaults are process as strings by the default Parameter's type.
308 (False, [], "False"),
309 (42, [], "42"),
310 (12.3, [], "12.3"),
311 ),
312 )
313 def test_flag_value_dual_options(runner, default, args, expected):
314 """Check how default is processed when options compete for the same variable name.
315
316 Covers the regression reported in
317 https://github.com/pallets/click/issues/3024#issuecomment-3146199461
318
319 .. hint::
320 Similar to ``test_options.py::test_default_dual_option_callback``.
321
322 ``test_defaults.py::test_shared_param_prefers_first_default``
323 is a smoke-test complement that exercises both default placements.
324 """
325
326 @click.command()
327 @click.option("--upper", "case", flag_value="upper", default=default)
328 @click.option("--lower", "case", flag_value="lower")
329 def cli(case):
330 click.echo(repr(case), nl=False)
331
332 result = runner.invoke(cli, args)
333 assert result.output == repr(expected)
334
335
336 def test_file_option(runner):
337 @click.command()
338 @click.option("--file", type=click.File("w"))
339 def input(file):
340 file.write("Hello World!\n")
341
342 @click.command()
343 @click.option("--file", type=click.File("r"))
344 def output(file):
345 click.echo(file.read())
346
347 with runner.isolated_filesystem():
348 result_in = runner.invoke(input, ["--file=example.txt"])
349 result_out = runner.invoke(output, ["--file=example.txt"])
350
351 assert not result_in.exception
352 assert result_in.output == ""
353 assert not result_out.exception
354 assert result_out.output == "Hello World!\n\n"
355
356
357 def test_file_lazy_mode(runner):
358 do_io = False
359
360 @click.command()
361 @click.option("--file", type=click.File("w"))
362 def input(file):
363 if do_io:
364 file.write("Hello World!\n")
365
366 @click.command()
367 @click.option("--file", type=click.File("r"))
368 def output(file):
369 pass
370
371 with runner.isolated_filesystem():
372 os.mkdir("example.txt")
373
374 do_io = True
375 result_in = runner.invoke(input, ["--file=example.txt"])
376 assert result_in.exit_code == 1
377
378 do_io = False
379 result_in = runner.invoke(input, ["--file=example.txt"])
380 assert result_in.exit_code == 0
381
382 result_out = runner.invoke(output, ["--file=example.txt"])
383 assert result_out.exception
384
385 @click.command()
386 @click.option("--file", type=click.File("w", lazy=False))
387 def input_non_lazy(file):
388 file.write("Hello World!\n")
389
390 with runner.isolated_filesystem():
391 os.mkdir("example.txt")
392 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])
393 assert result_in.exit_code == 2
394 assert "Invalid value for '--file': 'example.txt'" in result_in.output
395
396
397 def test_path_option(runner):
398 @click.command()
399 @click.option("-O", type=click.Path(file_okay=False, exists=True, writable=True))
400 def write_to_dir(o):
401 with open(os.path.join(o, "foo.txt"), "wb") as f:
402 f.write(b"meh\n")
403
404 with runner.isolated_filesystem():
405 os.mkdir("test")
406
407 result = runner.invoke(write_to_dir, ["-O", "test"])
408 assert not result.exception
409
410 with open("test/foo.txt", "rb") as f:
411 assert f.read() == b"meh\n"
412
413 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])
414 assert "is a file" in result.output
415
416 @click.command()
417 @click.option("-f", type=click.Path(exists=True))
418 def showtype(f):
419 click.echo(f"is_file={os.path.isfile(f)}")
420 click.echo(f"is_dir={os.path.isdir(f)}")
421
422 with runner.isolated_filesystem():
423 result = runner.invoke(showtype, ["-f", "xxx"])
424 assert "does not exist" in result.output
425
426 result = runner.invoke(showtype, ["-f", "."])
427 assert "is_file=False" in result.output
428 assert "is_dir=True" in result.output
429
430 @click.command()
431 @click.option("-f", type=click.Path())
432 def exists(f):
433 click.echo(f"exists={os.path.exists(f)}")
434
435 with runner.isolated_filesystem():
436 result = runner.invoke(exists, ["-f", "xxx"])
437 assert "exists=False" in result.output
438
439 result = runner.invoke(exists, ["-f", "."])
440 assert "exists=True" in result.output
441
442
443 def test_choice_option(runner):
444 @click.command()
445 @click.option("--method", type=click.Choice(["foo", "bar", "baz"]))
446 def cli(method):
447 click.echo(method)
448
449 result = runner.invoke(cli, ["--method=foo"])
450 assert not result.exception
451 assert result.output == "foo\n"
452
453 result = runner.invoke(cli, ["--method=meh"])
454 assert result.exit_code == 2
455 assert (
456 "Invalid value for '--method': 'meh' is not one of 'foo', 'bar', 'baz'."
457 in result.output
458 )
459
460 result = runner.invoke(cli, ["--help"])
461 assert "--method [foo|bar|baz]" in result.output
462
463
464 def test_choice_argument(runner):
465 @click.command()
466 @click.argument("method", type=click.Choice(["foo", "bar", "baz"]))
467 def cli(method):
468 click.echo(method)
469
470 result = runner.invoke(cli, ["foo"])
471 assert not result.exception
472 assert result.output == "foo\n"
473
474 result = runner.invoke(cli, ["meh"])
475 assert result.exit_code == 2
476 assert (
477 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"
478 " 'bar', 'baz'." in result.output
479 )
480
481 result = runner.invoke(cli, ["--help"])
482 assert "{foo|bar|baz}" in result.output
483
484
485 def test_choice_argument_enum(runner):
486 class MyEnum(str, enum.Enum):
487 FOO = "foo-value"
488 BAR = "bar-value"
489 BAZ = "baz-value"
490
491 @click.command()
492 @click.argument("method", type=click.Choice(MyEnum, case_sensitive=False))
493 def cli(method: MyEnum):
494 assert isinstance(method, MyEnum)
495 click.echo(method)
496
497 result = runner.invoke(cli, ["foo"])
498 assert result.output == "foo-value\n"
499 assert not result.exception
500
501 result = runner.invoke(cli, ["meh"])
502 assert result.exit_code == 2
503 assert (
504 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"
505 " 'bar', 'baz'." in result.output
506 )
507
508 result = runner.invoke(cli, ["--help"])
509 assert "{foo|bar|baz}" in result.output
510
511
512 def test_choice_argument_custom_type(runner):
513 class MyClass:
514 def __init__(self, value: str) -> None:
515 self.value = value
516
517 def __str__(self) -> str:
518 return self.value
519
520 @click.command()
521 @click.argument(
522 "method", type=click.Choice([MyClass("foo"), MyClass("bar"), MyClass("baz")])
523 )
524 def cli(method: MyClass):
525 assert isinstance(method, MyClass)
526 click.echo(method)
527
528 result = runner.invoke(cli, ["foo"])
529 assert not result.exception
530 assert result.output == "foo\n"
531
532 result = runner.invoke(cli, ["meh"])
533 assert result.exit_code == 2
534 assert (
535 "Invalid value for '{foo|bar|baz}': 'meh' is not one of 'foo',"
536 " 'bar', 'baz'." in result.output
537 )
538
539 result = runner.invoke(cli, ["--help"])
540 assert "{foo|bar|baz}" in result.output
541
542
543 def test_choice_argument_none(runner):
544 @click.command()
545 @click.argument(
546 "method", type=click.Choice(["not-none", None], case_sensitive=False)
547 )
548 def cli(method: str | None):
549 assert isinstance(method, str) or method is None
550 click.echo(repr(method), nl=False)
551
552 result = runner.invoke(cli, ["not-none"])
553 assert not result.exception
554 assert result.output == repr("not-none")
555
556 result = runner.invoke(cli, ["none"])
557 assert not result.exception
558 assert result.output == repr(None)
559
560 result = runner.invoke(cli, [])
561 assert result.exception
562 assert (
563 "Error: Missing argument '{not-none|none}'. "
564 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr
565 )
566
567 result = runner.invoke(cli, ["--help"])
568 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")
569
570
571 def test_datetime_option_default(runner):
572 @click.command()
573 @click.option("--start_date", type=click.DateTime())
574 def cli(start_date):
575 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))
576
577 result = runner.invoke(cli, ["--start_date=2015-09-29"])
578 assert not result.exception
579 assert result.output == "2015-09-29T00:00:00\n"
580
581 result = runner.invoke(cli, ["--start_date=2015-09-29T09:11:22"])
582 assert not result.exception
583 assert result.output == "2015-09-29T09:11:22\n"
584
585 result = runner.invoke(cli, ["--start_date=2015-09"])
586 assert result.exit_code == 2
587 assert (
588 "Invalid value for '--start_date': '2015-09' does not match the formats"
589 " '%Y-%m-%d', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%d %H:%M:%S'."
590 ) in result.output
591
592 result = runner.invoke(cli, ["--help"])
593 assert (
594 "--start_date [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d %H:%M:%S]" in result.output
595 )
596
597
598 def test_datetime_option_custom(runner):
599 @click.command()
600 @click.option("--start_date", type=click.DateTime(formats=["%A %B %d, %Y"]))
601 def cli(start_date):
602 click.echo(start_date.strftime("%Y-%m-%dT%H:%M:%S"))
603
604 result = runner.invoke(cli, ["--start_date=Wednesday June 05, 2010"])
605 assert not result.exception
606 assert result.output == "2010-06-05T00:00:00\n"
607
608
609 def test_required_option(runner):
610 @click.command()
611 @click.option("--foo", required=True)
612 def cli(foo):
613 click.echo(foo)
614
615 result = runner.invoke(cli, [])
616 assert result.exit_code == 2
617 assert "Missing option '--foo'" in result.output
618
619
620 def test_evaluation_order(runner):
621 called = []
622
623 def memo(ctx, param, value):
624 called.append(value)
625 return value
626
627 @click.command()
628 @click.option("--missing", default="missing", is_eager=False, callback=memo)
629 @click.option("--eager-flag1", flag_value="eager1", is_eager=True, callback=memo)
630 @click.option("--eager-flag2", flag_value="eager2", is_eager=True, callback=memo)
631 @click.option("--eager-flag3", flag_value="eager3", is_eager=True, callback=memo)
632 @click.option("--normal-flag1", flag_value="normal1", is_eager=False, callback=memo)
633 @click.option("--normal-flag2", flag_value="normal2", is_eager=False, callback=memo)
634 @click.option("--normal-flag3", flag_value="normal3", is_eager=False, callback=memo)
635 def cli(**x):
636 pass
637
638 result = runner.invoke(
639 cli,
640 [
641 "--eager-flag2",
642 "--eager-flag1",
643 "--normal-flag2",
644 "--eager-flag3",
645 "--normal-flag3",
646 "--normal-flag3",
647 "--normal-flag1",
648 "--normal-flag1",
649 ],
650 )
651 assert not result.exception
652 assert called == [
653 "eager2",
654 "eager1",
655 "eager3",
656 "normal2",
657 "normal3",
658 "normal1",
659 "missing",
660 ]
661
662
663 def test_hidden_option(runner):
664 @click.command()
665 @click.option("--nope", hidden=True)
666 def cli(nope):
667 click.echo(nope)
668
669 result = runner.invoke(cli, ["--help"])
670 assert result.exit_code == 0
671 assert "--nope" not in result.output
672
673
674 def test_hidden_command(runner):
675 @click.group()
676 def cli():
677 pass
678
679 @cli.command(hidden=True)
680 def nope():
681 pass
682
683 result = runner.invoke(cli, ["--help"])
684 assert result.exit_code == 0
685 assert "nope" not in result.output
686
687
688 def test_hidden_group(runner):
689 @click.group()
690 def cli():
691 pass
692
693 @cli.group(hidden=True)
694 def subgroup():
695 pass
696
697 @subgroup.command()
698 def nope():
699 pass
700
701 result = runner.invoke(cli, ["--help"])
702 assert result.exit_code == 0
703 assert "subgroup" not in result.output
704 assert "nope" not in result.output
705
706
707 def test_summary_line(runner):
708 @click.group()
709 def cli():
710 pass
711
712 @cli.command()
713 def cmd():
714 """
715 Summary line without period
716
717 Here is a sentence. And here too.
718 """
719 pass
720
721 result = runner.invoke(cli, ["--help"])
722 assert "Summary line without period" in result.output
723 assert "Here is a sentence." not in result.output
724
725
726 def test_help_invalid_default(runner):
727 cli = click.Command(
728 "cli",
729 params=[
730 click.Option(
731 ["-a"],
732 type=click.Path(exists=True),
733 default="not found",
734 show_default=True,
735 ),
736 ],
737 )
738 result = runner.invoke(cli, ["--help"])
739 assert result.exit_code == 0
740 assert "default: not found" in result.output