Debian Codegraph @

tests/test_options.py

raw
1 import enum
2 import os
3 import re
4 import sys
5 import tempfile
6 from contextlib import nullcontext
7 from typing import Literal
8
9 if sys.version_info < (3, 11):
10 enum.StrEnum = enum.Enum # type: ignore[assignment]
11
12 import pytest
13
14 import click
15 from click import Option
16 from click import UNPROCESSED
17 from click._utils import UNSET
18 from click.testing import CliRunner
19
20
21 def test_prefixes(runner):
22 @click.command()
23 @click.option("++foo", is_flag=True, help="das foo")
24 @click.option("--bar", is_flag=True, help="das bar")
25 def cli(foo, bar):
26 click.echo(f"foo={foo} bar={bar}")
27
28 result = runner.invoke(cli, ["++foo", "--bar"])
29 assert not result.exception
30 assert result.output == "foo=True bar=True\n"
31
32 result = runner.invoke(cli, ["--help"])
33 assert re.search(r"\+\+foo\s+das foo", result.output) is not None
34 assert re.search(r"--bar\s+das bar", result.output) is not None
35
36
37 def test_invalid_option(runner):
38 with pytest.raises(TypeError, match="name was passed") as exc_info:
39 click.Option(["foo"])
40
41 message = str(exc_info.value)
42 assert "name was passed (foo)" in message
43 assert "declare an argument" in message
44 assert "'--foo'" in message
45
46
47 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])
48 def test_deprecated_usage(runner, deprecated):
49 @click.command()
50 @click.option("--foo", default="bar", deprecated=deprecated)
51 def cmd(foo):
52 click.echo(foo)
53
54 result = runner.invoke(cmd, ["--help"])
55 assert "(DEPRECATED" in result.output
56
57 if isinstance(deprecated, str):
58 assert deprecated in result.output
59
60
61 @pytest.mark.parametrize("deprecated", [True, "USE B INSTEAD"])
62 def test_deprecated_warning(runner, deprecated):
63 @click.command()
64 @click.option(
65 "--my-option", required=False, deprecated=deprecated, default="default option"
66 )
67 def cli(my_option: str):
68 click.echo(f"{my_option}")
69
70 # defaults should not give a deprecated warning
71 result = runner.invoke(cli, [])
72 assert result.exit_code == 0, result.output
73 assert "is deprecated" not in result.output
74
75 result = runner.invoke(cli, ["--my-option", "hello"])
76 assert result.exit_code == 0, result.output
77 assert "option 'my_option' is deprecated" in result.output
78
79 if isinstance(deprecated, str):
80 assert deprecated in result.output
81
82
83 def test_deprecated_required(runner):
84 with pytest.raises(ValueError, match="is deprecated and still required"):
85 click.Option(["--a"], required=True, deprecated=True)
86
87
88 def test_deprecated_prompt(runner):
89 with pytest.raises(ValueError, match="`deprecated` options cannot use `prompt`"):
90 click.Option(["--a"], prompt=True, deprecated=True)
91
92
93 def test_invalid_nargs(runner):
94 with pytest.raises(TypeError, match="nargs=-1 is not supported for options."):
95
96 @click.command()
97 @click.option("--foo", nargs=-1)
98 def cli(foo):
99 pass
100
101
102 def test_nargs_tup_composite_mult(runner):
103 @click.command()
104 @click.option("--item", type=(str, int), multiple=True)
105 def copy(item):
106 for name, id in item:
107 click.echo(f"name={name} id={id:d}")
108
109 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])
110 assert not result.exception
111 assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]
112
113
114 def test_counting(runner):
115 @click.command()
116 @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))
117 def cli(v):
118 click.echo(f"verbosity={v:d}")
119
120 result = runner.invoke(cli, ["-vvv"])
121 assert not result.exception
122 assert result.output == "verbosity=3\n"
123
124 result = runner.invoke(cli, ["-vvvv"])
125 assert result.exception
126 assert "Invalid value for '-v': 4 is not in the range 0<=x<=3." in result.output
127
128 result = runner.invoke(cli, [])
129 assert not result.exception
130 assert result.output == "verbosity=0\n"
131
132 result = runner.invoke(cli, ["--help"])
133 assert re.search(r"-v\s+Verbosity", result.output) is not None
134
135
136 @pytest.mark.parametrize("unknown_flag", ["--foo", "-f"])
137 def test_unknown_options(runner, unknown_flag):
138 @click.command()
139 def cli():
140 pass
141
142 result = runner.invoke(cli, [unknown_flag])
143 assert result.exception
144 assert f"No such option: {unknown_flag}" in result.output
145
146
147 @pytest.mark.parametrize(
148 ("value", "expect"),
149 [
150 ("--cat", "Did you mean --count?"),
151 ("--bounds", "(Possible options: --bound, --count)"),
152 ("--bount", "(Possible options: --bound, --count)"),
153 ],
154 )
155 def test_suggest_possible_options(runner, value, expect):
156 cli = click.Command(
157 "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]
158 )
159 result = runner.invoke(cli, [value])
160 assert expect in result.output
161
162
163 def test_multiple_required(runner):
164 @click.command()
165 @click.option("-m", "--message", multiple=True, required=True)
166 def cli(message):
167 click.echo("\n".join(message))
168
169 result = runner.invoke(cli, ["-m", "foo", "-mbar"])
170 assert not result.exception
171 assert result.output == "foo\nbar\n"
172
173 result = runner.invoke(cli, [])
174 assert result.exception
175 assert "Error: Missing option '-m' / '--message'." in result.output
176
177
178 @pytest.mark.parametrize(
179 ("multiple", "nargs", "default", "expected"),
180 [
181 # If multiple values are allowed, defaults should be iterable.
182 (True, 1, [], ()),
183 (True, 1, (), ()),
184 (True, 1, tuple(), ()),
185 (True, 1, set(), ()),
186 (True, 1, frozenset(), ()),
187 (True, 1, {}, ()),
188 # Special values.
189 (True, 1, None, ()),
190 (True, 1, UNSET, ()),
191 # Number of values are kept as-is in the default.
192 (True, 1, [1], (1,)),
193 (True, 1, [1, 2], (1, 2)),
194 (True, 1, [1, 2, 3], (1, 2, 3)),
195 (True, 1, [1.1, 2.2], (1.1, 2.2)),
196 (True, 1, ["1", "2"], ("1", "2")),
197 (True, 1, [None, None], (None, None)),
198 # Contrary to list or tuples, native Python types not supported by Click are
199 # not recognized and are converted to the default format: tuple of strings.
200 # Refs: https://github.com/pallets/click/issues/3036
201 (True, 1, {1, 2}, ("1", "2")),
202 (True, 1, frozenset([1, 2]), ("1", "2")),
203 (True, 1, {1: "a", 2: "b"}, ("1", "2")),
204 # Multiple values with nargs > 1.
205 (True, 2, [], ()),
206 (True, 2, (), ()),
207 (True, 2, tuple(), ()),
208 (True, 2, set(), ()),
209 (True, 2, frozenset(), ()),
210 (True, 2, {}, ()),
211 (True, 2, None, ()),
212 (True, 2, UNSET, ()),
213 (True, 2, [[1, 2]], ((1, 2),)),
214 (True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))),
215 (True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))),
216 (True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))),
217 (True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))),
218 (True, 2, [[None, None], [None, None]], ((None, None), (None, None))),
219 (True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))),
220 (True, 2, [[1, 2.2], None], ((1, 2.2), None)),
221 # Default of the right length works for non-multiples.
222 (False, 2, [1, 2], (1, 2)),
223 ],
224 )
225 def test_good_defaults_for_multiple(runner, multiple, nargs, default, expected):
226 """Comprehensive check of default-value processing for options with
227 ``multiple=True`` and/or ``nargs > 1``.
228
229 .. hint::
230 An argument-specific equivalent is in
231 ``test_arguments.py::test_good_defaults_for_nargs``.
232
233 Smoke tests are in ``test_defaults.py``:
234 ``test_multiple_defaults`` (explicit ``type=FLOAT``)
235 and ``test_nargs_plus_multiple`` (``nargs=2``).
236 """
237
238 @click.command()
239 @click.option("-a", multiple=multiple, nargs=nargs, default=default)
240 def cmd(a):
241 click.echo(repr(a), nl=False)
242
243 result = runner.invoke(cmd)
244 assert result.output == repr(expected)
245
246
247 @pytest.mark.parametrize(
248 ("multiple", "nargs", "default", "exception", "message"),
249 [
250 # Non-iterables defaults.
251 (
252 True,
253 1,
254 "Yo",
255 None,
256 "Error: Invalid value for '-a': Value must be an iterable.",
257 ),
258 (
259 True,
260 1,
261 "",
262 None,
263 "Error: Invalid value for '-a': Value must be an iterable.",
264 ),
265 (
266 True,
267 1,
268 True,
269 None,
270 "Error: Invalid value for '-a': Value must be an iterable.",
271 ),
272 (
273 True,
274 1,
275 False,
276 None,
277 "Error: Invalid value for '-a': Value must be an iterable.",
278 ),
279 (
280 True,
281 1,
282 12,
283 None,
284 "Error: Invalid value for '-a': Value must be an iterable.",
285 ),
286 (
287 True,
288 1,
289 7.9,
290 None,
291 "Error: Invalid value for '-a': Value must be an iterable.",
292 ),
293 (
294 False,
295 2,
296 42,
297 None,
298 "Error: Invalid value for '-a': Value must be an iterable.",
299 ),
300 (
301 True,
302 2,
303 ["test string which is not a list in the list"],
304 None,
305 "Error: Invalid value for '-a': Value must be an iterable.",
306 ),
307 # Multiple options, each with 2 args, but with wrong length.
308 (
309 True,
310 2,
311 (1,),
312 None,
313 "Error: Invalid value for '-a': Value must be an iterable.",
314 ),
315 (
316 True,
317 2,
318 (1, 2, 3),
319 None,
320 "Error: Invalid value for '-a': Value must be an iterable.",
321 ),
322 (
323 True,
324 2,
325 [tuple()],
326 ValueError,
327 r"'nargs' must be 0 \(or None\) for type <click\.types\.Tuple object at "
328 r"0x[0-9A-Fa-f]+>, but it was 2\.",
329 ),
330 (
331 True,
332 2,
333 [(1,)],
334 ValueError,
335 r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "
336 r"0x[0-9A-Fa-f]+>, but it was 2\.",
337 ),
338 (
339 True,
340 2,
341 [(1, 2, 3)],
342 ValueError,
343 r"'nargs' must be 3 \(or None\) for type <click\.types\.Tuple object at "
344 r"0x[0-9A-Fa-f]+>, but it was 2\.",
345 ),
346 # A mix of valid and invalid defaults.
347 (
348 True,
349 2,
350 [[1, 2.2], []],
351 None,
352 "Error: Invalid value for '-a': 2 values are required, but 0 were given.",
353 ),
354 # Default values that are iterable but not of the right length.
355 (
356 False,
357 2,
358 [1],
359 None,
360 "Error: Invalid value for '-a': Takes 2 values but 1 was given.",
361 ),
362 (
363 True,
364 2,
365 [[1]],
366 ValueError,
367 r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "
368 r"0x[0-9A-Fa-f]+>, but it was 2\.",
369 ),
370 ],
371 )
372 def test_bad_defaults_for_multiple(
373 runner, multiple, nargs, default, exception, message
374 ):
375 if exception:
376 assert issubclass(exception, Exception)
377 else:
378 assert exception is None
379
380 with (
381 pytest.raises(exception, match=re.compile(message))
382 if exception
383 else nullcontext()
384 ):
385
386 @click.command()
387 @click.option("-a", multiple=multiple, nargs=nargs, default=default)
388 def cmd(a):
389 click.echo(repr(a))
390
391 result = runner.invoke(cmd)
392 assert message in result.stderr
393
394
395 @pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])
396 def test_empty_envvar(runner, env_key):
397 @click.command()
398 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")
399 def cli(mypath):
400 click.echo(f"mypath: {mypath}")
401
402 result = runner.invoke(cli, env={env_key: ""}, auto_envvar_prefix="AUTO")
403 assert result.exception is None
404 assert result.output == "mypath: None\n"
405
406
407 def test_multiple_envvar(runner):
408 @click.command()
409 @click.option("--arg", multiple=True)
410 def cmd(arg):
411 click.echo("|".join(arg))
412
413 result = runner.invoke(
414 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar baz"}
415 )
416 assert not result.exception
417 assert result.output == "foo|bar|baz\n"
418
419 @click.command()
420 @click.option("--arg", multiple=True, envvar="X")
421 def cmd(arg):
422 click.echo("|".join(arg))
423
424 result = runner.invoke(cmd, [], env={"X": "foo bar baz"})
425 assert not result.exception
426 assert result.output == "foo|bar|baz\n"
427
428 @click.command()
429 @click.option("--arg", multiple=True, type=click.Path())
430 def cmd(arg):
431 click.echo("|".join(arg))
432
433 result = runner.invoke(
434 cmd,
435 [],
436 auto_envvar_prefix="TEST",
437 env={"TEST_ARG": f"foo{os.path.pathsep}bar"},
438 )
439 assert not result.exception
440 assert result.output == "foo|bar\n"
441
442
443 @pytest.mark.parametrize(
444 ("envvar_name", "envvar_value", "expected"),
445 (
446 # Lower-cased variations of value.
447 ("SHOUT", "true", True),
448 ("SHOUT", "false", False),
449 # Title-cased variations of value.
450 ("SHOUT", "True", True),
451 ("SHOUT", "False", False),
452 # Upper-cased variations of value.
453 ("SHOUT", "TRUE", True),
454 ("SHOUT", "FALSE", False),
455 # Random-cased variations of value.
456 ("SHOUT", "TruE", True),
457 ("SHOUT", "truE", True),
458 ("SHOUT", "FaLsE", False),
459 ("SHOUT", "falsE", False),
460 # Extra spaces around the value.
461 ("SHOUT", "true ", True),
462 ("SHOUT", " true ", True),
463 ("SHOUT", " true", True),
464 ("SHOUT", "false ", False),
465 ("SHOUT", " false ", False),
466 ("SHOUT", " false", False),
467 # Integer variations.
468 ("SHOUT", "1", True),
469 ("SHOUT", "0", False),
470 # Alternative states.
471 ("SHOUT", "t", True),
472 ("SHOUT", "T", True),
473 ("SHOUT", " T ", True),
474 ("SHOUT", "f", False),
475 ("SHOUT", "y", True),
476 ("SHOUT", "n", False),
477 ("SHOUT", "yes", True),
478 ("SHOUT", "no", False),
479 ("SHOUT", "on", True),
480 ("SHOUT", "off", False),
481 # Blank value variations.
482 ("SHOUT", None, False),
483 ("SHOUT", "", False),
484 ("SHOUT", " ", False),
485 ("SHOUT", " ", False),
486 # Variable names are not stripped of spaces and so don't match the
487 # flag, which then naturraly takes its default value.
488 ("SHOUT ", "True", False),
489 ("SHOUT ", "False", False),
490 (" SHOUT ", "True", False),
491 (" SHOUT ", "False", False),
492 (" SHOUT", "True", False),
493 (" SHOUT", "False", False),
494 ("SH OUT", "True", False),
495 ("SH OUT", "False", False),
496 # Same for random and reverse environment variable names: they are not
497 # recognized by the option.
498 ("RANDOM", "True", False),
499 ("NO_SHOUT", "True", False),
500 ("NO_SHOUT", "False", False),
501 ("NOSHOUT", "True", False),
502 ("NOSHOUT", "False", False),
503 ),
504 )
505 def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):
506 assert isinstance(envvar_name, str)
507 assert isinstance(envvar_value, str) or envvar_value is None
508
509 @click.command()
510 @click.option("--shout/--no-shout", envvar="SHOUT")
511 def cli(shout):
512 click.echo(repr(shout), nl=False)
513
514 result = runner.invoke(cli, [], env={envvar_name: envvar_value})
515 assert result.exit_code == 0
516 assert result.output == repr(expected)
517
518
519 @pytest.mark.parametrize(
520 "value",
521 (
522 # Extra spaces inside the value.
523 "tr ue",
524 "fa lse",
525 # Numbers.
526 "10",
527 "01",
528 "00",
529 "11",
530 "0.0",
531 "1.1",
532 # Random strings.
533 "randomstring",
534 "None",
535 "'None'",
536 "A B",
537 " 1 2 ",
538 "9.3",
539 "a;n",
540 "x:y",
541 "i/o",
542 ),
543 )
544 def test_boolean_envvar_bad_values(runner, value):
545 @click.command()
546 @click.option("--shout/--no-shout", envvar="SHOUT")
547 def cli(shout):
548 click.echo(shout)
549
550 result = runner.invoke(cli, [], env={"SHOUT": value})
551 assert result.exit_code == 2
552 assert (
553 f"Invalid value for '--shout': {value!r} is not a valid boolean."
554 in result.output
555 )
556
557
558 def test_multiple_default_help(runner):
559 @click.command()
560 @click.option("--arg1", multiple=True, default=("foo", "bar"), show_default=True)
561 @click.option("--arg2", multiple=True, default=(1, 2), type=int, show_default=True)
562 def cmd(arg, arg2):
563 pass
564
565 result = runner.invoke(cmd, ["--help"])
566 assert not result.exception
567 assert "foo, bar" in result.output
568 assert "1, 2" in result.output
569
570
571 def test_show_default_default_map(runner):
572 @click.command()
573 @click.option("--arg", default="a", show_default=True)
574 def cmd(arg):
575 click.echo(arg)
576
577 result = runner.invoke(cmd, ["--help"], default_map={"arg": "b"})
578
579 assert not result.exception
580 assert "[default: b]" in result.output
581
582
583 def test_multiple_default_type():
584 opt = click.Option(["-a"], multiple=True, default=(1, 2))
585 assert opt.nargs == 1
586 assert opt.multiple
587 assert opt.type is click.INT
588 ctx = click.Context(click.Command("test"))
589 assert opt.get_default(ctx) == (1, 2)
590
591
592 def test_multiple_default_composite_type():
593 opt = click.Option(["-a"], multiple=True, default=[(1, "a")])
594 assert opt.nargs == 2
595 assert opt.multiple
596 assert isinstance(opt.type, click.Tuple)
597 assert opt.type.types == [click.INT, click.STRING]
598 ctx = click.Context(click.Command("test"))
599 assert opt.type_cast_value(ctx, opt.get_default(ctx)) == ((1, "a"),)
600
601
602 def test_parse_multiple_default_composite_type(runner):
603 @click.command()
604 @click.option("-a", multiple=True, default=("a", "b"))
605 @click.option("-b", multiple=True, default=[(1, "a")])
606 def cmd(a, b):
607 click.echo(a)
608 click.echo(b)
609
610 # result = runner.invoke(cmd, "-a c -a 1 -a d -b 2 two -b 4 four".split())
611 # assert result.output == "('c', '1', 'd')\n((2, 'two'), (4, 'four'))\n"
612 result = runner.invoke(cmd)
613 assert result.output == "('a', 'b')\n((1, 'a'),)\n"
614
615
616 def test_dynamic_default_help_unset(runner):
617 @click.command()
618 @click.option(
619 "--username",
620 prompt=True,
621 default=lambda: os.environ.get("USER", ""),
622 show_default=True,
623 )
624 def cmd(username):
625 print("Hello,", username)
626
627 result = runner.invoke(cmd, ["--help"])
628 assert result.exit_code == 0
629 assert "--username" in result.output
630 assert "lambda" not in result.output
631 assert "(dynamic)" in result.output
632
633
634 def test_dynamic_default_help_text(runner):
635 @click.command()
636 @click.option(
637 "--username",
638 prompt=True,
639 default=lambda: os.environ.get("USER", ""),
640 show_default="current user",
641 )
642 def cmd(username):
643 print("Hello,", username)
644
645 result = runner.invoke(cmd, ["--help"])
646 assert result.exit_code == 0
647 assert "--username" in result.output
648 assert "lambda" not in result.output
649 assert "(current user)" in result.output
650
651
652 def test_dynamic_default_help_special_method(runner):
653 class Value:
654 def __call__(self):
655 return 42
656
657 def __str__(self):
658 return "special value"
659
660 opt = click.Option(["-a"], default=Value(), show_default=True)
661 ctx = click.Context(click.Command("cli"))
662 assert opt.get_help_extra(ctx) == {"default": "special value"}
663 assert "special value" in opt.get_help_record(ctx)[1]
664
665
666 @pytest.mark.parametrize(
667 ("type", "expect"),
668 [
669 (click.IntRange(1, 32), "1<=x<=32"),
670 (click.IntRange(1, 32, min_open=True, max_open=True), "1<x<32"),
671 (click.IntRange(1), "x>=1"),
672 (click.IntRange(max=32), "x<=32"),
673 ],
674 )
675 def test_intrange_default_help_text(type, expect):
676 option = click.Option(["--num"], type=type, show_default=True, default=2)
677 context = click.Context(click.Command("test"))
678 assert option.get_help_extra(context) == {"default": "2", "range": expect}
679 result = option.get_help_record(context)[1]
680 assert expect in result
681
682
683 def test_count_default_type_help():
684 """A count option with the default type should not show >=0 in help."""
685 option = click.Option(["--count"], count=True, help="some words")
686 context = click.Context(click.Command("test"))
687 assert option.get_help_extra(context) == {}
688 result = option.get_help_record(context)[1]
689 assert result == "some words"
690
691
692 def test_file_type_help_default():
693 """The default for a File type is a filename string. The string
694 should be displayed in help, not an open file object.
695
696 Type casting is only applied to defaults in processing, not when
697 getting the default value.
698 """
699 option = click.Option(
700 ["--in"], type=click.File(), default=__file__, show_default=True
701 )
702 context = click.Context(click.Command("test"))
703 assert option.get_help_extra(context) == {"default": __file__}
704 result = option.get_help_record(context)[1]
705 assert __file__ in result
706
707
708 def test_toupper_envvar_prefix(runner):
709 @click.command()
710 @click.option("--arg")
711 def cmd(arg):
712 click.echo(arg)
713
714 result = runner.invoke(cmd, [], auto_envvar_prefix="test", env={"TEST_ARG": "foo"})
715 assert not result.exception
716 assert result.output == "foo\n"
717
718
719 def test_nargs_envvar(runner):
720 @click.command()
721 @click.option("--arg", nargs=2)
722 def cmd(arg):
723 click.echo("|".join(arg))
724
725 result = runner.invoke(
726 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "foo bar"}
727 )
728 assert not result.exception
729 assert result.output == "foo|bar\n"
730
731 @click.command()
732 @click.option("--arg", nargs=2, multiple=True)
733 def cmd(arg):
734 for item in arg:
735 click.echo("|".join(item))
736
737 result = runner.invoke(
738 cmd, [], auto_envvar_prefix="TEST", env={"TEST_ARG": "x 1 y 2"}
739 )
740 assert not result.exception
741 assert result.output == "x|1\ny|2\n"
742
743
744 def test_show_envvar(runner):
745 @click.command()
746 @click.option("--arg1", envvar="ARG1", show_envvar=True)
747 def cmd(arg):
748 pass
749
750 result = runner.invoke(cmd, ["--help"])
751 assert not result.exception
752 assert "ARG1" in result.output
753
754
755 def test_show_envvar_auto_prefix(runner):
756 @click.command()
757 @click.option("--arg1", show_envvar=True)
758 def cmd(arg):
759 pass
760
761 result = runner.invoke(cmd, ["--help"], auto_envvar_prefix="TEST")
762 assert not result.exception
763 assert "TEST_ARG1" in result.output
764
765
766 def test_show_envvar_auto_prefix_dash_in_command(runner):
767 @click.group()
768 def cli():
769 pass
770
771 @cli.command()
772 @click.option("--baz", show_envvar=True)
773 def foo_bar(baz):
774 pass
775
776 result = runner.invoke(cli, ["foo-bar", "--help"], auto_envvar_prefix="TEST")
777 assert not result.exception
778 assert "TEST_FOO_BAR_BAZ" in result.output
779
780
781 def test_custom_validation(runner):
782 def validate_pos_int(ctx, param, value):
783 if value < 0:
784 raise click.BadParameter("Value needs to be positive")
785 return value
786
787 @click.command()
788 @click.option("--foo", callback=validate_pos_int, default=1)
789 def cmd(foo):
790 click.echo(foo)
791
792 result = runner.invoke(cmd, ["--foo", "-1"])
793 assert "Invalid value for '--foo': Value needs to be positive" in result.output
794
795 result = runner.invoke(cmd, ["--foo", "42"])
796 assert result.output == "42\n"
797
798
799 def test_callback_validates_prompt(runner, monkeypatch):
800 def validate(ctx, param, value):
801 if value < 0:
802 raise click.BadParameter("should be positive")
803
804 return value
805
806 @click.command()
807 @click.option("-a", type=int, callback=validate, prompt=True)
808 def cli(a):
809 click.echo(a)
810
811 result = runner.invoke(cli, input="-12\n60\n")
812 assert result.output == "A: -12\nError: should be positive\nA: 60\n60\n"
813
814
815 def test_winstyle_options(runner):
816 @click.command()
817 @click.option("/debug;/no-debug", help="Enables or disables debug mode.")
818 def cmd(debug):
819 click.echo(debug)
820
821 result = runner.invoke(cmd, ["/debug"], help_option_names=["/?"])
822 assert result.output == "True\n"
823 result = runner.invoke(cmd, ["/no-debug"], help_option_names=["/?"])
824 assert result.output == "False\n"
825 result = runner.invoke(cmd, [], help_option_names=["/?"])
826 assert result.output == "False\n"
827 result = runner.invoke(cmd, ["/?"], help_option_names=["/?"])
828 assert "/debug; /no-debug Enables or disables debug mode." in result.output
829 assert "/? Show this message and exit." in result.output
830
831
832 def test_legacy_options(runner):
833 @click.command()
834 @click.option("-whatever")
835 def cmd(whatever):
836 click.echo(whatever)
837
838 result = runner.invoke(cmd, ["-whatever", "42"])
839 assert result.output == "42\n"
840 result = runner.invoke(cmd, ["-whatever=23"])
841 assert result.output == "23\n"
842
843
844 @pytest.mark.parametrize(
845 ("value", "expect_missing", "processed_value"),
846 [
847 (UNSET, True, None),
848 (None, False, None),
849 # Default type of the argument is str, so everything is processed as strings.
850 ("", False, ""),
851 (" ", False, " "),
852 ("foo", False, "foo"),
853 ("12", False, "12"),
854 (12, False, "12"),
855 (12.1, False, "12.1"),
856 (list(), False, "[]"),
857 (tuple(), False, "()"),
858 (set(), False, "set()"),
859 (frozenset(), False, "frozenset()"),
860 (dict(), False, "{}"),
861 ],
862 )
863 def test_required_option(value, expect_missing, processed_value):
864 ctx = click.Context(click.Command(""))
865 argument = click.Option(["-a"], required=True)
866
867 if expect_missing:
868 with pytest.raises(click.MissingParameter) as excinfo:
869 argument.process_value(ctx, value)
870 assert str(excinfo.value) == "Missing parameter: a"
871
872 else:
873 value = argument.process_value(ctx, value)
874 assert value == processed_value
875
876
877 def test_missing_required_flag(runner):
878 cli = click.Command(
879 "cli", params=[click.Option(["--on/--off"], is_flag=True, required=True)]
880 )
881 result = runner.invoke(cli)
882 assert result.exit_code == 2
883 assert "Error: Missing option '--on'." in result.output
884
885
886 def test_missing_choice(runner):
887 @click.command()
888 @click.option("--foo", type=click.Choice(["foo", "bar"]), required=True)
889 def cmd(foo):
890 click.echo(foo)
891
892 result = runner.invoke(cmd)
893 assert result.exit_code == 2
894 error, separator, choices = result.output.partition("Choose from")
895 assert "Error: Missing option '--foo'. " in error
896 assert "Choose from" in separator
897 assert "foo" in choices
898 assert "bar" in choices
899
900
901 def test_missing_envvar(runner):
902 cli = click.Command(
903 "cli", params=[click.Option(["--foo"], envvar="bar", required=True)]
904 )
905 result = runner.invoke(cli)
906 assert result.exit_code == 2
907 assert "Error: Missing option '--foo'." in result.output
908 cli = click.Command(
909 "cli",
910 params=[click.Option(["--foo"], envvar="bar", show_envvar=True, required=True)],
911 )
912 result = runner.invoke(cli)
913 assert result.exit_code == 2
914 assert "Error: Missing option '--foo' (env var: 'bar')." in result.output
915
916 cli = click.Command(
917 "cli", params=[click.Option(["--foo"], show_envvar=True, required=True)]
918 )
919 result = runner.invoke(cli)
920 assert result.exit_code == 2
921 assert "Error: Missing option '--foo'." in result.output
922
923
924 def test_case_insensitive_choice(runner):
925 @click.command()
926 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))
927 def cmd(foo):
928 click.echo(foo)
929
930 result = runner.invoke(cmd, ["--foo", "apple"])
931 assert result.exit_code == 0
932 assert result.output == "Apple\n"
933
934 result = runner.invoke(cmd, ["--foo", "oRANGe"])
935 assert result.exit_code == 0
936 assert result.output == "Orange\n"
937
938 result = runner.invoke(cmd, ["--foo", "Apple"])
939 assert result.exit_code == 0
940 assert result.output == "Apple\n"
941
942 @click.command()
943 @click.option("--foo", type=click.Choice(["Orange", "Apple"]))
944 def cmd2(foo):
945 click.echo(foo)
946
947 result = runner.invoke(cmd2, ["--foo", "apple"])
948 assert result.exit_code == 2
949
950 result = runner.invoke(cmd2, ["--foo", "oRANGe"])
951 assert result.exit_code == 2
952
953 result = runner.invoke(cmd2, ["--foo", "Apple"])
954 assert result.exit_code == 0
955
956
957 def test_case_insensitive_choice_returned_exactly(runner):
958 @click.command()
959 @click.option("--foo", type=click.Choice(["Orange", "Apple"], case_sensitive=False))
960 def cmd(foo):
961 click.echo(foo)
962
963 result = runner.invoke(cmd, ["--foo", "apple"])
964 assert result.exit_code == 0
965 assert result.output == "Apple\n"
966
967
968 def test_option_help_preserve_paragraphs(runner):
969 @click.command()
970 @click.option(
971 "-C",
972 "--config",
973 type=click.Path(),
974 help="""Configuration file to use.
975
976 If not given, the environment variable CONFIG_FILE is consulted
977 and used if set. If neither are given, a default configuration
978 file is loaded.""",
979 )
980 def cmd(config):
981 pass
982
983 result = runner.invoke(cmd, ["--help"])
984 assert result.exit_code == 0
985 i = " " * 21
986 assert (
987 " -C, --config PATH Configuration file to use.\n"
988 f"{i}\n"
989 f"{i}If not given, the environment variable CONFIG_FILE is\n"
990 f"{i}consulted and used if set. If neither are given, a default\n"
991 f"{i}configuration file is loaded."
992 ) in result.output
993
994
995 def test_argument_custom_class(runner):
996 class CustomArgument(click.Argument):
997 def get_default(self, ctx, call=True):
998 """a dumb override of a default value for testing"""
999 return "I am a default"
1000
1001 @click.command()
1002 @click.argument("testarg", cls=CustomArgument, default="you wont see me")
1003 def cmd(testarg):
1004 click.echo(testarg)
1005
1006 result = runner.invoke(cmd)
1007 assert "I am a default" in result.output
1008 assert "you wont see me" not in result.output
1009
1010
1011 def test_option_custom_class(runner):
1012 class CustomOption(click.Option):
1013 def get_help_record(self, ctx):
1014 """a dumb override of a help text for testing"""
1015 return ("--help", "I am a help text")
1016
1017 @click.command()
1018 @click.option("--testoption", cls=CustomOption, help="you wont see me")
1019 def cmd(testoption):
1020 click.echo(testoption)
1021
1022 result = runner.invoke(cmd, ["--help"])
1023 assert "I am a help text" in result.output
1024 assert "you wont see me" not in result.output
1025
1026
1027 @pytest.mark.parametrize(
1028 ("param_decl", "option_kwargs", "pass_argv"),
1029 (
1030 # there is a large potential parameter space to explore here
1031 # this is just a very small sample of it
1032 ("--opt", {}, []),
1033 ("--opt", {"multiple": True}, []),
1034 ("--opt", {"is_flag": True}, []),
1035 ("--opt/--no-opt", {"is_flag": True, "default": None}, []),
1036 ("--req", {"is_flag": True, "required": True}, ["--req"]),
1037 ),
1038 )
1039 def test_option_custom_class_can_override_type_cast_value_and_never_sees_unset(
1040 runner, param_decl, option_kwargs, pass_argv
1041 ):
1042 """
1043 Test that overriding type_cast_value is supported
1044
1045 In particular, the option is never passed an UNSET sentinel value.
1046 """
1047
1048 class CustomOption(click.Option):
1049 def type_cast_value(self, ctx, value):
1050 assert value is not UNSET
1051 return value
1052
1053 @click.command()
1054 @click.option("myparam", param_decl, **option_kwargs, cls=CustomOption)
1055 def cmd(myparam):
1056 click.echo("ok")
1057
1058 result = runner.invoke(cmd, pass_argv)
1059 assert not result.exception
1060 assert result.exit_code == 0
1061
1062
1063 def test_option_custom_class_reusable(runner):
1064 """Ensure we can reuse a custom class option. See Issue #926"""
1065
1066 class CustomOption(click.Option):
1067 def get_help_record(self, ctx):
1068 """a dumb override of a help text for testing"""
1069 return ("--help", "I am a help text")
1070
1071 # Assign to a variable to re-use the decorator.
1072 testoption = click.option("--testoption", cls=CustomOption, help="you wont see me")
1073
1074 @click.command()
1075 @testoption
1076 def cmd1(testoption):
1077 click.echo(testoption)
1078
1079 @click.command()
1080 @testoption
1081 def cmd2(testoption):
1082 click.echo(testoption)
1083
1084 # Both of the commands should have the --help option now.
1085 for cmd in (cmd1, cmd2):
1086 result = runner.invoke(cmd, ["--help"])
1087 assert "I am a help text" in result.output
1088 assert "you wont see me" not in result.output
1089
1090
1091 @pytest.mark.parametrize("custom_class", (True, False))
1092 @pytest.mark.parametrize(
1093 ("name_specs", "expected"),
1094 (
1095 (
1096 ("-h", "--help"),
1097 " -h, --help Show this message and exit.\n",
1098 ),
1099 (
1100 ("-h",),
1101 " -h Show this message and exit.\n"
1102 " --help Show this message and exit.\n",
1103 ),
1104 (
1105 ("--help",),
1106 " --help Show this message and exit.\n",
1107 ),
1108 ),
1109 )
1110 def test_help_option_custom_names_and_class(runner, custom_class, name_specs, expected):
1111 class CustomHelpOption(click.Option):
1112 pass
1113
1114 option_attrs = {}
1115 if custom_class:
1116 option_attrs["cls"] = CustomHelpOption
1117
1118 @click.command()
1119 @click.help_option(*name_specs, **option_attrs)
1120 def cmd():
1121 pass
1122
1123 for arg in name_specs:
1124 result = runner.invoke(cmd, [arg])
1125 assert not result.exception
1126 assert result.exit_code == 0
1127 assert expected in result.output
1128
1129
1130 def test_bool_flag_with_type(runner):
1131 @click.command()
1132 @click.option("--shout/--no-shout", default=False, type=bool)
1133 def cmd(shout):
1134 pass
1135
1136 result = runner.invoke(cmd)
1137 assert not result.exception
1138
1139
1140 def test_aliases_for_flags(runner):
1141 @click.command()
1142 @click.option("--warnings/--no-warnings", " /-W", default=True)
1143 def cli(warnings):
1144 click.echo(warnings)
1145
1146 result = runner.invoke(cli, ["--warnings"])
1147 assert result.output == "True\n"
1148 result = runner.invoke(cli, ["--no-warnings"])
1149 assert result.output == "False\n"
1150 result = runner.invoke(cli, ["-W"])
1151 assert result.output == "False\n"
1152
1153 @click.command()
1154 @click.option("--warnings/--no-warnings", "-w", default=True)
1155 def cli_alt(warnings):
1156 click.echo(warnings)
1157
1158 result = runner.invoke(cli_alt, ["--warnings"])
1159 assert result.output == "True\n"
1160 result = runner.invoke(cli_alt, ["--no-warnings"])
1161 assert result.output == "False\n"
1162 result = runner.invoke(cli_alt, ["-w"])
1163 assert result.output == "True\n"
1164
1165
1166 @pytest.mark.parametrize(
1167 "option_args,expected",
1168 [
1169 (["--aggressive", "--all", "-a"], "aggressive"),
1170 (["--first", "--second", "--third", "-a", "-b", "-c"], "first"),
1171 (["--apple", "--banana", "--cantaloupe", "-a", "-b", "-c"], "apple"),
1172 (["--cantaloupe", "--banana", "--apple", "-c", "-b", "-a"], "cantaloupe"),
1173 (["-a", "-b", "-c"], "a"),
1174 (["-c", "-b", "-a"], "c"),
1175 (["-a", "--apple", "-b", "--banana", "-c", "--cantaloupe"], "apple"),
1176 (["-c", "-a", "--cantaloupe", "-b", "--banana", "--apple"], "cantaloupe"),
1177 (["--from", "-f", "_from"], "_from"),
1178 (["--return", "-r", "_ret"], "_ret"),
1179 ],
1180 )
1181 def test_option_names(runner, option_args, expected):
1182 @click.command()
1183 @click.option(*option_args, is_flag=True)
1184 def cmd(**kwargs):
1185 click.echo(str(kwargs[expected]))
1186
1187 assert cmd.params[0].name == expected
1188
1189 for form in option_args:
1190 if form.startswith("-"):
1191 result = runner.invoke(cmd, [form])
1192 assert result.output == "True\n"
1193
1194
1195 def test_flag_duplicate_names(runner):
1196 with pytest.raises(ValueError, match="cannot use the same flag for true/false"):
1197 click.Option(["--foo/--foo"], default=False)
1198
1199
1200 @pytest.mark.parametrize(("default", "expect"), [(False, "no-cache"), (True, "cache")])
1201 def test_show_default_boolean_flag_name(runner, default, expect):
1202 """When a boolean flag has distinct True/False opts, it should show
1203 the default opt name instead of the default value. It should only
1204 show one name even if multiple are declared.
1205 """
1206 opt = click.Option(
1207 ("--cache/--no-cache", "--c/--nc"),
1208 default=default,
1209 show_default=True,
1210 help="Enable/Disable the cache.",
1211 )
1212 ctx = click.Context(click.Command("test"))
1213 assert opt.get_help_extra(ctx) == {"default": expect}
1214 message = opt.get_help_record(ctx)[1]
1215 assert f"[default: {expect}]" in message
1216
1217
1218 def test_show_true_default_boolean_flag_value(runner):
1219 """When a boolean flag only has one opt and its default is True,
1220 it will show the default value, not the opt name.
1221 """
1222 opt = click.Option(
1223 ("--cache",),
1224 is_flag=True,
1225 show_default=True,
1226 default=True,
1227 help="Enable the cache.",
1228 )
1229 ctx = click.Context(click.Command("test"))
1230 assert opt.get_help_extra(ctx) == {"default": "True"}
1231 message = opt.get_help_record(ctx)[1]
1232 assert "[default: True]" in message
1233
1234
1235 @pytest.mark.parametrize("default", [False, None])
1236 def test_hide_false_default_boolean_flag_value(runner, default):
1237 """When a boolean flag only has one opt and its default is False or
1238 None, it will not show the default
1239 """
1240 opt = click.Option(
1241 ("--cache",),
1242 is_flag=True,
1243 show_default=True,
1244 default=default,
1245 help="Enable the cache.",
1246 )
1247 ctx = click.Context(click.Command("test"))
1248 assert opt.get_help_extra(ctx) == {}
1249 message = opt.get_help_record(ctx)[1]
1250 assert "[default: " not in message
1251
1252
1253 def test_show_default_string(runner):
1254 """When show_default is a string show that value as default."""
1255 opt = click.Option(["--limit"], show_default="unlimited")
1256 ctx = click.Context(click.Command("cli"))
1257 assert opt.get_help_extra(ctx) == {"default": "(unlimited)"}
1258 message = opt.get_help_record(ctx)[1]
1259 assert "[default: (unlimited)]" in message
1260
1261
1262 def test_string_show_default_shows_custom_string_in_prompt(runner):
1263 @click.command()
1264 @click.option(
1265 "--arg1", show_default="custom", prompt=True, default="my-default-value"
1266 )
1267 def cmd(arg1):
1268 pass
1269
1270 result = runner.invoke(cmd, input="my-input", standalone_mode=False)
1271 assert "(custom)" in result.output
1272 assert "my-default-value" not in result.output
1273
1274
1275 class _StrictEq:
1276 """Object whose ``__eq__`` raises on string comparison (like semver.Version)."""
1277
1278 def __eq__(self, other):
1279 if isinstance(other, str):
1280 raise ValueError("cannot compare to string")
1281 return NotImplemented
1282
1283 def __str__(self):
1284 return "strict"
1285
1286
1287 @pytest.mark.parametrize(
1288 ("default", "expected"),
1289 [
1290 ("", '[default: ""]'),
1291 (_StrictEq(), "[default: strict]"),
1292 ],
1293 ids=["empty-string", "non-string-comparable-object"],
1294 )
1295 def test_show_default_with_empty_string(runner, default, expected):
1296 """The empty-string check in help rendering must not break on objects
1297 whose ``__eq__`` raises for string operands.
1298
1299 Regression test for https://github.com/pallets/click/issues/3298.
1300 """
1301 opt = click.Option(["--limit"], default=default, show_default=True)
1302 ctx = click.Context(click.Command("cli"))
1303 message = opt.get_help_record(ctx)[1]
1304 assert expected in message
1305
1306
1307 def test_do_not_show_no_default(runner):
1308 """When show_default is True and no default is set do not show None."""
1309 opt = click.Option(["--limit"], show_default=True)
1310 ctx = click.Context(click.Command("cli"))
1311 assert opt.get_help_extra(ctx) == {}
1312 message = opt.get_help_record(ctx)[1]
1313 assert "[default: None]" not in message
1314
1315
1316 def test_do_not_show_default_empty_multiple():
1317 """When show_default is True and multiple=True is set, it should not
1318 print empty default value in --help output.
1319 """
1320 opt = click.Option(["-a"], multiple=True, help="values", show_default=True)
1321 ctx = click.Context(click.Command("cli"))
1322 assert opt.get_help_extra(ctx) == {}
1323 message = opt.get_help_record(ctx)[1]
1324 assert message == "values"
1325
1326
1327 @pytest.mark.parametrize(
1328 ("ctx_value", "opt_value", "extra_value", "expect"),
1329 [
1330 (None, None, {}, False),
1331 (None, False, {}, False),
1332 (None, True, {"default": "1"}, True),
1333 (False, None, {}, False),
1334 (False, False, {}, False),
1335 (False, True, {"default": "1"}, True),
1336 (True, None, {"default": "1"}, True),
1337 (True, False, {}, False),
1338 (True, True, {"default": "1"}, True),
1339 (False, "one", {"default": "(one)"}, True),
1340 ],
1341 )
1342 def test_show_default_precedence(ctx_value, opt_value, extra_value, expect):
1343 ctx = click.Context(click.Command("test"), show_default=ctx_value)
1344 opt = click.Option("-a", default=1, help="value", show_default=opt_value)
1345 assert opt.get_help_extra(ctx) == extra_value
1346 help = opt.get_help_record(ctx)[1]
1347 assert ("default:" in help) is expect
1348
1349
1350 @pytest.mark.parametrize(
1351 ("args", "expect"),
1352 [
1353 (None, (None, None, ())),
1354 (["--opt"], ("flag", None, ())),
1355 (["--opt", "-a", 42], ("flag", "42", ())),
1356 (["--opt", "test", "-a", 42], ("test", "42", ())),
1357 (["--opt=test", "-a", 42], ("test", "42", ())),
1358 (["-o"], ("flag", None, ())),
1359 (["-o", "-a", 42], ("flag", "42", ())),
1360 (["-o", "test", "-a", 42], ("test", "42", ())),
1361 (["-otest", "-a", 42], ("test", "42", ())),
1362 (["a", "b", "c"], (None, None, ("a", "b", "c"))),
1363 (["--opt", "a", "b", "c"], ("a", None, ("b", "c"))),
1364 (["--opt", "test"], ("test", None, ())),
1365 (["-otest", "a", "b", "c"], ("test", None, ("a", "b", "c"))),
1366 (["--opt=test", "a", "b", "c"], ("test", None, ("a", "b", "c"))),
1367 ],
1368 )
1369 def test_option_with_optional_value(runner, args, expect):
1370 @click.command()
1371 @click.option("-o", "--opt", is_flag=False, flag_value="flag")
1372 @click.option("-a")
1373 @click.argument("b", nargs=-1)
1374 def cli(opt, a, b):
1375 return opt, a, b
1376
1377 result = runner.invoke(cli, args, standalone_mode=False, catch_exceptions=False)
1378 assert result.return_value == expect
1379
1380
1381 def test_multiple_option_with_optional_value(runner):
1382 cli = click.Command(
1383 "cli",
1384 params=[
1385 click.Option(["-f"], is_flag=False, flag_value="flag", multiple=True),
1386 click.Option(["-a"]),
1387 click.Argument(["b"], nargs=-1),
1388 ],
1389 callback=lambda **kwargs: kwargs,
1390 )
1391 result = runner.invoke(
1392 cli,
1393 ["-f", "-f", "other", "-f", "-a", "1", "a", "b"],
1394 standalone_mode=False,
1395 catch_exceptions=False,
1396 )
1397 assert result.return_value == {
1398 "f": ("flag", "other", "flag"),
1399 "a": "1",
1400 "b": ("a", "b"),
1401 }
1402
1403
1404 def test_type_from_flag_value():
1405 param = click.Option(["-a", "x"], default=True, flag_value=4)
1406 assert param.type is click.INT
1407 param = click.Option(["-b", "x"], flag_value=8)
1408 assert param.type is click.INT
1409
1410
1411 @pytest.mark.parametrize(
1412 ("opt_params", "args", "expected"),
1413 [
1414 # The type passed to the option is responsible to converting the value, whether
1415 # we pass the option flag or not.
1416 ({"type": bool}, [], False),
1417 ({"type": bool}, ["--foo"], True),
1418 ({"type": click.BOOL}, [], False),
1419 ({"type": click.BOOL}, ["--foo"], True),
1420 ({"type": str}, [], None),
1421 ({"type": str}, ["--foo"], "True"),
1422 # Default value is given as-is to the --foo option when it is not passed,
1423 # whatever the type. Now if --foo is passed, the value is always True, whatever
1424 # the type. In both case the type of the option is responsible for the
1425 # conversion of the value.
1426 ({"type": bool, "default": True}, [], True),
1427 ({"type": bool, "default": True}, ["--foo"], True),
1428 ({"type": bool, "default": False}, [], False),
1429 ({"type": bool, "default": False}, ["--foo"], True),
1430 # ({"type": bool, "default": "foo"}, [], "foo"),
1431 ({"type": bool, "default": "foo"}, ["--foo"], True),
1432 ({"type": bool, "default": None}, [], None),
1433 ({"type": bool, "default": None}, ["--foo"], True),
1434 ({"type": click.BOOL, "default": True}, [], True),
1435 ({"type": click.BOOL, "default": True}, ["--foo"], True),
1436 ({"type": click.BOOL, "default": False}, [], False),
1437 ({"type": click.BOOL, "default": False}, ["--foo"], True),
1438 # ({"type": click.BOOL, "default": "foo"}, [], "foo"),
1439 ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),
1440 ({"type": click.BOOL, "default": None}, [], None),
1441 ({"type": click.BOOL, "default": None}, ["--foo"], True),
1442 ({"type": str, "default": True}, [], "True"),
1443 ({"type": str, "default": True}, ["--foo"], "True"),
1444 ({"type": str, "default": False}, [], "False"),
1445 ({"type": str, "default": False}, ["--foo"], "True"),
1446 ({"type": str, "default": "foo"}, [], "foo"),
1447 ({"type": str, "default": "foo"}, ["--foo"], "True"),
1448 ({"type": str, "default": None}, [], None),
1449 ({"type": str, "default": None}, ["--foo"], "True"),
1450 # Flag value is given as-is to the --foo option when it is passed, then
1451 # converted by the option type.
1452 ({"type": bool, "flag_value": True}, [], False),
1453 ({"type": bool, "flag_value": True}, ["--foo"], True),
1454 ({"type": bool, "flag_value": False}, [], False),
1455 ({"type": bool, "flag_value": False}, ["--foo"], False),
1456 ({"type": bool, "flag_value": None}, [], False),
1457 ({"type": bool, "flag_value": None}, ["--foo"], None),
1458 ({"type": click.BOOL, "flag_value": True}, [], False),
1459 ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),
1460 ({"type": click.BOOL, "flag_value": False}, [], False),
1461 ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),
1462 ({"type": click.BOOL, "flag_value": None}, [], False),
1463 ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),
1464 ({"type": str, "flag_value": True}, [], None),
1465 ({"type": str, "flag_value": True}, ["--foo"], "True"),
1466 ({"type": str, "flag_value": False}, [], None),
1467 ({"type": str, "flag_value": False}, ["--foo"], "False"),
1468 ({"type": str, "flag_value": "foo"}, [], None),
1469 ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),
1470 ({"type": str, "flag_value": None}, [], None),
1471 ({"type": str, "flag_value": None}, ["--foo"], None),
1472 # Not passing --foo returns the default value as-is, in its Python type, then
1473 # converted by the option type. For boolean flags, default=True is a literal
1474 # value, not a sentinel meaning "activate flag". So it is NOT substituted with
1475 # flag_value. See: https://github.com/pallets/click/issues/3111
1476 # https://github.com/pallets/click/pull/3239
1477 ({"type": bool, "default": True, "flag_value": True}, [], True),
1478 ({"type": bool, "default": True, "flag_value": False}, [], True),
1479 ({"type": bool, "default": False, "flag_value": True}, [], False),
1480 ({"type": bool, "default": False, "flag_value": False}, [], False),
1481 ({"type": bool, "default": None, "flag_value": True}, [], None),
1482 ({"type": bool, "default": None, "flag_value": False}, [], None),
1483 ({"type": str, "default": True, "flag_value": True}, [], "True"),
1484 ({"type": str, "default": True, "flag_value": False}, [], "False"),
1485 ({"type": str, "default": False, "flag_value": True}, [], "False"),
1486 ({"type": str, "default": False, "flag_value": False}, [], "False"),
1487 ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),
1488 ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),
1489 ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),
1490 ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),
1491 ({"type": str, "default": None, "flag_value": True}, [], None),
1492 ({"type": str, "default": None, "flag_value": False}, [], None),
1493 # Passing --foo returns the flag_value that was explicitly set by the user,
1494 # with its Python type, but still converted by the option type.
1495 ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),
1496 ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),
1497 ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),
1498 ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),
1499 ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),
1500 ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),
1501 ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),
1502 ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),
1503 ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),
1504 ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),
1505 ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),
1506 ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),
1507 ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),
1508 ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),
1509 ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),
1510 ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),
1511 ],
1512 )
1513 def test_flag_value_and_default(runner, opt_params, args, expected):
1514 @click.command()
1515 @click.option("--foo", is_flag=True, **opt_params)
1516 def cmd(foo):
1517 click.echo(repr(foo), nl=False)
1518
1519 result = runner.invoke(cmd, args)
1520 assert result.output == repr(expected)
1521
1522
1523 @pytest.mark.parametrize(
1524 ("args", "opts"),
1525 [
1526 ([], {"type": bool, "default": "foo"}),
1527 ([], {"type": click.BOOL, "default": "foo"}),
1528 (["--foo"], {"type": bool, "flag_value": "foo"}),
1529 (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),
1530 ],
1531 )
1532 def test_invalid_flag_definition(runner, args, opts):
1533 @click.command()
1534 @click.option("--foo", is_flag=True, **opts)
1535 def cmd(foo):
1536 click.echo(foo)
1537
1538 result = runner.invoke(cmd, args)
1539 assert (
1540 "Error: Invalid value for '--foo': 'foo' is not a valid boolean"
1541 in result.output
1542 )
1543
1544
1545 @pytest.mark.parametrize(
1546 ("default", "args", "expected"),
1547 # These test cases are similar to the ones in
1548 # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync.
1549 (
1550 # Each option is returning its own flag_value, whatever the default is.
1551 (True, ["--js"], "js"),
1552 (True, ["--xml"], "xml"),
1553 (False, ["--js"], "js"),
1554 (False, ["--xml"], "xml"),
1555 (None, ["--js"], "js"),
1556 (None, ["--xml"], "xml"),
1557 (UNSET, ["--js"], "js"),
1558 (UNSET, ["--xml"], "xml"),
1559 # Check that the last option wins when both are specified.
1560 (True, ["--js", "--xml"], "xml"),
1561 (True, ["--xml", "--js"], "js"),
1562 # Check that the default is returned as-is when no option is specified.
1563 ("js", [], "js"),
1564 ("xml", [], "xml"),
1565 ("jS", [], "jS"),
1566 ("xMl", [], "xMl"),
1567 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),
1568 (None, [], None),
1569 # Special case: UNSET is not provided as-is to the callback, but normalized to
1570 # None.
1571 (UNSET, [], None),
1572 # Special case: if default=True and flag_value is set, the value returned is the
1573 # flag_value, not the True Python value itself.
1574 (True, [], "js"),
1575 # Non-string defaults are process as strings by the default Parameter's type.
1576 (False, [], "False"),
1577 (42, [], "42"),
1578 (12.3, [], "12.3"),
1579 ),
1580 )
1581 def test_default_dual_option_callback(runner, default, args, expected):
1582 """Check how default is processed by the callback when options compete for the same
1583 variable name.
1584
1585 Reproduction of the issue reported in
1586 https://github.com/pallets/click/pull/3030#discussion_r2271571819
1587
1588 .. hint::
1589 Similar to ``test_basic.py::test_flag_value_dual_options``.
1590
1591 ``test_defaults.py::test_shared_param_prefers_first_default``
1592 is a smoke-test complement that exercises both default placements.
1593 """
1594
1595 def _my_func(ctx, param, value):
1596 # Print the value received by the callback as-is, so we can check for it.
1597 return f"Callback value: {value!r}"
1598
1599 @click.command()
1600 @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)
1601 @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)
1602 def main(fmt):
1603 click.secho(fmt, nl=False)
1604
1605 result = runner.invoke(main, args)
1606 assert result.output == f"Callback value: {expected!r}"
1607 assert result.exit_code == 0
1608
1609
1610 @pytest.mark.parametrize(
1611 ("flag_value", "envvar_value", "expected"),
1612 [
1613 # The envvar match exactly the flag value and is case-sensitive.
1614 ("bar", "bar", "bar"),
1615 ("BAR", "BAR", "BAR"),
1616 (" bar ", " bar ", " bar "),
1617 ("42", "42", "42"),
1618 ("None", "None", "None"),
1619 ("True", "True", "True"),
1620 ("False", "False", "False"),
1621 ("true", "true", "true"),
1622 ("false", "false", "false"),
1623 ("A B", "A B", "A B"),
1624 (" 1 2 ", " 1 2 ", " 1 2 "),
1625 ("9.3", "9.3", "9.3"),
1626 ("a;n", "a;n", "a;n"),
1627 ("x:y", "x:y", "x:y"),
1628 ("i/o", "i/o", "i/o"),
1629 # Empty or absent envvar is consider unset, so the flag default value is
1630 # returned, which is None in this case.
1631 ("bar", "", None),
1632 ("bar", None, None),
1633 ("BAR", "", None),
1634 ("BAR", None, None),
1635 (" bar ", "", None),
1636 (" bar ", None, None),
1637 (42, "", None),
1638 (42, None, None),
1639 ("42", "", None),
1640 ("42", None, None),
1641 (None, "", None),
1642 (None, None, None),
1643 ("None", "", None),
1644 ("None", None, None),
1645 (True, "", None),
1646 (True, None, None),
1647 ("True", "", None),
1648 ("True", None, None),
1649 ("true", "", None),
1650 ("true", None, None),
1651 (False, "", None),
1652 (False, None, None),
1653 ("False", "", None),
1654 ("False", None, None),
1655 ("false", "", None),
1656 ("false", None, None),
1657 # Activate the flag with a value recognized as True by the envvar, which
1658 # returns the flag_value.
1659 ("bar", "True", "bar"),
1660 ("bar", "true", "bar"),
1661 ("bar", "trUe", "bar"),
1662 ("bar", " TRUE ", "bar"),
1663 ("bar", "1", "bar"),
1664 ("bar", "yes", "bar"),
1665 ("bar", "on", "bar"),
1666 ("bar", "t", "bar"),
1667 ("bar", "y", "bar"),
1668 # Deactivating the flag with a value recognized as False by the envvar, which
1669 # explicitly return the 'False' as the option is explicitly declared as a
1670 # string.
1671 ("bar", "False", "False"),
1672 ("bar", "false", "False"),
1673 ("bar", "faLse", "False"),
1674 ("bar", " FALSE ", "False"),
1675 ("bar", "0", "False"),
1676 ("bar", "no", "False"),
1677 ("bar", "off", "False"),
1678 ("bar", "f", "False"),
1679 ("bar", "n", "False"),
1680 # Any other value than the flag_value, or a recogned True or False value, fails
1681 # to explicitly activate or deactivate the flag. So the flag default value is
1682 # returned, which is None in this case.
1683 ("bar", " bar ", None),
1684 ("bar", "BAR", None),
1685 ("bar", "random", None),
1686 ("bar", "bar random", None),
1687 ("bar", "random bar", None),
1688 ("BAR", "bar", None),
1689 (" bar ", "bar", None),
1690 (" bar ", "BAR", None),
1691 (42, "42", None),
1692 (42, "foo", None),
1693 (None, "foo", None),
1694 ("None", "foo", None),
1695 ],
1696 )
1697 def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):
1698 """Ensure that flag_value is recognized by the envvar."""
1699
1700 @click.command()
1701 @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER")
1702 def cmd(upper):
1703 click.echo(repr(upper), nl=False)
1704
1705 result = runner.invoke(cmd, env={"UPPER": envvar_value})
1706 assert result.exit_code == 0
1707 assert result.output == repr(expected)
1708
1709
1710 @pytest.mark.parametrize(
1711 ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"),
1712 [
1713 # Not boolean flags.
1714 ("-a", {"type": int}, False, False),
1715 ("-a", {"type": bool}, False, False),
1716 ("-a", {"default": True}, False, False),
1717 ("-a", {"default": False}, False, False),
1718 ("-a", {"flag_value": 1}, True, False),
1719 # Boolean flags.
1720 ("-a", {"is_flag": True}, True, True),
1721 ("-a/-A", {}, True, True),
1722 ("-a", {"flag_value": True}, True, True),
1723 # Non-flag with flag_value.
1724 ("-a", {"is_flag": False, "flag_value": 1}, False, False),
1725 ],
1726 )
1727 def test_flag_auto_detection(
1728 opt_decls, opt_params, expect_is_flag, expect_is_bool_flag
1729 ):
1730 option = Option([opt_decls], **opt_params)
1731 assert option.is_flag is expect_is_flag
1732 assert option.is_bool_flag is expect_is_bool_flag
1733
1734
1735 @pytest.mark.parametrize(
1736 ("kwargs", "message"),
1737 [
1738 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),
1739 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),
1740 ],
1741 )
1742 def test_invalid_flag_combinations(runner, kwargs, message):
1743 with pytest.raises(TypeError) as e:
1744 click.Option(["-a"], **kwargs)
1745
1746 assert message in str(e.value)
1747
1748
1749 def test_non_flag_with_non_negatable_default(runner):
1750 class NonNegatable:
1751 def __bool__(self):
1752 raise ValueError("Cannot negate this object")
1753
1754 @click.command()
1755 @click.option("--foo", default=NonNegatable())
1756 def cmd(foo):
1757 pass
1758
1759 result = runner.invoke(cmd)
1760 assert result.exit_code == 0
1761
1762
1763 class HashType(enum.Enum):
1764 MD5 = "MD5"
1765 SHA1 = "SHA1"
1766 SHA256 = "SHA-256"
1767
1768
1769 class Number(enum.IntEnum):
1770 ONE = enum.auto()
1771 TWO = enum.auto()
1772
1773
1774 class Letter(enum.StrEnum):
1775 NAME_1 = "Value-1"
1776 NAME_2 = "Value_2"
1777 NAME_3 = "42_value"
1778
1779
1780 class Color(enum.Flag):
1781 RED = enum.auto()
1782 GREEN = enum.auto()
1783 BLUE = enum.auto()
1784
1785
1786 class ColorInt(enum.IntFlag):
1787 RED = enum.auto()
1788 GREEN = enum.auto()
1789 BLUE = enum.auto()
1790
1791
1792 @pytest.mark.parametrize(
1793 ("choices", "metavar"),
1794 [
1795 (["foo", "bar"], "[TEXT]"),
1796 ([1, 2], "[INTEGER]"),
1797 ([1.0, 2.0], "[FLOAT]"),
1798 ([True, False], "[BOOLEAN]"),
1799 (["foo", 1], "[TEXT|INTEGER]"),
1800 (HashType, "[HASHTYPE]"),
1801 (Number, "[NUMBER]"),
1802 (Letter, "[LETTER]"),
1803 (Color, "[COLOR]"),
1804 (ColorInt, "[COLORINT]"),
1805 ],
1806 )
1807 def test_choice_usage_rendering(runner, choices, metavar):
1808 """BY default ``--help`` prints choice's values in the usage message.
1809
1810 But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of
1811 values.
1812
1813 Also check that usage error message always suggests the actual values.
1814 """
1815
1816 @click.command()
1817 @click.option("-g", type=click.Choice(choices))
1818 def cli_with_choices(g):
1819 pass
1820
1821 @click.command()
1822 @click.option("-g", type=click.Choice(choices), show_choices=False)
1823 def cli_without_choices(g):
1824 pass
1825
1826 display_values = tuple(
1827 i.name if isinstance(i, enum.Enum) else str(i) for i in choices
1828 )
1829
1830 # Check that the choices values are rendered as-is in the usage message.
1831 result = runner.invoke(cli_with_choices, ["--help"])
1832 assert f"[{'|'.join(display_values)}]" in result.stdout
1833 assert not result.stderr
1834 assert result.exit_code == 0
1835
1836 # Check that the metavar is rendered instead of the choices values themselves.
1837 result = runner.invoke(cli_without_choices, ["--help"])
1838 assert metavar in result.stdout
1839 assert not result.stderr
1840 assert result.exit_code == 0
1841
1842 # Check the usage error message suggests the actual accepted values.
1843 for cli in (cli_with_choices, cli_without_choices):
1844 result = runner.invoke(cli, ["-g", "random"])
1845 assert (
1846 "\n\nError: Invalid value for '-g': 'random' is not one of "
1847 f"{', '.join(map(repr, display_values))}.\n" in result.stderr
1848 )
1849 assert not result.stdout
1850 assert result.exit_code == 2
1851
1852
1853 @pytest.mark.parametrize(
1854 ("choices", "default", "default_string"),
1855 [
1856 (["foo", "bar"], "bar", "bar"),
1857 # The default value is not enforced to be in the choices.
1858 (["foo", "bar"], "random", "random"),
1859 # None cannot be a default value as-is: it left the default value as unset.
1860 (["foo", "bar"], None, None),
1861 ([0, 1], 0, "0"),
1862 # Values are not coerced to the type of the choice, even if equivalent.
1863 ([0, 1], 0.0, "0.0"),
1864 ([1, 2], 2, "2"),
1865 ([1.0, 2.0], 2, "2"),
1866 ([1.0, 2.0], 2.0, "2.0"),
1867 ([True, False], True, "True"),
1868 ([True, False], False, "False"),
1869 (["foo", 1], "foo", "foo"),
1870 (["foo", 1], 1, "1"),
1871 # Enum choices are rendered as their names, not values.
1872 # See: https://github.com/pallets/click/issues/2911
1873 (HashType, HashType.SHA1, "SHA1"),
1874 # Enum choices allow defaults strings that are their names.
1875 (HashType, HashType.SHA256, "SHA256"),
1876 (HashType, "SHA256", "SHA256"),
1877 (Number, Number.TWO, "TWO"),
1878 (Number, "TWO", "TWO"),
1879 (Letter, Letter.NAME_1, "NAME_1"),
1880 (Letter, Letter.NAME_2, "NAME_2"),
1881 (Letter, Letter.NAME_3, "NAME_3"),
1882 (Letter, "NAME_1", "NAME_1"),
1883 (Letter, "NAME_2", "NAME_2"),
1884 (Letter, "NAME_3", "NAME_3"),
1885 (Color, Color.GREEN, "GREEN"),
1886 (Color, "GREEN", "GREEN"),
1887 (ColorInt, ColorInt.GREEN, "GREEN"),
1888 (ColorInt, "GREEN", "GREEN"),
1889 ],
1890 )
1891 def test_choice_default_rendering(runner, choices, default, default_string):
1892 @click.command()
1893 @click.option("-g", type=click.Choice(choices), default=default, show_default=True)
1894 def cli_with_choices(g):
1895 pass
1896
1897 # Check that the default value is kept normalized to the type of the choice.
1898 assert cli_with_choices.params[0].default == default
1899
1900 result = runner.invoke(cli_with_choices, ["--help"])
1901 extra_usage = f"[default: {default_string}]"
1902 if default_string is None:
1903 assert extra_usage not in result.output
1904 else:
1905 assert extra_usage in result.output
1906
1907
1908 @pytest.mark.parametrize(
1909 "opts_one,opts_two",
1910 [
1911 # No duplicate shortnames
1912 (
1913 ("-a", "--aardvark"),
1914 ("-a", "--avocado"),
1915 ),
1916 # No duplicate long names
1917 (
1918 ("-a", "--aardvark"),
1919 ("-b", "--aardvark"),
1920 ),
1921 ],
1922 )
1923 def test_duplicate_names_warning(runner, opts_one, opts_two):
1924 @click.command()
1925 @click.option(*opts_one)
1926 @click.option(*opts_two)
1927 def cli(one, two):
1928 pass
1929
1930 with pytest.warns(UserWarning):
1931 runner.invoke(cli, [])
1932
1933
1934 OBJECT_SENTINEL = object()
1935 """An object-based sentinel value."""
1936
1937
1938 class EnumSentinel(enum.Enum):
1939 FALSY_SENTINEL = object()
1940
1941 def __bool__(self) -> Literal[False]:
1942 """Force the sentinel to be falsy to make sure it is not caught by Click
1943 internal implementation.
1944
1945 Falsy sentinels have been discussed in:
1946 https://github.com/pallets/click/pull/3030#pullrequestreview-3106604795
1947 https://github.com/pallets/click/pull/3030#pullrequestreview-3108471552
1948 """
1949 return False
1950
1951
1952 # Any kind of sentinel value is recognized by Click as a valid flag value.
1953 @pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))
1954 @pytest.mark.parametrize(
1955 ("args", "expected"),
1956 (
1957 # Option default to None.
1958 ([], None),
1959 # Config has no default value, and no flag value, so it requires an argument.
1960 (
1961 ["--config"],
1962 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),
1963 ),
1964 (
1965 ["--no-config", "--config"],
1966 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),
1967 ),
1968 # Passing --no-config defaults to the sentinel value because of the flag_value,
1969 # and then the custom type receives that sentinel and returns a message.
1970 (["--no-config"], "No configuration file provided."),
1971 # Passing --config with an argument returns the file path.
1972 (["--config", "foo.conf"], "foo.conf"),
1973 # An argument is not allowed for --no-config, so it raises an error.
1974 (
1975 ["--no-config", "foo.conf"],
1976 re.compile(
1977 r"Usage: main \[OPTIONS\]\n"
1978 r"Try 'main --help' for help.\n"
1979 r"\n"
1980 r"Error: Got unexpected extra argument (.+)\n"
1981 ),
1982 ),
1983 # Passing --config with an argument that does not exist raises an error.
1984 (
1985 ["--config", "random-file.conf"],
1986 re.compile(
1987 r"Usage: main \[OPTIONS\]\n"
1988 r"Try 'main --help' for help.\n"
1989 r"\n"
1990 r"Error: Invalid value for '-c' / '--config': "
1991 r"File 'random-file.conf' does not exist.\n"
1992 ),
1993 ),
1994 (
1995 ["--config", "--no-config"],
1996 re.compile(
1997 r"Usage: main \[OPTIONS\]\n"
1998 r"Try 'main --help' for help.\n"
1999 r"\n"
2000 r"Error: Invalid value for '-c' / '--config': "
2001 r"File '--no-config' does not exist.\n"
2002 ),
2003 ),
2004 (
2005 ["--config", "--no-config", "foo.conf"],
2006 re.compile(
2007 r"Usage: main \[OPTIONS\]\n"
2008 r"Try 'main --help' for help.\n"
2009 r"\n"
2010 r"Error: Invalid value for '-c' / '--config': "
2011 r"File '--no-config' does not exist.\n"
2012 ),
2013 ),
2014 # --config is passed last and overrides the --no-config option.
2015 (["--no-config", "--config", "foo.conf"], "foo.conf"),
2016 ),
2017 )
2018 def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected):
2019 """Check that an object-based sentinel, used as a flag value, is returned as-is
2020 to a custom type that is shared by two options, competing for the same variable
2021 name.
2022
2023 A reproduction of
2024 https://github.com/pallets/click/issues/3024#issuecomment-3146511356
2025 """
2026
2027 class ConfigParamType(click.ParamType):
2028 """A custom type that accepts a file path or a sentinel value."""
2029
2030 def convert(self, value, param, ctx):
2031 if value is sentinel:
2032 return "No configuration file provided."
2033 else:
2034 return click.Path(exists=True, dir_okay=False).convert(
2035 value, param, ctx
2036 )
2037
2038 @click.command()
2039 @click.option("-c", "--config", type=ConfigParamType())
2040 @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType())
2041 def main(config):
2042 click.echo(repr(config), nl=False)
2043
2044 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:
2045 if "foo.conf" in args:
2046 named_tempfile.write("Blah blah")
2047 named_tempfile.flush()
2048 args = [named_tempfile.name if a == "foo.conf" else a for a in args]
2049
2050 result = runner.invoke(main, args)
2051
2052 if isinstance(expected, re.Pattern):
2053 assert re.match(expected, result.output)
2054 else:
2055 assert result.output == repr(
2056 named_tempfile.name if expected == "foo.conf" else expected
2057 )
2058
2059
2060 class EngineType(enum.Enum):
2061 OSS = enum.auto()
2062 PRO = enum.auto()
2063 MAX = enum.auto()
2064
2065
2066 class Class1:
2067 pass
2068
2069
2070 class Class2:
2071 pass
2072
2073
2074 @pytest.mark.parametrize(
2075 ("opt_params", "args", "expected"),
2076 [
2077 # Check that the flag value is returned as-is when the option is passed, and
2078 # not normalized to a boolean, even if it is explicitly declared as a flag.
2079 ({"type": EngineType, "flag_value": None}, ["--pro"], None),
2080 (
2081 {"type": EngineType, "is_flag": True, "flag_value": None},
2082 ["--pro"],
2083 None,
2084 ),
2085 ({"type": EngineType, "flag_value": EngineType.OSS}, ["--pro"], EngineType.OSS),
2086 (
2087 {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},
2088 ["--pro"],
2089 EngineType.OSS,
2090 ),
2091 (
2092 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},
2093 ["--pro"],
2094 EngineType.OSS,
2095 ),
2096 # The default value is returned as-is when the option is not passed, whatever
2097 # the flag value.
2098 ({"type": EngineType, "flag_value": None}, [], None),
2099 ({"type": EngineType, "is_flag": True, "flag_value": None}, [], None),
2100 ({"type": EngineType, "flag_value": EngineType.OSS}, [], None),
2101 (
2102 {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},
2103 [],
2104 None,
2105 ),
2106 (
2107 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},
2108 [],
2109 EngineType.OSS,
2110 ),
2111 # The option has not enough parameters to be detected as flag-like, so it
2112 # requires an argument.
2113 (
2114 {"type": EngineType, "default": EngineType.OSS},
2115 ["--pro"],
2116 re.compile(re.escape("Error: Option '--pro' requires an argument.\n")),
2117 ),
2118 ({"type": EngineType, "default": EngineType.OSS}, [], EngineType.OSS),
2119 # If a flag value is set, it is returned instead of the default value.
2120 (
2121 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},
2122 ["--pro"],
2123 EngineType.OSS,
2124 ),
2125 (
2126 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},
2127 [],
2128 EngineType.OSS,
2129 ),
2130 # Type is not specified and default to string, so the default value is
2131 # returned as a string, even if it is a boolean. Also, defaults to the
2132 # flag_value instead of the default value to support legacy behavior.
2133 ({"flag_value": "1", "default": True}, [], "1"),
2134 ({"flag_value": "1", "default": 42}, [], "42"),
2135 ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),
2136 ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),
2137 # See: the result is the same if we force the type to be str.
2138 ({"type": str, "flag_value": 1, "default": True}, [], "1"),
2139 ({"type": str, "flag_value": 1, "default": 42}, [], "42"),
2140 ({"type": str, "flag_value": "1", "default": True}, [], "1"),
2141 ({"type": str, "flag_value": "1", "default": 42}, [], "42"),
2142 (
2143 {"type": str, "flag_value": EngineType.OSS, "default": True},
2144 [],
2145 "EngineType.OSS",
2146 ),
2147 ({"type": str, "flag_value": EngineType.OSS, "default": 42}, [], "42"),
2148 # But having the flag value set to integer is automaticcally recognized by
2149 # Click.
2150 ({"flag_value": 1, "default": True}, [], 1),
2151 ({"flag_value": 1, "default": 42}, [], 42),
2152 ({"type": int, "flag_value": 1, "default": True}, [], 1),
2153 ({"type": int, "flag_value": 1, "default": 42}, [], 42),
2154 ({"type": int, "flag_value": "1", "default": True}, [], 1),
2155 ({"type": int, "flag_value": "1", "default": 42}, [], 42),
2156 ],
2157 )
2158 def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):
2159 """Test how the type and flag_value influence the returned value.
2160
2161 Cover cases reported in:
2162 https://github.com/pallets/click/issues/3024#issuecomment-3146480714
2163 https://github.com/pallets/click/issues/2012#issuecomment-892437060
2164 """
2165
2166 @click.command()
2167 @click.option("--pro", **opt_params)
2168 def scan(pro):
2169 click.echo(repr(pro), nl=False)
2170
2171 result = runner.invoke(scan, args)
2172 if isinstance(expected, re.Pattern):
2173 assert re.match(expected, result.output)
2174 else:
2175 assert result.output == repr(expected)
2176
2177
2178 @pytest.mark.parametrize(
2179 ("opt1_params", "opt2_params", "args", "expected"),
2180 [
2181 # Dual options sharing the same variable name, are not competitive, and the
2182 # flag value is returned as-is. Especially when the type is force to be
2183 # unprocessed.
2184 (
2185 {"flag_value": EngineType.OSS, "type": UNPROCESSED},
2186 {"flag_value": EngineType.PRO, "type": UNPROCESSED},
2187 [],
2188 None,
2189 ),
2190 (
2191 {"flag_value": EngineType.OSS, "type": UNPROCESSED},
2192 {"flag_value": EngineType.PRO, "type": UNPROCESSED},
2193 ["--opt1"],
2194 EngineType.OSS,
2195 ),
2196 (
2197 {"flag_value": EngineType.OSS, "type": UNPROCESSED},
2198 {"flag_value": EngineType.PRO, "type": UNPROCESSED},
2199 ["--opt2"],
2200 EngineType.PRO,
2201 ),
2202 # Check that passing exotic flag values like classes is supported, but are
2203 # rendered to strings when the type is not specified.
2204 # https://github.com/pallets/click/issues/3121
2205 (
2206 {"flag_value": Class1, "default": True},
2207 {"flag_value": Class2},
2208 [],
2209 "<class 'test_options.Class1'>",
2210 ),
2211 (
2212 {"flag_value": Class1, "default": True},
2213 {"flag_value": Class2},
2214 ["--opt1"],
2215 "<class 'test_options.Class1'>",
2216 ),
2217 (
2218 {"flag_value": Class1, "default": True},
2219 {"flag_value": Class2},
2220 ["--opt2"],
2221 "<class 'test_options.Class2'>",
2222 ),
2223 # Even the default is processed as a string.
2224 ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),
2225 ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),
2226 # To get the classes as-is, we need to specify the type as UNPROCESSED.
2227 # https://github.com/pallets/click/issues/3121
2228 (
2229 {"flag_value": Class1, "type": UNPROCESSED, "default": True},
2230 {"flag_value": Class2, "type": UNPROCESSED},
2231 [],
2232 Class1,
2233 ),
2234 (
2235 {"flag_value": Class1, "type": UNPROCESSED, "default": True},
2236 {"flag_value": Class2, "type": UNPROCESSED},
2237 ["--opt1"],
2238 Class1,
2239 ),
2240 (
2241 {"flag_value": Class1, "type": UNPROCESSED, "default": True},
2242 {"flag_value": Class2, "type": UNPROCESSED},
2243 ["--opt2"],
2244 Class2,
2245 ),
2246 # Setting the default to a class, an instance of the class is returned instead
2247 # of the class itself, because the default is allowed to be callable (and
2248 # consummd). And this happens whatever the type is.
2249 (
2250 {"flag_value": Class1, "default": Class1},
2251 {"flag_value": Class2},
2252 [],
2253 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),
2254 ),
2255 (
2256 {"flag_value": Class1, "default": Class2},
2257 {"flag_value": Class2},
2258 [],
2259 re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),
2260 ),
2261 (
2262 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},
2263 {"flag_value": Class2, "type": UNPROCESSED},
2264 [],
2265 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),
2266 ),
2267 (
2268 {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},
2269 {"flag_value": Class2, "type": UNPROCESSED},
2270 [],
2271 re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),
2272 ),
2273 # Having the flag value set to integer is automaticcally recognized by Click.
2274 (
2275 {"flag_value": 1, "default": True},
2276 {"flag_value": "1"},
2277 [],
2278 1,
2279 ),
2280 (
2281 {"flag_value": 1, "type": int, "default": True},
2282 {"flag_value": "1", "type": int},
2283 [],
2284 1,
2285 ),
2286 ],
2287 )
2288 def test_custom_type_flag_value_dual_options(
2289 runner, opt1_params, opt2_params, args, expected
2290 ):
2291 """Test how flag values are processed with dual options competing for the same
2292 variable name.
2293
2294 Reproduce issues reported in:
2295 https://github.com/pallets/click/issues/3024#issuecomment-3146508536
2296 https://github.com/pallets/click/issues/2012#issue-946471049
2297 https://github.com/pallets/click/issues/2012#issuecomment-892437060
2298 """
2299
2300 @click.command()
2301 @click.option("--opt1", "dual_option", **opt1_params)
2302 @click.option("--opt2", "dual_option", **opt2_params)
2303 def cli(dual_option):
2304 click.echo(repr(dual_option), nl=False)
2305
2306 result = runner.invoke(cli, args)
2307 if isinstance(expected, re.Pattern):
2308 assert re.match(expected, result.output)
2309 else:
2310 assert result.output == repr(expected)
2311
2312
2313 @pytest.mark.parametrize(
2314 ("opt_params", "args", "expected"),
2315 [
2316 # Class flag_value with default=True and UNPROCESSED: the class itself is
2317 # returned, NOT an instance. Regression test for
2318 # https://github.com/pallets/click/issues/3121
2319 ({"flag_value": Class1, "type": UNPROCESSED, "default": True}, [], Class1),
2320 (
2321 {"flag_value": Class1, "type": UNPROCESSED, "default": True},
2322 ["--opt"],
2323 Class1,
2324 ),
2325 # Without UNPROCESSED, the class is str()-ified by the default STRING type.
2326 ({"flag_value": Class1, "default": True}, [], "<class 'test_options.Class1'>"),
2327 (
2328 {"flag_value": Class1, "default": True},
2329 ["--opt"],
2330 "<class 'test_options.Class1'>",
2331 ),
2332 # Explicit default=Class1 (not via default=True alignment): callable IS invoked,
2333 # because the user explicitly set a callable as the default.
2334 (
2335 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},
2336 [],
2337 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),
2338 ),
2339 # Explicit default=Class2, different from flag_value=Class1.
2340 (
2341 {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},
2342 [],
2343 re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),
2344 ),
2345 # Non-callable flag_value with default=True: unaffected by the fix.
2346 ({"flag_value": "upper", "default": True}, [], "upper"),
2347 ({"flag_value": "upper", "default": True}, ["--opt"], "upper"),
2348 ],
2349 )
2350 def test_callable_flag_value_not_instantiated(runner, opt_params, args, expected):
2351 """A callable ``flag_value`` like a class, with ``default=True`` should not be
2352 invoked when resolving the default. This is the single-option variant of
2353 the regression reported in https://github.com/pallets/click/issues/3121.
2354 """
2355
2356 @click.command()
2357 @click.option("--opt", "value", **opt_params)
2358 def cli(value):
2359 click.echo(repr(value), nl=False)
2360
2361 result = runner.invoke(cli, args)
2362 assert result.exit_code == 0
2363 if isinstance(expected, re.Pattern):
2364 assert re.match(expected, result.output)
2365 else:
2366 assert result.output == repr(expected)
2367
2368
2369 def test_callable_flag_value_default_map(runner):
2370 """A ``default_map`` entry should override the auto-aligned callable ``flag_value``.
2371
2372 When ``default=True`` and ``flag_value=SomeClass``, the default is aligned to
2373 ``SomeClass``. If ``default_map`` provides a different value (including a
2374 callable), it should take precedence and callables from ``default_map`` should
2375 still be invoked.
2376 """
2377
2378 @click.command()
2379 @click.option("--opt", "value", flag_value=Class1, type=UNPROCESSED, default=True)
2380 def cli(value):
2381 click.echo(repr(value), nl=False)
2382
2383 # Static value in default_map overrides the flag_value default.
2384 result = runner.invoke(cli, [], default_map={"value": "from-map"})
2385 assert result.output == repr("from-map")
2386
2387 # Callable in default_map is still invoked (not suppressed by the fix).
2388 result = runner.invoke(cli, [], default_map={"value": lambda: "lazy-map"})
2389 assert result.output == repr("lazy-map")
2390
2391 # CLI arg still wins over everything.
2392 result = runner.invoke(cli, ["--opt"])
2393 assert result.output == repr(Class1)
2394
2395
2396 def test_callable_flag_value_show_default(runner):
2397 """Help text with ``show_default=True`` should display the class name, not
2398 instantiate it.
2399 """
2400
2401 @click.command()
2402 @click.option(
2403 "--opt",
2404 "value",
2405 flag_value=Class1,
2406 type=UNPROCESSED,
2407 default=True,
2408 show_default=True,
2409 )
2410 def cli(value):
2411 pass
2412
2413 result = runner.invoke(cli, ["--help"])
2414 assert result.exit_code == 0
2415 assert "Class1" in result.output
2416 assert "object at 0x" not in result.output
2417
2418
2419 @pytest.mark.parametrize(
2420 ("opt_params", "expected_default_attr", "expected_get_default"),
2421 [
2422 # default=True with callable flag_value: the attribute stays True
2423 # (not eagerly aligned), but get_default() resolves to the flag_value.
2424 (
2425 {"flag_value": Class1, "type": UNPROCESSED, "default": True},
2426 True,
2427 Class1,
2428 ),
2429 # default=True with non-callable flag_value: same lazy resolution.
2430 (
2431 {"flag_value": "upper", "default": True},
2432 True,
2433 "upper",
2434 ),
2435 # Explicit default (not True): attribute and get_default() agree.
2436 (
2437 {"flag_value": Class1, "type": UNPROCESSED, "default": "custom"},
2438 "custom",
2439 "custom",
2440 ),
2441 # No default: attribute and get_default() are both UNSET.
2442 (
2443 {"flag_value": Class1, "type": UNPROCESSED},
2444 UNSET,
2445 UNSET,
2446 ),
2447 ],
2448 )
2449 def test_callable_flag_value_get_default_override(
2450 runner, opt_params, expected_default_attr, expected_get_default
2451 ):
2452 """The ``default=True`` to ``flag_value`` alignment is resolved lazily in
2453 ``get_default()`` rather than eagerly in ``__init__``. This means
2454 ``option.default`` stays as ``True`` while ``get_default()`` returns the
2455 ``flag_value``.
2456
2457 A user subclass that reads ``self.default`` directly (bypassing
2458 ``get_default()``) will see ``True`` instead of the ``flag_value``.
2459 """
2460
2461 @click.command()
2462 @click.option("--opt", "value", **opt_params)
2463 def cli(value):
2464 pass
2465
2466 opt = cli.params[0]
2467
2468 # The raw attribute reflects what the user wrote.
2469 assert opt.default is expected_default_attr
2470
2471 # get_default() resolves the alignment lazily.
2472 ctx = click.Context(cli)
2473 assert opt.get_default(ctx, call=True) is expected_get_default
2474
2475
2476 def test_custom_type_frozenset_flag_value(runner):
2477 """Check that frozenset is correctly handled as a type, a flag value and a default.
2478
2479 Reproduces https://github.com/pallets/click/issues/2610
2480 """
2481
2482 @click.command()
2483 @click.option(
2484 "--without-scm-ignore-files",
2485 "scm_ignore_files",
2486 is_flag=True,
2487 type=frozenset,
2488 flag_value=frozenset(),
2489 default=frozenset(["git"]),
2490 )
2491 def rcli(scm_ignore_files):
2492 click.echo(repr(scm_ignore_files), nl=False)
2493
2494 result = runner.invoke(rcli)
2495 assert result.stdout == "frozenset({'git'})"
2496 assert result.exit_code == 0
2497
2498 result = runner.invoke(rcli, ["--without-scm-ignore-files"])
2499 assert result.stdout == "frozenset()"
2500 assert result.exit_code == 0
2501
2502
2503 @pytest.mark.parametrize(
2504 ("default", "args", "expected"),
2505 [
2506 # default=None: 3-state pattern (e.g. Flask --reload/--no-reload).
2507 # https://github.com/pallets/click/issues/3024
2508 (None, [], None),
2509 (None, ["--flag"], True),
2510 (None, ["--no-flag"], False),
2511 # default=True: literal value, not substituted with flag_value.
2512 # https://github.com/pallets/click/issues/3111
2513 (True, [], True),
2514 (True, ["--flag"], True),
2515 (True, ["--no-flag"], False),
2516 ],
2517 )
2518 def test_bool_flag_pair_default(runner, default, args, expected):
2519 """Boolean flag pairs pass ``default`` through literally.
2520
2521 Ensures ``default=True`` is not replaced by ``flag_value`` for boolean
2522 flags, and that ``default=None`` enables 3-state logic.
2523 """
2524
2525 @click.command()
2526 @click.option("--flag/--no-flag", default=default)
2527 def cli(flag):
2528 click.echo(repr(flag), nl=False)
2529
2530 result = runner.invoke(cli, args)
2531 assert result.exit_code == 0
2532 assert result.output == repr(expected)
2533
2534
2535 @pytest.mark.parametrize(
2536 ("flag_type", "args", "expect_output"),
2537 [
2538 (str, [], "Default\n"),
2539 (str, ["--theflag"], "FlagValue\n"),
2540 (str, ["--theflag", "value"], "value\n"),
2541 (int, [], "0\n"),
2542 (int, ["--theflag"], "1\n"),
2543 (int, ["--theflag", "2"], "2\n"),
2544 ],
2545 )
2546 def test_flag_value_on_option_with_zero_or_one_args(flag_type, args, expect_output):
2547 """An option with flag_value and is_flag=False can be
2548 omitted or used with 0 or 1 args.
2549
2550 Regression test for https://github.com/pallets/click/issues/3084
2551 """
2552 if flag_type is str:
2553 flagopt = click.option(
2554 "--theflag",
2555 type=str,
2556 is_flag=False,
2557 flag_value="FlagValue",
2558 default="Default",
2559 )
2560 elif flag_type is int:
2561 flagopt = click.option(
2562 "--theflag", type=int, is_flag=False, flag_value=1, default=0
2563 )
2564 else:
2565 raise NotImplementedError(flag_type)
2566
2567 @click.command()
2568 @flagopt
2569 def cmd(theflag):
2570 click.echo(theflag)
2571
2572 runner = CliRunner()
2573 result = runner.invoke(cmd, args)
2574 assert result.exit_code == 0
2575 assert result.output == expect_output