Skip to content
Myr

Merge branch 'main' into stable

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parents 23780fa, 9c632c0 · Browse files · 15 files+2083 added−499 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+2083 added−499 removed

  • tests:+1620 added−280 removed
  • other:+463 added−219 removed

15 files+2083 added−499 removed

modified:docs/options.md+25 added-4 removed
312 unmodified lines
313```314315## Flag Value316317To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To set a default flag, set `default=True`. Setting flag values can be used to create patterns like this:317To have an flag pass a value to the underlying function set `flag_value`. This automatically sets `is_flag=True`. To mark the flag as default, set `default=True`. Setting flag values can be used to create patterns like this:318319```{eval-rst}320.. click:example::321
12 unmodified lines
334 invoke(info, args=['--lower'])335 invoke(info)336```337338````{note}339The `default` value is given to the underlying function as-is. So if you set `default=None`, the value passed to the function is the `None` Python value. Same for any other type.340341But there is a special case for flags. If a flag has a `flag_value`, then setting `default=True` is interpreted as *the flag should be activated by default*. So instead of the underlying function receiving the `True` Python value, it will receive the `flag_value`.342343Which means, in example above, this option:344345```python346@click.option('--upper', 'transformation', flag_value='upper', default=True)347```348349is equivalent to:350351```python352@click.option('--upper', 'transformation', flag_value='upper', default='upper')353```354355Because the two are equivalent, it is recommended to always use the second form, and set `default` to the actual value you want to pass. And not use the special `True` case. This makes the code more explicit and predictable.356````357358## Values from Environment Variables359360To pass in a value in from a specific environment variable use `envvar`.361
43 unmodified lines
405 - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag406 - If the flag option has a `flag_value` argument, passing that value in the environment variable will activate the flag, in addition to all the cases described above407 - Any other value is interpreted as deactivating the flag408389.. caution::390 For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.409```{caution}410For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.411392 So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.412So an option defined as `--flag\--no-flag`, with a `envvar="FLAG"` parameter, there is no magical `NO_FLAG=<anything>` variable that is recognized. Only the `FLAG=<anything>` environment variable is recognized.413```414415Once the status of the flag has been determine to be activated or not, the `flag_value` is used as the value of the flag if it is activated. If the flag is not activated, the value of the flag is set to `None` by default.416417## Multiple Options from Environment Values
80 unmodified lines
added:src/click/_utils.py+36 added
1from __future__ import annotations23import enum4import typing as t567class Sentinel(enum.Enum):8 """Enum used to define sentinel values.910 .. seealso::1112 `PEP 661 - Sentinel Values <https://peps.python.org/pep-0661/>`_.13 """1415 UNSET = object()16 FLAG_NEEDS_VALUE = object()1718 def __repr__(self) -> str:19 return f"{self.__class__.__name__}.{self.name}"202122UNSET = Sentinel.UNSET23"""Sentinel used to indicate that a value is not set."""2425FLAG_NEEDS_VALUE = Sentinel.FLAG_NEEDS_VALUE26"""Sentinel used to indicate an option was passed as a flag without a27value but is not a flag option.2829``Option.consume_value`` uses this to prompt or use the ``flag_value``.30"""3132T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]33"""Type hint for the :data:`UNSET` sentinel value."""3435T_FLAG_NEEDS_VALUE = t.Literal[FLAG_NEEDS_VALUE] # type: ignore[valid-type]36"""Type hint for the :data:`FLAG_NEEDS_VALUE` sentinel value."""
modified:src/click/core.py+343 added-174 removed
17 unmodified lines
18from itertools import repeat19from types import TracebackType2021from . import types22from ._utils import FLAG_NEEDS_VALUE23from ._utils import UNSET24from .exceptions import Abort25from .exceptions import BadParameter26from .exceptions import ClickException27from .exceptions import Exit
3 unmodified lines
31from .formatting import HelpFormatter32from .formatting import join_options33from .globals import pop_context34from .globals import push_context33from .parser import _flag_needs_value35from .parser import _OptionParser36from .parser import _split_opt37from .termui import confirm38from .termui import prompt
443 unmodified lines
482 self,483 exc_type: type[BaseException] | None,484 exc_value: BaseException | None,485 tb: TracebackType | None,485 ) -> None:486 ) -> bool | None:487 self._depth -= 1488 exit_result: bool | None = None489 if self._depth == 0:488 self.close()490 exit_result = self._close_with_exception_info(exc_type, exc_value, tb)491 pop_context()492493 return exit_result494495 @contextmanager496 def scope(self, cleanup: bool = True) -> cabc.Iterator[Context]:497 """This helper method can be used with the context object to promote498 it to the current thread local (see :func:`get_current_context`).
118 unmodified lines
617 """Invoke all close callbacks registered with618 :meth:`call_on_close`, and exit all context managers entered619 with :meth:`with_resource`.620 """617 self._exit_stack.close()621 self._close_with_exception_info(None, None, None)622623 def _close_with_exception_info(624 self,625 exc_type: type[BaseException] | None,626 exc_value: BaseException | None,627 tb: TracebackType | None,628 ) -> bool | None:629 """Unwind the exit stack by calling its :meth:`__exit__` providing the exception630 information to allow for exception handling by the various resources registered631 using :meth;`with_resource`632633 :return: Whatever ``exit_stack.__exit__()`` returns.634 """635 exit_result = self._exit_stack.__exit__(exc_type, exc_value, tb)636 # In case the context is reused, create a new exit stack.637 self._exit_stack = ExitStack()638639 return exit_result640641 @property642 def command_path(self) -> str:643 """The computed command path. This is used for the ``usage``644 information on the help page. It's automatically created by
60 unmodified lines
705 .. versionchanged:: 8.0706 Added the ``call`` parameter.707 """708 if self.default_map is not None:689 value = self.default_map.get(name)709 value = self.default_map.get(name, UNSET)710711 if call and callable(value):712 return value()713714 return value715696 return None716 return UNSET717718 def fail(self, message: str) -> t.NoReturn:719 """Aborts the execution of the program with a specific error720 message.
492 unmodified lines
1213 parser = self.make_parser(ctx)1214 opts, args, param_order = parser.parse_args(args=args)12151216 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1197 value, args = param.handle_parse_result(ctx, opts, args)1217 _, args = param.handle_parse_result(ctx, opts, args)12181219 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1220 ctx.fail(1221 ngettext(
812 unmodified lines
2034 otherwise it's skipped.2035 :param is_eager: eager values are processed before non eager ones. This2036 should not be set for arguments or it will inverse the2037 order of processing.2018 :param envvar: a string or list of strings that are environment variables2019 that should be checked.2038 :param envvar: environment variable(s) that are used to provide a default value for2039 this parameter. This can be a string or a sequence of strings. If a sequence is2040 given, only the first non-empty environment variable is used for the parameter.2041 :param shell_complete: A function that returns custom shell2042 completions. Used instead of the param's type completion if2043 given. Takes ``ctx, param, incomplete`` and must return a list2044 of :class:`~click.shell_completion.CompletionItem` or a list of
53 unmodified lines
2098 self,2099 param_decls: cabc.Sequence[str] | None = None,2100 type: types.ParamType | t.Any | None = None,2101 required: bool = False,2102 # XXX The default historically embed two concepts:2103 # - the declaration of a Parameter object carrying the default (handy to2104 # arbitrage the default value of coupled Parameters sharing the same2105 # self.name, like flag options),2106 # - and the actual value of the default.2107 # It is confusing and is the source of many issues discussed in:2108 # https://github.com/pallets/click/pull/30302109 # In the future, we might think of splitting it in two, not unlike2110 # Option.is_flag and Option.flag_value: we could have something like2111 # Parameter.is_default and Parameter.default_value.2081 default: t.Any | t.Callable[[], t.Any] | None = None,2112 default: t.Any | t.Callable[[], t.Any] | None = UNSET,2113 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,2114 nargs: int | None = None,2115 multiple: bool = False,2116 metavar: str | None = None,
40 unmodified lines
2157 f"'nargs' must be {self.type.arity} (or None) for"2158 f" type {self.type!r}, but it was {nargs}."2159 )21602130 # Skip no default or callable default.2131 check_default = default if not callable(default) else None21322133 if check_default is not None:2134 if multiple:2135 try:2136 # Only check the first value against nargs.2137 check_default = next(_check_iter(check_default), None)2138 except TypeError:2139 raise ValueError(2140 "'default' must be a list when 'multiple' is true."2141 ) from None21422143 # Can be None for multiple with empty default.2144 if nargs != 1 and check_default is not None:2145 try:2146 _check_iter(check_default)2147 except TypeError:2148 if multiple:2149 message = (2150 "'default' must be a list of lists when 'multiple' is"2151 " true and 'nargs' != 1."2152 )2153 else:2154 message = "'default' must be a list when 'nargs' != 1."21552156 raise ValueError(message) from None21572158 if nargs > 1 and len(check_default) != nargs:2159 subject = "item length" if multiple else "length"2160 raise ValueError(2161 f"'default' {subject} must match nargs={nargs}."2162 )21632161 if required and deprecated:2162 raise ValueError(2163 f"The {self.param_type_name} '{self.human_readable_name}' "2164 "is deprecated and still required. A deprecated "
6 unmodified lines
21712172 Use :meth:`click.Context.to_info_dict` to traverse the entire2173 CLI structure.21742175 .. versionchanged:: 8.3.02176 Returns ``None`` for the :attr:`default` if it was not set.21772178 .. versionadded:: 8.02179 """2180 return {2181 "name": self.name,
3 unmodified lines
2185 "type": self.type.to_info_dict(),2186 "required": self.required,2187 "nargs": self.nargs,2188 "multiple": self.multiple,2189 "default": self.default,2189 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2190 # make it an implementation detail. And because ``to_info_dict`` has been2191 # designed for documentation purposes, we return ``None`` instead.2192 "default": self.default if self.default is not UNSET else None,2193 "envvar": self.envvar,2194 }21952196 def __repr__(self) -> str:
59 unmodified lines
2256 Added the ``call`` parameter.2257 """2258 value = ctx.lookup_default(self.name, call=False) # type: ignore22592257 if value is None:2260 if value is UNSET:2261 value = self.default22622263 if call and callable(value):2264 value = value()
5 unmodified lines
22702271 def consume_value(2272 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2273 ) -> tuple[t.Any, ParameterSource]:2271 value = opts.get(self.name) # type: ignore2272 source = ParameterSource.COMMANDLINE2274 """Returns the parameter value produced by the parser.22752274 if value is None:2275 value = self.value_from_envvar(ctx)2276 source = ParameterSource.ENVIRONMENT2276 If the parser did not produce a value from user input, the value is either2277 sourced from the environment variable, the default map, or the parameter's2278 default value. In that order of precedence.22792278 if value is None:2279 value = ctx.lookup_default(self.name) # type: ignore2280 source = ParameterSource.DEFAULT_MAP2280 If no value is found, an internal sentinel value is returned.22812282 if value is None:2283 value = self.get_default(ctx)2284 source = ParameterSource.DEFAULT2282 :meta private:2283 """2284 # Collect from the parse the value passed by the user to the CLI.2285 value = opts.get(self.name, UNSET) # type: ignore2286 # If the value is set, it means it was sourced from the command line by the2287 # parser, otherwise it left unset by default.2288 source = (2289 ParameterSource.COMMANDLINE2290 if value is not UNSET2291 else ParameterSource.DEFAULT2292 )22932294 if value is UNSET:2295 envvar_value = self.value_from_envvar(ctx)2296 if envvar_value is not None:2297 value = envvar_value2298 source = ParameterSource.ENVIRONMENT22992300 if value is UNSET:2301 default_map_value = ctx.lookup_default(self.name) # type: ignore2302 if default_map_value is not UNSET:2303 value = default_map_value2304 source = ParameterSource.DEFAULT_MAP23052306 if value is UNSET:2307 default_value = self.get_default(ctx)2308 if default_value is not UNSET:2309 value = default_value2310 source = ParameterSource.DEFAULT23112312 return value, source23132314 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2289 """Convert and validate a value against the option's2315 """Convert and validate a value against the parameter's2316 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2317 """2292 if value is None:2293 return () if self.multiple or self.nargs == -1 else None2318 if value in (None, UNSET):2319 if self.multiple or self.nargs == -1:2320 return ()2321 else:2322 return value23232324 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2325 try:2326 return _check_iter(value)
4 unmodified lines
2331 raise BadParameter(2332 _("Value must be an iterable."), ctx=ctx, param=self2333 ) from None23342335 # Define the conversion function based on nargs and type.23362337 if self.nargs == 1 or self.type.is_composite:23382339 def convert(value: t.Any) -> t.Any:2340 return self.type(value, param=self, ctx=ctx)
26 unmodified lines
23672368 return convert(value)23692370 def value_is_missing(self, value: t.Any) -> bool:2371 """A value is considered missing if:23722373 - it is :attr:`UNSET`,2374 - or if it is an empty sequence while the parameter is suppose to have2375 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is2376 set).23772378 :meta private:2379 """2340 if value is None:2380 if value is UNSET:2381 return True23822383 if (self.nargs != 1 or self.multiple) and value == ():2384 return True23852386 return False23872388 def process_value(self, ctx: Context, value: t.Any) -> t.Any:2389 """Process the value of this parameter:23902391 1. Type cast the value using :meth:`type_cast_value`.2392 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise2393 :exc:`MissingParameter` if it is required.2394 3. If a :attr:`callback` is set, call it to have the value replaced by the2395 result of the callback. If the value was not set, the callback receive2396 ``None``. This keep the legacy behavior as it was before the introduction of2397 the :attr:`UNSET` sentinel.23982399 :meta private:2400 """2401 value = self.type_cast_value(ctx, value)24022403 if self.required and self.value_is_missing(value):2404 raise MissingParameter(ctx=ctx, param=self)24052406 if self.callback is not None:2407 # Legacy case: UNSET is not exposed directly to the callback, but converted2408 # to None.2409 if value is UNSET:2410 value = None2411 value = self.callback(ctx, self, value)24122413 return value24142415 def resolve_envvar_value(self, ctx: Context) -> str | None:2360 if self.envvar is None:2416 """Returns the value found in the environment variable(s) attached to this2417 parameter.24182419 Environment variables values are `always returned as strings2420 <https://docs.python.org/3/library/os.html#os.environ>`_.24212422 This method returns ``None`` if:24232424 - the :attr:`envvar` property is not set on the :class:`Parameter`,2425 - the environment variable is not found in the environment,2426 - the variable is found in the environment but its value is empty (i.e. the2427 environment variable is present but has an empty string).24282429 If :attr:`envvar` is setup with multiple environment variables,2430 then only the first non-empty value is returned.24312432 .. caution::24332434 The raw value extracted from the environment is not normalized and is2435 returned as-is. Any normalization or reconciliation is performed later by2436 the :class:`Parameter`'s :attr:`type`.24372438 :meta private:2439 """2440 if not self.envvar:2441 return None24422443 if isinstance(self.envvar, str):2444 rv = os.environ.get(self.envvar)
3 unmodified lines
2448 else:2449 for envvar in self.envvar:2450 rv = os.environ.get(envvar)24512452 # Return the first non-empty value of the list of environment variables.2453 if rv:2454 return rv2455 # Else, absence of value is interpreted as an environment variable that2456 # is not set, so proceed to the next one.24572458 return None24592377 def value_from_envvar(self, ctx: Context) -> t.Any | None:2378 rv: t.Any | None = self.resolve_envvar_value(ctx)2460 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:2461 """Process the raw environment variable string for this parameter.24622463 Returns the string as-is or splits it into a sequence of strings if the2464 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set2465 to a value other than ``1``).24662467 :meta private:2468 """2469 rv = self.resolve_envvar_value(ctx)24702471 if rv is not None and self.nargs != 1:2381 rv = self.type.split_envvar_value(rv)2472 return self.type.split_envvar_value(rv)24732474 return rv24752476 def handle_parse_result(2477 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]2478 ) -> tuple[t.Any, list[str]]:2479 """Process the value produced by the parser from user input.24802481 Always process the value through the Parameter's :attr:`type`, wherever it2482 comes from.24832484 If the parameter is deprecated, this method warn the user about it. But only if2485 the value has been explicitly set by the user (and as such, is not coming from2486 a default).24872488 :meta private:2489 """2490 with augment_usage_errors(ctx, param=self):2491 value, source = self.consume_value(ctx, opts)24922493 ctx.set_parameter_source(self.name, source) # type: ignore24942495 # Display a deprecation warning if necessary.2496 if (2497 self.deprecated2393 and value is not None2394 and source2395 not in (2396 ParameterSource.DEFAULT,2397 ParameterSource.DEFAULT_MAP,2398 )2498 and value is not UNSET2499 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)2500 ):2501 extra_message = (2502 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2503 )
6 unmodified lines
2510 extra_message=extra_message,2511 )2512 echo(style(message, fg="red"), err=True)25132413 ctx.set_parameter_source(self.name, source) # type: ignore24142514 # Process the value through the parameter's type.2515 try:2516 value = self.process_value(ctx, value)2517 except Exception:2518 if not ctx.resilient_parsing:2519 raise2520 # In resilient parsing mode, we do not want to fail the command if the2521 # value is incompatible with the parameter type, so we reset the value2522 # to UNSET, which will be interpreted as a missing value.2523 value = UNSET25242421 value = None2525 # Add parameter's value to the context.2526 if (2527 self.expose_value2528 # We skip adding the value if it was previously set by another parameter2529 # targeting the same variable name. This prevents parameters competing for2530 # the same name to override each other.2531 and self.name not in ctx.params2532 ):2533 # Click is logically enforcing that the name is None if the parameter is2534 # not to be exposed. We still assert it here to please the type checker.2535 assert self.name is not None, (2536 f"{self!r} parameter's name should not be None when exposing value."2537 )2538 # Normalize UNSET values to None, as we're about to pass them to the2539 # command function and move them to the pure-Python realm of user-written2540 # code.2541 ctx.params[self.name] = value if value is not UNSET else None25422423 if self.expose_value:2424 ctx.params[self.name] = value # type: ignore24252543 return value, args25442545 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2546 pass
108 unmodified lines
2655 confirmation_prompt: bool | str = False,2656 prompt_required: bool = True,2657 hide_input: bool = False,2658 is_flag: bool | None = None,2542 flag_value: t.Any | None = None,2659 flag_value: t.Any = UNSET,2660 multiple: bool = False,2661 count: bool = False,2662 allow_from_autoenv: bool = True,2663 type: types.ParamType | t.Any | None = None,
34 unmodified lines
2698 self.prompt_required = prompt_required2699 self.hide_input = hide_input2700 self.hidden = hidden27012585 # If prompt is enabled but not required, then the option can be2586 # used as a flag to indicate using prompt or flag_value.2702 # The _flag_needs_value property tells the parser that this option is a flag2703 # that cannot be used standalone and needs a value. With this information, the2704 # parser can determine whether to consider the next user-provided argument in2705 # the CLI as a value for this flag or as a new option.2706 # If prompt is enabled but not required, then it opens the possibility for the2707 # option to gets its value from the user.2708 self._flag_needs_value = self.prompt is not None and not self.prompt_required27092710 # Auto-detect if this is a flag or not.2711 if is_flag is None:2712 # Implicitly a flag because flag_value was set.2591 if flag_value is not None:2713 if flag_value is not UNSET:2714 is_flag = True2715 # Not a flag, but when used as a flag it shows a prompt.2716 elif self._flag_needs_value:2717 is_flag = False2596 # Implicitly a flag because flag options were given.2718 # Implicitly a flag because secondary options names were given.2719 elif self.secondary_opts:2720 is_flag = True2721 # The option is explicitly not a flag. But we do not know yet if it needs a2722 # value or not. So we look at the default value to determine it.2723 elif is_flag is False and not self._flag_needs_value:2600 # Not a flag, and prompt is not enabled, can be used as a2601 # flag if flag_value is set.2602 self._flag_needs_value = flag_value is not None2724 self._flag_needs_value = self.default is UNSET27252604 self.default: t.Any | t.Callable[[], t.Any]26052726 if is_flag:2727 # Set missing default for flags if not explicitly required or prompted.2608 if self.default is None and not self.required and not self.prompt:2728 if self.default is UNSET and not self.required and not self.prompt:2729 if multiple:2730 self.default = ()27312732 # Auto-detect the type of the flag based on the flag_value.2733 if type is None:2734 # A flag without a flag_value is a boolean flag.2735 if flag_value is UNSET:2736 self.type = types.BoolParamType()2737 # If the flag value is a boolean, use BoolParamType.2738 elif isinstance(flag_value, bool):2739 self.type = types.BoolParamType()2740 # Otherwise, guess the type from the flag value.2741 else:2612 self.default = False2742 self.type = types.convert_type(None, flag_value)27432614 if flag_value is None:2615 # A boolean flag presence in the command line is enough to set2616 # the value: to the default if it is not blank, or to True2617 # otherwise.2618 flag_value = self.default if self.default else True26192620 self.type: types.ParamType2621 if is_flag and type is None:2622 # Re-guess the type from the flag value instead of the2623 # default.2624 self.type = types.convert_type(None, flag_value)26252744 self.is_flag: bool = bool(is_flag)2745 self.is_bool_flag: bool = bool(2746 is_flag and isinstance(self.type, types.BoolParamType)2747 )2748 self.flag_value: t.Any = flag_value27492750 # Set boolean flag default to False if unset and not required.2751 if self.is_bool_flag:2752 if self.default is UNSET and not self.required:2753 self.default = False27542755 # Support the special case of aligning the default value with the flag_value2756 # for flags whose default is explicitly set to True. Note that as long as we2757 # have this condition, there is no way a flag can have a default set to True,2758 # and a flag_value set to something else. Refs:2759 # https://github.com/pallets/click/issues/3024#issuecomment-31461994612760 # https://github.com/pallets/click/pull/3030/commits/06847da2761 if self.default is True and self.flag_value is not UNSET:2762 self.default = self.flag_value27632764 # Set the default flag_value if it is not set.2765 if self.flag_value is UNSET:2766 if self.is_flag:2767 self.flag_value = True2768 else:2769 self.flag_value = None27702632 # Counting2771 # Counting.2772 self.count = count2773 if count:2774 if type is None:2775 self.type = types.IntRange(min=0)2637 if self.default is None:2776 if self.default is UNSET:2777 self.default = 027782779 self.allow_from_autoenv = allow_from_autoenv2780 self.help = help
7 unmodified lines
27882789 if self.nargs == -1:2790 raise TypeError("nargs=-1 is not supported for options.")27912653 if self.prompt and self.is_flag and not self.is_bool_flag:2654 raise TypeError("'prompt' is not valid for non-boolean flag.")26552792 if not self.is_bool_flag and self.secondary_opts:2793 raise TypeError("Secondary flag is not valid for non-boolean flag.")27942795 if self.is_bool_flag and self.hide_input and self.prompt is not None:
8 unmodified lines
2804 if self.is_flag:2805 raise TypeError("'count' is not valid with 'is_flag'.")28062807 def to_info_dict(self) -> dict[str, t.Any]:2808 """2809 .. versionchanged:: 8.3.02810 Returns ``None`` for the :attr:`flag_value` if it was not set.2811 """2812 info_dict = super().to_info_dict()2813 info_dict.update(2814 help=self.help,2815 prompt=self.prompt,2816 is_flag=self.is_flag,2677 flag_value=self.flag_value,2817 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2818 # make it an implementation detail. And because ``to_info_dict`` has been2819 # designed for documentation purposes, we return ``None`` instead.2820 flag_value=self.flag_value if self.flag_value is not UNSET else None,2821 count=self.count,2822 hidden=self.hidden,2823 )2824 return info_dict
184 unmodified lines
3009 show_default = self.show_default3010 elif ctx.show_default is not None:3011 show_default = ctx.show_default30122870 if show_default_is_str or (show_default and (default_value is not None)):3013 if show_default_is_str or (3014 show_default and (default_value not in (None, UNSET))3015 ):3016 if show_default_is_str:3017 default_string = f"({self.show_default})"3018 elif isinstance(default_value, (list, tuple)):3019 default_string = ", ".join(str(d) for d in default_value)
31 unmodified lines
3051 extra["required"] = "required"30523053 return extra30542910 @t.overload2911 def get_default(2912 self, ctx: Context, call: t.Literal[True] = True2913 ) -> t.Any | None: ...29142915 @t.overload2916 def get_default(2917 self, ctx: Context, call: bool = ...2918 ) -> t.Any | t.Callable[[], t.Any] | None: ...29192920 def get_default(2921 self, ctx: Context, call: bool = True2922 ) -> t.Any | t.Callable[[], t.Any] | None:2923 # If we're a non boolean flag our default is more complex because2924 # we need to look at all flags in the same group to figure out2925 # if we're the default one in which case we return the flag2926 # value as default.2927 if self.is_flag and not self.is_bool_flag:2928 for param in ctx.command.params:2929 if param.name == self.name and param.default is not None:2930 return t.cast(Option, param).default29312932 return None29332934 return super().get_default(ctx, call=call)29353055 def prompt_for_value(self, ctx: Context) -> t.Any:3056 """This is an alternative flow that can be activated in the full3057 value processing if a value does not exist. It will prompt the3058 user until a valid value exists and then returns the processed3059 value as result.3060 """3061 assert self.prompt is not None30622944 # Calculate the default before prompting anything to be stable.3063 # Calculate the default before prompting anything to lock in the value before3064 # attempting any user interaction.3065 default = self.get_default(ctx)30662947 # If this is a prompt for a flag we need to handle this2948 # differently.3067 # A boolean flag can use a simplified [y/n] confirmation prompt.3068 if self.is_bool_flag:3069 # If we have no boolean default, we force the user to explicitly provide3070 # one.3071 if default in (UNSET, None):3072 default = None3073 # Nothing prevent you to declare an option that is simultaneously:3074 # 1) auto-detected as a boolean flag,3075 # 2) allowed to prompt, and3076 # 3) still declare a non-boolean default.3077 # This forced casting into a boolean is necessary to align any non-boolean3078 # default to the prompt, which is going to be a [y/n]-style confirmation3079 # because the option is still a boolean flag. That way, instead of [y/n],3080 # we get [Y/n] or [y/N] depending on the truthy value of the default.3081 # Refs: https://github.com/pallets/click/pull/3030#discussion_r22891802493082 else:3083 default = bool(default)3084 return confirm(self.prompt, default)30853086 # If show_default is set to True/False, provide this to `prompt` as well. For3087 # non-bool values of `show_default`, we use `prompt`'s default behavior
2 unmodified lines
3090 prompt_kwargs["show_default"] = self.show_default30913092 return prompt(3093 self.prompt,2960 default=default,3094 # Use ``None`` to inform the prompt() function to reiterate until a valid3095 # value is provided by the user if we have no default.3096 default=None if default is UNSET else default,3097 type=self.type,3098 hide_input=self.hide_input,3099 show_choices=self.show_choices,3100 confirmation_prompt=self.confirmation_prompt,
1 unmodified line
3102 **prompt_kwargs,3103 )31043105 def resolve_envvar_value(self, ctx: Context) -> str | None:2970 """Find which environment variable to read for this option and return2971 its value.3106 """:class:`Option` resolves its environment variable the same way as3107 :func:`Parameter.resolve_envvar_value`, but it also supports3108 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from3109 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`3110 to build dynamiccaly the environment variable name using the3111 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.31122973 Returns the value of the environment variable if it exists, or ``None``2974 if it does not.29752976 .. caution::29772978 The raw value extracted from the environment is not normalized and2979 is returned as-is. Any normalization or reconciation with the2980 option's type should happen later.3113 :meta private:3114 """3115 rv = super().resolve_envvar_value(ctx)31163117 if rv is not None:
11 unmodified lines
3129 return rv31303131 return None31323000 def value_from_envvar(self, ctx: Context) -> t.Any | None:3001 """Normalize the value from the environment variable, if it exists."""3002 rv: str | None = self.resolve_envvar_value(ctx)3133 def value_from_envvar(self, ctx: Context) -> t.Any:3134 """For :class:`Option`, this method processes the raw environment variable3135 string the same way as :func:`Parameter.value_from_envvar` does.31363137 But in the case of non-boolean flags, the value is analyzed to determine if the3138 flag is activated or not, and returns a boolean of its activation, or the3139 :attr:`flag_value` if the latter is set.31403141 This method also takes care of repeated options (i.e. options with3142 :attr:`multiple` set to ``True``).31433144 :meta private:3145 """3146 rv = self.resolve_envvar_value(ctx)31473148 # Absent environment variable or an empty string is interpreted as unset.3149 if rv is None:3150 return None31513152 # Non-boolean flags are more liberal in what they accept. But a flag being a3008 # flag, its envvar value still needs to analyzed to determine if the flag is3153 # flag, its envvar value still needs to be analyzed to determine if the flag is3154 # activated or not.3155 if self.is_flag and not self.is_bool_flag:3156 # If the flag_value is set and match the envvar value, return it3157 # directly.3013 if self.flag_value is not None and rv == self.flag_value:3158 if self.flag_value is not UNSET and rv == self.flag_value:3159 return self.flag_value3160 # Analyze the envvar value as a boolean to know if the flag is3161 # activated or not.3162 return types.BoolParamType.str_to_bool(rv)
11 unmodified lines
31743175 def consume_value(3176 self, ctx: Context, opts: cabc.Mapping[str, Parameter]3177 ) -> tuple[t.Any, ParameterSource]:3178 """For :class:`Option`, the value can be collected from an interactive prompt3179 if the option is a flag that needs a value (and the :attr:`prompt` property is3180 set).31813182 Additionally, this method handles flag option that are activated without a3183 value, in which case the :attr:`flag_value` is returned.31843185 :meta private:3186 """3187 value, source = super().consume_value(ctx, opts)31883035 # The parser will emit a sentinel value if the option can be3036 # given as a flag without a value. This is different from None3037 # to distinguish from the flag not being given at all.3038 if value is _flag_needs_value:3189 # The parser will emit a sentinel value if the option is allowed to as a flag3190 # without a value.3191 if value is FLAG_NEEDS_VALUE:3192 # If the option allows for a prompt, we start an interaction with the user.3193 if self.prompt is not None and not ctx.resilient_parsing:3194 value = self.prompt_for_value(ctx)3195 source = ParameterSource.PROMPT3196 # Else the flag takes its flag_value as value.3197 else:3198 value = self.flag_value3199 source = ParameterSource.COMMANDLINE32003046 # A flag which is activated and has a flag_value set, should returns3047 # the latter, unless the value comes from the explicitly sets default.3201 # A flag which is activated always returns the flag value, unless the value3202 # comes from the explicitly sets default.3203 elif (3204 self.is_flag3205 and value is True3206 and not self.is_bool_flag3052 and self.flag_value is not None3053 and source is not ParameterSource.DEFAULT3207 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3208 ):3209 value = self.flag_value32103211 # Re-interpret a multiple option which has been sent as-is by the parser.3212 # Here we replace each occurrence of value-less flags (marked by the3213 # FLAG_NEEDS_VALUE sentinel) with the flag_value.3214 elif (3215 self.multiple3059 and value is not None3060 and any(v is _flag_needs_value for v in value)3216 and value is not UNSET3217 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3218 and any(v is FLAG_NEEDS_VALUE for v in value)3219 ):3062 value = [self.flag_value if v is _flag_needs_value else v for v in value]3220 value = [self.flag_value if v is FLAG_NEEDS_VALUE else v for v in value]3221 source = ParameterSource.COMMANDLINE32223065 # The value wasn't set, or used the param's default, prompt if3066 # prompting is enabled.3223 # The value wasn't set, or used the param's default, prompt for one to the user3224 # if prompting is enabled.3225 elif (3068 source in {None, ParameterSource.DEFAULT}3226 (3227 value is UNSET3228 or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3229 )3230 and self.prompt is not None3231 and (self.required or self.prompt_required)3232 and not ctx.resilient_parsing3233 ):
1 unmodified line
3235 source = ParameterSource.PROMPT32363237 return value, source32383239 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:3240 if self.is_flag and not self.required:3241 if value is UNSET:3242 if self.is_bool_flag:3243 # If the flag is a boolean flag, we return False if it is not set.3244 value = False3245 return super().type_cast_value(ctx, value)324632473248class Argument(Parameter):3249 """Arguments are positional parameters to a command. They generally3250 provide fewer features than options but can have infinite ``nargs``3251 and are required by default.
8 unmodified lines
3260 param_decls: cabc.Sequence[str],3261 required: bool | None = None,3262 **attrs: t.Any,3263 ) -> None:3264 # Auto-detect the requirement status of the argument if not explicitly set.3265 if required is None:3096 if attrs.get("default") is not None:3097 required = False3098 else:3266 # The argument gets automatically required if it has no explicit default3267 # value set and is setup to match at least one value.3268 if attrs.get("default", UNSET) is UNSET:3269 required = attrs.get("nargs", 1) > 03270 # If the argument has a default value, it is not required.3271 else:3272 required = False32733274 if "multiple" in attrs:3275 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")32763277 super().__init__(param_decls, required=required, **attrs)32783106 if __debug__:3107 if self.default is not None and self.nargs == -1:3108 raise TypeError("'default' is not supported for nargs=-1.")31093279 @property3280 def human_readable_name(self) -> str:3281 if self.metavar is not None:3282 return self.metavar
65 unmodified lines
modified:src/click/parser.py+24 added-24 removed
28 unmodified lines
29from collections import deque30from gettext import gettext as _31from gettext import ngettext3233from ._utils import FLAG_NEEDS_VALUE34from ._utils import UNSET35from .exceptions import BadArgumentUsage36from .exceptions import BadOptionUsage37from .exceptions import NoSuchOption38from .exceptions import UsageError3940if t.TYPE_CHECKING:41 from ._utils import T_FLAG_NEEDS_VALUE42 from ._utils import T_UNSET43 from .core import Argument as CoreArgument44 from .core import Context45 from .core import Option as CoreOption46 from .core import Parameter as CoreParameter4748V = t.TypeVar("V")4946# Sentinel value that indicates an option was passed as a flag without a47# value but is not a flag option. Option.consume_value uses this to48# prompt or use the flag_value.49_flag_needs_value = object()505151def _unpack_args(52 args: cabc.Sequence[str], nargs_spec: cabc.Sequence[int]53) -> tuple[cabc.Sequence[str | cabc.Sequence[str | None] | None], list[str]]:54 """Given an iterable of arguments and an iterable of nargs specifications,
2 unmodified lines
5758 The nargs specification is the number of arguments that should be consumed59 or `-1` to indicate that this position should eat up all the remainders.6062 Missing items are filled with `None`.61 Missing items are filled with ``UNSET``.62 """63 args = deque(args)64 nargs_spec = deque(nargs_spec)66 rv: list[str | tuple[str | None, ...] | None] = []65 rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []66 spos: int | None = None6769 def _fetch(c: deque[V]) -> V | None:68 def _fetch(c: deque[V]) -> V | T_UNSET:69 try:70 if spos is None:71 return c.popleft()72 else:73 return c.pop()74 except IndexError:76 return None75 return UNSET7677 while nargs_spec:78 nargs = _fetch(nargs_spec)7980 if nargs is None:81 continue8283 if nargs == 1:85 rv.append(_fetch(args))84 rv.append(_fetch(args)) # type: ignore[arg-type]85 elif nargs > 1:86 x = [_fetch(args) for _ in range(nargs)]8788 # If we're reversed, we're pulling in the arguments in reverse,
6 unmodified lines
95 if spos is not None:96 raise TypeError("Cannot have two nargs < 0")9798 spos = len(rv)100 rv.append(None)99 rv.append(UNSET)100101 # spos is the position of the wildcard (star). If it's not `None`,102 # we fill it with the remainder.103 if spos is not None:
81 unmodified lines
185 self.obj = obj186187 def process(188 self,190 value: str | cabc.Sequence[str | None] | None,189 value: str | cabc.Sequence[str | None] | None | T_UNSET,190 state: _ParsingState,191 ) -> None:192 if self.nargs > 1:194 assert value is not None195 holes = sum(1 for x in value if x is None)193 assert isinstance(value, cabc.Sequence)194 holes = sum(1 for x in value if x is UNSET)195 if holes == len(value):197 value = None196 value = UNSET197 elif holes != 0:198 raise BadArgumentUsage(199 _("Argument {name!r} takes {nargs} values.").format(200 name=self.dest, nargs=self.nargs201 )202 )203205 if self.nargs == -1 and self.obj.envvar is not None and value == ():206 # Replace empty tuple with None so that a value from the207 # environment may be tried.208 value = None204 # We failed to collect any argument value so we consider the argument as unset.205 if value == ():206 value = UNSET207208 state.opts[self.dest] = value # type: ignore209 state.order.append(self.obj)210
170 unmodified lines
381 opt, _("Option {name!r} does not take a value.").format(name=opt)382 )383384 else:387 value = None385 value = UNSET386387 option.process(value, state)388389 def _match_short_opt(self, arg: str, state: _ParsingState) -> None:
21 unmodified lines
411412 value = self._get_value_from_state(opt, option, state)413414 else:417 value = None415 value = UNSET416417 option.process(value, state)418419 if stop:
7 unmodified lines
427 state.largs.append(f"{prefix}{''.join(unknown_options)}")428429 def _get_value_from_state(430 self, option_name: str, option: _Option, state: _ParsingState433 ) -> t.Any:431 ) -> str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE:432 nargs = option.nargs433434 value: str | cabc.Sequence[str] | T_FLAG_NEEDS_VALUE435436 if len(state.rargs) < nargs:437 if option.obj._flag_needs_value:438 # Option allows omitting the value.439 value = _flag_needs_value439 value = FLAG_NEEDS_VALUE440 else:441 raise BadOptionUsage(442 option_name,443 ngettext(
12 unmodified lines
456 and len(next_rarg) > 1457 ):458 # The next arg looks like the start of an option, don't459 # use it as the value if omitting the value is allowed.460 value = _flag_needs_value460 value = FLAG_NEEDS_VALUE461 else:462 value = state.rargs.pop(0)463 else:464 value = tuple(state.rargs[:nargs])
68 unmodified lines
modified:src/click/testing.py+8 added-9 removed
125 unmodified lines
126 @property127 def mode(self) -> str:128 return self._mode129130 def __next__(self) -> str: # type: ignore131 try:132 line = super().__next__()133 except StopIteration as e:134 raise EOFError() from e135 return line130137131def make_input_stream(132 input: str | bytes | t.IO[t.Any] | None, charset: str133) -> t.BinaryIO:134 # Is already an input stream.
216 unmodified lines
351352 @_pause_echo(echo_input) # type: ignore353 def visible_input(prompt: str | None = None) -> str:354 sys.stdout.write(prompt or "")355 try:362 val = next(text_input).rstrip("\r\n")356 val = next(text_input).rstrip("\r\n")357 except StopIteration as e:358 raise EOFError() from e359 sys.stdout.write(f"{val}\n")360 sys.stdout.flush()361 return val362363 @_pause_echo(echo_input) # type: ignore364 def hidden_input(prompt: str | None = None) -> str:365 sys.stdout.write(f"{prompt or ''}\n")366 sys.stdout.flush()367 try:371 return next(text_input).rstrip("\r\n")368 return next(text_input).rstrip("\r\n")369 except StopIteration as e:370 raise EOFError() from e371372 @_pause_echo(echo_input) # type: ignore373 def _getchar(echo: bool) -> str:374 char = sys.stdin.read(1)
203 unmodified lines
modified:tests/test_arguments.py+141 added-30 removed
2 unmodified lines
34import pytest56import click7from click._utils import UNSET8910def test_nargs_star(runner):11 @click.command()
7 unmodified lines
19 assert not result.exception20 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]212222def test_argument_unbounded_nargs_cant_have_default(runner):23 with pytest.raises(TypeError, match="nargs=-1"):2425 @click.command()26 @click.argument("src", nargs=-1, default=["42"])27 def copy(src):28 pass293023def test_nargs_tup(runner):24 @click.command()25 @click.argument("name", nargs=1)26 @click.argument("point", nargs=2, type=click.INT)
138 unmodified lines
165166 result = runner.invoke(inout, [])167 assert not result.exception168 assert result.output == "Foo bar baz\n"169 assert result.stdout == "Foo bar baz\n"170 assert not result.stderr171172173@pytest.mark.parametrize(174 ("nargs", "value", "expect"),
69 unmodified lines
244 assert result.exit_code == 2245 assert "Missing argument 'ARG'." in result.output246247254def test_missing_argument_string_cast():248@pytest.mark.parametrize(249 ("value", "expect_missing", "processed_value"),250 [251 # Unspecified type of the argument fallback to string, so everything is252 # processed the click.STRING type.253 ("", False, ""),254 (" ", False, " "),255 ("foo", False, "foo"),256 ("12", False, "12"),257 (12, False, "12"),258 (12.1, False, "12.1"),259 (list(), False, "[]"),260 (tuple(), False, "()"),261 (set(), False, "set()"),262 (frozenset(), False, "frozenset()"),263 (dict(), False, "{}"),264 # None is a value that is allowed to be processed by a required argument265 # because at this stage, the process_value method happens after the default is266 # applied.267 (None, False, None),268 # An UNSET required argument will raise MissingParameter.269 (UNSET, True, None),270 ],271)272def test_required_argument(value, expect_missing, processed_value):273 """Test how a required argument is processing the provided values."""274 ctx = click.Context(click.Command(""))275 argument = click.Argument(["a"], required=True)276277 if expect_missing:257 with pytest.raises(click.MissingParameter) as excinfo:258 click.Argument(["a"], required=True).process_value(ctx, None)278 with pytest.raises(click.MissingParameter) as excinfo:279 argument.process_value(ctx, value)280 assert str(excinfo.value) == "Missing parameter: a"281260 assert str(excinfo.value) == "Missing parameter: a"282 else:283 value = argument.process_value(ctx, value)284 assert value == processed_value285286287def test_implicit_non_required(runner):288 @click.command()
85 unmodified lines
374 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])375 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]376377354def test_defaults_for_nargs(runner):378@pytest.mark.parametrize(379 ("argument_params", "args", "expected"),380 [381 # Any iterable with the same number of arguments as nargs is valid.382 [{"nargs": 2, "default": (1, 2)}, [], (1, 2)],383 [{"nargs": 2, "default": (1.1, 2.2)}, [], (1, 2)],384 [{"nargs": 2, "default": ("1", "2")}, [], (1, 2)],385 [{"nargs": 2, "default": (None, None)}, [], (None, None)],386 [{"nargs": 2, "default": [1, 2]}, [], (1, 2)],387 [{"nargs": 2, "default": {1, 2}}, [], (1, 2)],388 [{"nargs": 2, "default": frozenset([1, 2])}, [], (1, 2)],389 [{"nargs": 2, "default": {1: "a", 2: "b"}}, [], (1, 2)],390 # Empty iterable is valid if default is None.391 [{"nargs": 2, "default": None}, [], None],392 # Arguments overrides the default.393 [{"nargs": 2, "default": (1, 2)}, ["3", "4"], (3, 4)],394 # Unbounded arguments are allowed to have a default.395 # See: https://github.com/pallets/click/issues/2164396 [{"nargs": -1, "default": [42]}, [], (42,)],397 [{"nargs": -1, "default": None}, [], ()],398 [{"nargs": -1, "default": {1, 2, 3, 4, 5}}, [], (1, 2, 3, 4, 5)],399 ],400)401def test_good_defaults_for_nargs(runner, argument_params, args, expected):402 @click.command()356 @click.argument("a", nargs=2, type=int, default=(1, 2))403 @click.argument("a", type=int, **argument_params)404 def cmd(a):358 x, y = a359 click.echo(x + y)405 click.echo(repr(a), nl=False)406361 result = runner.invoke(cmd, [])362 assert result.output.strip() == "3"407 result = runner.invoke(cmd, args)408 assert result.output == repr(expected)409364 result = runner.invoke(cmd, ["3", "4"])365 assert result.output.strip() == "7"410367 result = runner.invoke(cmd, ["3"])368 assert result.exception is not None369 assert "Argument 'a' takes 2 values." in result.output411@pytest.mark.parametrize(412 ("default", "message"),413 [414 # Non-iterables defaults.415 ["Yo", "Error: Invalid value for '[A]...': Value must be an iterable."],416 ["", "Error: Invalid value for '[A]...': Value must be an iterable."],417 [True, "Error: Invalid value for '[A]...': Value must be an iterable."],418 [False, "Error: Invalid value for '[A]...': Value must be an iterable."],419 [12, "Error: Invalid value for '[A]...': Value must be an iterable."],420 [7.9, "Error: Invalid value for '[A]...': Value must be an iterable."],421 # Generator default.422 [(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],423 # Unset default.424 [UNSET, "Error: Missing argument 'A...'."],425 # Tuples defaults with wrong length.426 [427 tuple(),428 "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",429 ],430 [(1,), "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],431 [432 (1, 2, 3),433 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",434 ],435 # Lists defaults with wrong length.436 [list(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],437 [[1], "Error: Invalid value for '[A]...': Takes 2 values but 1 was given."],438 [439 [1, 2, 3],440 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",441 ],442 # Sets defaults with wrong length.443 [set(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],444 [445 set([1]),446 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",447 ],448 [449 set([1, 2, 3]),450 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",451 ],452 # Frozensets defaults with wrong length.453 [454 frozenset(),455 "Error: Invalid value for '[A]...': Takes 2 values but 0 were given.",456 ],457 [458 frozenset([1]),459 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",460 ],461 [462 frozenset([1, 2, 3]),463 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",464 ],465 # Dictionaries defaults with wrong length.466 [dict(), "Error: Invalid value for '[A]...': Takes 2 values but 0 were given."],467 [468 {1: "a"},469 "Error: Invalid value for '[A]...': Takes 2 values but 1 was given.",470 ],471 [472 {1: "a", 2: "b", 3: "c"},473 "Error: Invalid value for '[A]...': Takes 2 values but 3 were given.",474 ],475 ],476)477def test_bad_defaults_for_nargs(runner, default, message):478 """Some defaults are not valid when nargs is set."""479480 @click.command()481 @click.argument("a", nargs=2, type=int, default=default)482 def cmd(a):483 click.echo(repr(a))484485 result = runner.invoke(cmd, [])486 assert message in result.stderr487488489def test_multiple_param_decls_not_allowed(runner):490 with pytest.raises(TypeError):491492 @click.command()
6 unmodified lines
499 with pytest.raises(TypeError, match="multiple"):500 click.Argument(["a"], multiple=True)501502386@pytest.mark.parametrize("value", [(), ("a",), ("a", "b", "c")])387def test_nargs_bad_default(runner, value):388 with pytest.raises(ValueError, match="nargs=2"):389 click.Argument(["a"], nargs=2, default=value)390391503def test_subcommand_help(runner):504 @click.group()505 @click.argument("name")506 @click.argument("val")
75 unmodified lines
modified:tests/test_basic.py+86 added-9 removed
5 unmodified lines
67import pytest89import click10from click._utils import UNSET111213def test_basic_functionality(runner):14 @click.command()
190 unmodified lines
205 else:206 assert result.exception is None207208208@pytest.mark.parametrize("default", [True, False])209@pytest.mark.parametrize(210 ("args", "expect"), [(["--on"], True), (["--off"], False), ([], None)]210 ("args", "default", "expect"),211 [212 (["--on"], True, True),213 (["--on"], False, True),214 (["--on"], None, True),215 (["--on"], UNSET, True),216 (["--off"], True, False),217 (["--off"], False, False),218 (["--off"], None, False),219 (["--off"], UNSET, False),220 ([], True, True),221 ([], False, False),222 ([], None, None),223 ([], UNSET, False),224 ],225)212def test_boolean_switch(runner, default, args, expect):226def test_boolean_switch(runner, args, default, expect):227 @click.command()228 @click.option("--on/--off", default=default)229 def cli(on):230 return on231218 if expect is None:219 expect = default220232 result = runner.invoke(cli, args, standalone_mode=False)233 assert result.return_value is expect234235
3 unmodified lines
239 (True, ["--f"], True),240 (True, [], True),241 (False, ["--f"], True),242 (False, [], False),243 # Boolean flags have a 3-states logic.244 # See: https://github.com/pallets/click/issues/3024#issue-3285556668245 (None, ["--f"], True),246 (None, [], None),247 ),248)249def test_boolean_flag(runner, default, args, expect):250 @click.command()
24 unmodified lines
275 result = runner.invoke(cli, ["--flag", value.title()])276 assert result.output == expect277278279@pytest.mark.parametrize(280 ("default", "args", "expected"),281 # These test cases are similar to the ones in282 # tests/test_options.py::test_default_dual_option_callback, so keep them in sync.283 (284 # Each option is returning its own flag_value, whatever the default is.285 (True, ["--upper"], "upper"),286 (True, ["--lower"], "lower"),287 (False, ["--upper"], "upper"),288 (False, ["--lower"], "lower"),289 (None, ["--upper"], "upper"),290 (None, ["--lower"], "lower"),291 (UNSET, ["--upper"], "upper"),292 (UNSET, ["--lower"], "lower"),293 # Check that the last option wins when both are specified.294 (True, ["--upper", "--lower"], "lower"),295 (True, ["--lower", "--upper"], "upper"),296 # Check that the default is returned as-is when no option is specified.297 ("upper", [], "upper"),298 ("lower", [], "lower"),299 ("uPPer", [], "uPPer"),300 ("lOwEr", [], "lOwEr"),301 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),302 (None, [], None),303 # Default is normalized to None if it is UNSET.304 (UNSET, [], None),305 # Special case: if default=True and flag_value is set, the value returned is the306 # flag_value, not the True Python value itself.307 (True, [], "upper"),308 # Non-string defaults are process as strings by the default Parameter's type.309 (False, [], "False"),310 (42, [], "42"),311 (12.3, [], "12.3"),312 ),313)314def test_flag_value_dual_options(runner, default, args, expected):315 """Check how default is processed when options compete for the same variable name.316317 Covers the regression reported in318 https://github.com/pallets/click/issues/3024#issuecomment-3146199461319 """320321 @click.command()322 @click.option("--upper", "case", flag_value="upper", default=default)323 @click.option("--lower", "case", flag_value="lower")324 def cli(case):325 click.echo(repr(case), nl=False)326327 result = runner.invoke(cli, args)328 assert result.output == repr(expected)329330331def test_file_option(runner):332 @click.command()333 @click.option("--file", type=click.File("w"))334 def input(file):
206 unmodified lines
541 "method", type=click.Choice(["not-none", None], case_sensitive=False)542 )543 def cli(method: str | None):544 assert isinstance(method, str) or method is None478 click.echo(method)545 click.echo(repr(method), nl=False)546547 result = runner.invoke(cli, ["not-none"])548 assert not result.exception482 assert result.output == "not-none\n"549 assert result.output == repr("not-none")550484 # None is not yet supported.551 result = runner.invoke(cli, ["none"])552 assert not result.exception553 assert result.output == repr(None)554555 result = runner.invoke(cli, [])556 assert result.exception557 assert (558 "Error: Missing argument '{not-none|none}'. "559 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr560 )561562 result = runner.invoke(cli, ["--help"])563 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")564565566def test_datetime_option_default(runner):567 @click.command()568 @click.option("--start_date", type=click.DateTime())569 def cli(start_date):
166 unmodified lines
modified:tests/test_chain.py+2 added-2 removed
161 unmodified lines
162163 return processor164165 result = runner.invoke(cli, args, input=input)166 # last two lines are '' and 'Aborted!'167 assert result.output.splitlines()[:-2] == expect166 assert not result.exception167 assert result.output.splitlines() == expect168169170def test_args_and_chain(runner):171 @click.group(chain=True)
74 unmodified lines
modified:tests/test_context.py+127 added
1import logging2from contextlib import AbstractContextManager3from contextlib import contextmanager4from types import TracebackType56import pytest78import click
415 unmodified lines
424425 assert rv == [0]426427428def test_with_resource_exception() -> None:429 class TestContext(AbstractContextManager[list[int]]):430 _handle_exception: bool431 _base_val: int432 val: list[int]433434 def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:435 self._handle_exception = handle_exception436 self._base_val = base_val437438 def __enter__(self) -> list[int]:439 self.val = [self._base_val]440 return self.val441442 def __exit__(443 self,444 exc_type: type[BaseException] | None,445 exc_value: BaseException | None,446 traceback: TracebackType | None,447 ) -> bool | None:448 if not exc_type:449 self.val[0] = self._base_val - 1450 return None451452 self.val[0] = self._base_val + 1453 return self._handle_exception454455 class TestException(Exception):456 pass457458 ctx = click.Context(click.Command("test"))459460 base_val = 1461462 with ctx.scope():463 rv = ctx.with_resource(TestContext(base_val=base_val))464 assert rv[0] == base_val465466 assert rv == [base_val - 1]467468 with ctx.scope():469 rv = ctx.with_resource(TestContext(base_val=base_val))470 raise TestException()471472 assert rv == [base_val + 1]473474 with pytest.raises(TestException):475 with ctx.scope():476 rv = ctx.with_resource(477 TestContext(base_val=base_val, handle_exception=False)478 )479 raise TestException()480481482def test_with_resource_nested_exception() -> None:483 class TestContext(AbstractContextManager[list[int]]):484 _handle_exception: bool485 _base_val: int486 val: list[int]487488 def __init__(self, base_val: int = 1, *, handle_exception: bool = True) -> None:489 self._handle_exception = handle_exception490 self._base_val = base_val491492 def __enter__(self) -> list[int]:493 self.val = [self._base_val]494 return self.val495496 def __exit__(497 self,498 exc_type: type[BaseException] | None,499 exc_value: BaseException | None,500 traceback: TracebackType | None,501 ) -> bool | None:502 if not exc_type:503 self.val[0] = self._base_val - 1504 return None505506 self.val[0] = self._base_val + 1507 return self._handle_exception508509 class TestException(Exception):510 pass511512 ctx = click.Context(click.Command("test"))513 base_val = 1514 base_val_nested = 11515516 with ctx.scope():517 rv = ctx.with_resource(TestContext(base_val=base_val))518 rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))519 assert rv[0] == base_val520 assert rv_nested[0] == base_val_nested521522 assert rv == [base_val - 1]523 assert rv_nested == [base_val_nested - 1]524525 with ctx.scope():526 rv = ctx.with_resource(TestContext(base_val=base_val))527 rv_nested = ctx.with_resource(TestContext(base_val=base_val_nested))528 raise TestException()529530 # If one of the context "eats" the exceptions they will not be forwarded to other531 # parts. This is due to how ExitStack unwinding works532 assert rv_nested == [base_val_nested + 1]533 assert rv == [base_val - 1]534535 with ctx.scope():536 rv = ctx.with_resource(TestContext(base_val=base_val))537 rv_nested = ctx.with_resource(538 TestContext(base_val=base_val_nested, handle_exception=False)539 )540 raise TestException()541542 assert rv_nested == [base_val_nested + 1]543 assert rv == [base_val + 1]544545 with pytest.raises(TestException):546 rv = ctx.with_resource(TestContext(base_val=base_val, handle_exception=False))547 rv_nested = ctx.with_resource(548 TestContext(base_val=base_val_nested, handle_exception=False)549 )550 raise TestException()551552553def test_make_pass_decorator_args(runner):554 """555 Test to check that make_pass_decorator doesn't consume arguments based on556 invocation order.
116 unmodified lines
modified:tests/test_options.py+995 added-239 removed
1import enum2import os3import re4import sys5import tempfile6from contextlib import nullcontext7from typing import Literal89if sys.version_info < (3, 11):10 enum.StrEnum = enum.Enum # type: ignore[assignment]1112import pytest1314import click15from click import Option16from click import UNPROCESSED17from click._utils import UNSET181920def test_prefixes(runner):21 @click.command()
67 unmodified lines
89 click.Option(["--a"], prompt=True, deprecated=True)909192def test_invalid_nargs(runner):88 with pytest.raises(TypeError, match="nargs=-1"):93 with pytest.raises(TypeError, match="nargs=-1 is not supported for options."):9495 @click.command()96 @click.option("--foo", nargs=-1)97 def cli(foo):
76 unmodified lines
174 assert "Error: Missing option '-m' / '--message'." in result.output175176177@pytest.mark.parametrize(173 ("multiple", "nargs", "default"),178 ("multiple", "nargs", "default", "expected"),179 [175 (True, 1, []),176 (True, 1, [1]),177 # (False, -1, []),178 # (False, -1, [1]),179 (False, 2, [1, 2]),180 # (True, -1, [[]]),181 # (True, -1, []),182 # (True, -1, [[1]]),183 (True, 2, []),184 (True, 2, [[1, 2]]),180 # If multiple values are allowed, defaults should be iterable.181 (True, 1, [], ()),182 (True, 1, (), ()),183 (True, 1, tuple(), ()),184 (True, 1, set(), ()),185 (True, 1, frozenset(), ()),186 (True, 1, {}, ()),187 # Special values.188 (True, 1, None, ()),189 (True, 1, UNSET, ()),190 # Number of values are kept as-is in the default.191 (True, 1, [1], (1,)),192 (True, 1, [1, 2], (1, 2)),193 (True, 1, [1, 2, 3], (1, 2, 3)),194 (True, 1, [1.1, 2.2], (1.1, 2.2)),195 (True, 1, ["1", "2"], ("1", "2")),196 (True, 1, [None, None], (None, None)),197 # Contrary to list or tuples, native Python types not supported by Click are198 # not recognized and are converted to the default format: tuple of strings.199 # Refs: https://github.com/pallets/click/issues/3036200 (True, 1, {1, 2}, ("1", "2")),201 (True, 1, frozenset([1, 2]), ("1", "2")),202 (True, 1, {1: "a", 2: "b"}, ("1", "2")),203 # Multiple values with nargs > 1.204 (True, 2, [], ()),205 (True, 2, (), ()),206 (True, 2, tuple(), ()),207 (True, 2, set(), ()),208 (True, 2, frozenset(), ()),209 (True, 2, {}, ()),210 (True, 2, None, ()),211 (True, 2, UNSET, ()),212 (True, 2, [[1, 2]], ((1, 2),)),213 (True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))),214 (True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))),215 (True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))),216 (True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))),217 (True, 2, [[None, None], [None, None]], ((None, None), (None, None))),218 (True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))),219 (True, 2, [[1, 2.2], None], ((1, 2.2), None)),220 # Default of the right length works for non-multiples.221 (False, 2, [1, 2], (1, 2)),222 ],223)187def test_init_good_default_list(runner, multiple, nargs, default):188 click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)224def test_good_defaults_for_multiple(runner, multiple, nargs, default, expected):225 @click.command()226 @click.option("-a", multiple=multiple, nargs=nargs, default=default)227 def cmd(a):228 click.echo(repr(a), nl=False)229230 result = runner.invoke(cmd)231 assert result.output == repr(expected)232233234@pytest.mark.parametrize(192 ("multiple", "nargs", "default"),235 ("multiple", "nargs", "default", "exception", "message"),236 [194 (True, 1, 1),195 # (False, -1, 1),196 (False, 2, [1]),197 (True, 2, [[1]]),237 # Non-iterables defaults.238 (239 True,240 1,241 "Yo",242 None,243 "Error: Invalid value for '-a': Value must be an iterable.",244 ),245 (246 True,247 1,248 "",249 None,250 "Error: Invalid value for '-a': Value must be an iterable.",251 ),252 (253 True,254 1,255 True,256 None,257 "Error: Invalid value for '-a': Value must be an iterable.",258 ),259 (260 True,261 1,262 False,263 None,264 "Error: Invalid value for '-a': Value must be an iterable.",265 ),266 (267 True,268 1,269 12,270 None,271 "Error: Invalid value for '-a': Value must be an iterable.",272 ),273 (274 True,275 1,276 7.9,277 None,278 "Error: Invalid value for '-a': Value must be an iterable.",279 ),280 #281 (282 False,283 2,284 42,285 None,286 "Error: Invalid value for '-a': Value must be an iterable.",287 ),288 (289 True,290 2,291 ["test string which is not a list in the list"],292 None,293 "Error: Invalid value for '-a': Value must be an iterable.",294 ),295 # Multiple options, each with 2 args, but with wrong length.296 (297 True,298 2,299 (1,),300 None,301 "Error: Invalid value for '-a': Value must be an iterable.",302 ),303 (304 True,305 2,306 (1, 2, 3),307 None,308 "Error: Invalid value for '-a': Value must be an iterable.",309 ),310 (311 True,312 2,313 [tuple()],314 ValueError,315 r"'nargs' must be 0 \(or None\) for type <click\.types\.Tuple object at "316 r"0x[0-9A-Fa-f]+>, but it was 2\.",317 ),318 (319 True,320 2,321 [(1,)],322 ValueError,323 r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "324 r"0x[0-9A-Fa-f]+>, but it was 2\.",325 ),326 (327 True,328 2,329 [(1, 2, 3)],330 ValueError,331 r"'nargs' must be 3 \(or None\) for type <click\.types\.Tuple object at "332 r"0x[0-9A-Fa-f]+>, but it was 2\.",333 ),334 # A mix of valid and invalid defaults.335 (336 True,337 2,338 [[1, 2.2], []],339 None,340 "Error: Invalid value for '-a': 2 values are required, but 0 were given.",341 ),342 # Default values that are iterable but not of the right length.343 (344 False,345 2,346 [1],347 None,348 "Error: Invalid value for '-a': Takes 2 values but 1 was given.",349 ),350 (351 True,352 2,353 [[1]],354 ValueError,355 r"'nargs' must be 1 \(or None\) for type <click\.types\.Tuple object at "356 r"0x[0-9A-Fa-f]+>, but it was 2\.",357 ),358 ],359)200def test_init_bad_default_list(runner, multiple, nargs, default):201 type = (str, str) if nargs == 2 else None360def test_bad_defaults_for_multiple(361 runner, multiple, nargs, default, exception, message362):363 if exception:364 assert issubclass(exception, Exception)365 else:366 assert exception is None367203 with pytest.raises(ValueError, match="default"):204 click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)368 with (369 pytest.raises(exception, match=re.compile(message))370 if exception371 else nullcontext()372 ):373374 @click.command()375 @click.option("-a", multiple=multiple, nargs=nargs, default=default)376 def cmd(a):377 click.echo(repr(a))378379 result = runner.invoke(cmd)380 assert message in result.stderr381382383@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])384def test_empty_envvar(runner, env_key):385 @click.command()386 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")
41 unmodified lines
428 assert result.output == "foo|bar\n"429430431@pytest.mark.parametrize(256 ("name", "value", "expected"),432 ("envvar_name", "envvar_value", "expected"),433 (434 # Lower-cased variations of value.435 ("SHOUT", "true", True),436 ("SHOUT", "false", False),
8 unmodified lines
445 ("SHOUT", "truE", True),446 ("SHOUT", "FaLsE", False),447 ("SHOUT", "falsE", False),448 # Extra spaces around the value.273 ("SHOUT", "true ", True),274 ("SHOUT", " true", True),275 ("SHOUT", " true ", True),276 ("SHOUT", "false ", False),277 ("SHOUT", " false", False),278 ("SHOUT", " false ", False),449 ("SHOUT", "true ", True),450 ("SHOUT", " true ", True),451 ("SHOUT", " true", True),452 ("SHOUT", "false ", False),453 ("SHOUT", " false ", False),454 ("SHOUT", " false", False),455 # Integer variations.456 ("SHOUT", "1", True),457 ("SHOUT", "0", False),458 # Alternative states.459 ("SHOUT", "t", True),460 ("SHOUT", "T", True),461 ("SHOUT", " T ", True),462 ("SHOUT", "f", False),463 ("SHOUT", "y", True),464 ("SHOUT", "n", False),465 ("SHOUT", "yes", True),
6 unmodified lines
472 ("SHOUT", " ", False),473 ("SHOUT", " ", False),474 # Variable names are not stripped of spaces and so don't match the475 # flag, which then naturraly takes its default value.298 ("SHOUT ", "True", False),299 ("SHOUT ", "False", False),476 ("SHOUT ", "True", False),477 ("SHOUT ", "False", False),478 (" SHOUT ", "True", False),479 (" SHOUT ", "False", False),480 (" SHOUT", "True", False),481 (" SHOUT", "False", False),482 ("SH OUT", "True", False),483 ("SH OUT", "False", False),484 # Same for random and reverse environment variable names: they are not485 # recognized by the option.486 ("RANDOM", "True", False),487 ("NO_SHOUT", "True", False),488 ("NO_SHOUT", "False", False),489 ("NOSHOUT", "True", False),490 ("NOSHOUT", "False", False),491 ),492)309def test_boolean_envvar_normalization(runner, name, value, expected):493def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):494 assert isinstance(envvar_name, str)495 assert isinstance(envvar_value, str) or envvar_value is None496497 @click.command()498 @click.option("--shout/--no-shout", envvar="SHOUT")499 def cli(shout):313 click.echo(f"shout: {shout!r}")500 click.echo(repr(shout), nl=False)501315 result = runner.invoke(cli, [], env={name: value})502 result = runner.invoke(cli, [], env={envvar_name: envvar_value})503 assert result.exit_code == 0317 assert result.output == f"shout: {expected}\n"504 assert result.output == repr(expected)505506507@pytest.mark.parametrize(321 ("name", "value"),508 "value",509 (323 ("SHOUT", "tr ue"),324 ("SHOUT", "10"),325 ("SHOUT", "01"),326 ("SHOUT", "00"),327 ("SHOUT", "11"),328 ("SHOUT", "randomstring"),329 ("SHOUT", "None"),510 # Extra spaces inside the value.511 "tr ue",512 "fa lse",513 # Numbers.514 "10",515 "01",516 "00",517 "11",518 "0.0",519 "1.1",520 # Random strings.521 "randomstring",522 "None",523 "'None'",524 "A B",525 " 1 2 ",526 "9.3",527 "a;n",528 "x:y",529 "i/o",530 ),531)332def test_boolean_envvar_bad_values(runner, name, value):532def test_boolean_envvar_bad_values(runner, value):533 @click.command()534 @click.option("--shout/--no-shout", envvar="SHOUT")535 def cli(shout):336 click.echo(f"shout: {shout!r}")536 click.echo(shout)537338 result = runner.invoke(cli, [], env={name: value})538 result = runner.invoke(cli, [], env={"SHOUT": value})539 assert result.exit_code == 2540 assert (541 f"Invalid value for '--shout': {value!r} is not a valid boolean."542 in result.output
285 unmodified lines
828 result = runner.invoke(cmd, ["-whatever=23"])829 assert result.output == "23\n"830831632def test_missing_option_string_cast():832@pytest.mark.parametrize(833 ("value", "expect_missing", "processed_value"),834 [835 (UNSET, True, None),836 (None, False, None),837 # Default type of the argument is str, so everything is processed as strings.838 ("", False, ""),839 (" ", False, " "),840 ("foo", False, "foo"),841 ("12", False, "12"),842 (12, False, "12"),843 (12.1, False, "12.1"),844 (list(), False, "[]"),845 (tuple(), False, "()"),846 (set(), False, "set()"),847 (frozenset(), False, "frozenset()"),848 (dict(), False, "{}"),849 ],850)851def test_required_option(value, expect_missing, processed_value):852 ctx = click.Context(click.Command(""))853 argument = click.Option(["-a"], required=True)854855 if expect_missing:635 with pytest.raises(click.MissingParameter) as excinfo:636 click.Option(["-a"], required=True).process_value(ctx, None)856 with pytest.raises(click.MissingParameter) as excinfo:857 argument.process_value(ctx, value)858 assert str(excinfo.value) == "Missing parameter: a"859638 assert str(excinfo.value) == "Missing parameter: a"860 else:861 value = argument.process_value(ctx, value)862 assert value == processed_value863864865def test_missing_required_flag(runner):866 cli = click.Command(
456 unmodified lines
1323 assert param.type is click.INT132413251326@pytest.mark.parametrize(1103 ("opt_params", "pass_flag", "expected"),1327 ("opt_params", "args", "expected"),1328 [1105 # Effect of the presence/absence of flag depending on type1106 ({"type": bool}, False, False),1107 ({"type": bool}, True, True),1108 ({"type": click.BOOL}, False, False),1109 ({"type": click.BOOL}, True, True),1110 ({"type": str}, False, "False"),1111 ({"type": str}, True, "True"),1112 # Effects of default value1113 ({"type": bool, "default": True}, False, True),1114 ({"type": bool, "default": True}, True, True),1115 ({"type": bool, "default": False}, False, False),1116 ({"type": bool, "default": False}, True, True),1117 ({"type": bool, "default": None}, False, False),1118 ({"type": bool, "default": None}, True, True),1119 ({"type": click.BOOL, "default": True}, False, True),1120 ({"type": click.BOOL, "default": True}, True, True),1121 ({"type": click.BOOL, "default": False}, False, False),1122 ({"type": click.BOOL, "default": False}, True, True),1123 ({"type": click.BOOL, "default": None}, False, False),1124 ({"type": click.BOOL, "default": None}, True, True),1125 ({"type": str, "default": True}, False, "True"),1126 ({"type": str, "default": True}, True, "True"),1127 ({"type": str, "default": False}, False, "False"),1128 ({"type": str, "default": False}, True, "True"),1129 ({"type": str, "default": "foo"}, False, "foo"),1130 ({"type": str, "default": "foo"}, True, "foo"),1131 ({"type": str, "default": None}, False, "False"),1132 ({"type": str, "default": None}, True, "True"),1133 # Effects of flag_value1134 ({"type": bool, "flag_value": True}, False, False),1135 ({"type": bool, "flag_value": True}, True, True),1136 ({"type": bool, "flag_value": False}, False, False),1137 ({"type": bool, "flag_value": False}, True, False),1138 ({"type": bool, "flag_value": None}, False, False),1139 ({"type": bool, "flag_value": None}, True, True),1140 ({"type": click.BOOL, "flag_value": True}, False, False),1141 ({"type": click.BOOL, "flag_value": True}, True, True),1142 ({"type": click.BOOL, "flag_value": False}, False, False),1143 ({"type": click.BOOL, "flag_value": False}, True, False),1144 ({"type": click.BOOL, "flag_value": None}, False, False),1145 ({"type": click.BOOL, "flag_value": None}, True, True),1146 ({"type": str, "flag_value": True}, False, "False"),1147 ({"type": str, "flag_value": True}, True, "True"),1148 ({"type": str, "flag_value": False}, False, "False"),1149 ({"type": str, "flag_value": False}, True, "False"),1150 ({"type": str, "flag_value": "foo"}, False, "False"),1151 ({"type": str, "flag_value": "foo"}, True, "foo"),1152 ({"type": str, "flag_value": None}, False, "False"),1153 ({"type": str, "flag_value": None}, True, "True"),1154 # Not passing --foo returns the default value as-is1155 ({"type": bool, "default": True, "flag_value": True}, False, True),1156 ({"type": bool, "default": True, "flag_value": False}, False, True),1157 ({"type": bool, "default": False, "flag_value": True}, False, False),1158 ({"type": bool, "default": False, "flag_value": False}, False, False),1159 ({"type": bool, "default": None, "flag_value": True}, False, False),1160 ({"type": bool, "default": None, "flag_value": False}, False, False),1161 ({"type": str, "default": True, "flag_value": True}, False, "True"),1162 ({"type": str, "default": True, "flag_value": False}, False, "True"),1163 ({"type": str, "default": False, "flag_value": True}, False, "False"),1164 ({"type": str, "default": False, "flag_value": False}, False, "False"),1165 ({"type": str, "default": "foo", "flag_value": True}, False, "foo"),1166 ({"type": str, "default": "foo", "flag_value": False}, False, "foo"),1167 ({"type": str, "default": "foo", "flag_value": "bar"}, False, "foo"),1168 ({"type": str, "default": "foo", "flag_value": None}, False, "foo"),1169 ({"type": str, "default": None, "flag_value": True}, False, "False"),1170 ({"type": str, "default": None, "flag_value": False}, False, "False"),1171 # Passing --foo returns the explicitly set flag_value1172 ({"type": bool, "default": True, "flag_value": True}, True, True),1173 ({"type": bool, "default": True, "flag_value": False}, True, False),1174 ({"type": bool, "default": False, "flag_value": True}, True, True),1175 ({"type": bool, "default": False, "flag_value": False}, True, False),1176 ({"type": bool, "default": None, "flag_value": True}, True, True),1177 ({"type": bool, "default": None, "flag_value": False}, True, False),1178 ({"type": str, "default": True, "flag_value": True}, True, "True"),1179 ({"type": str, "default": True, "flag_value": False}, True, "False"),1180 ({"type": str, "default": False, "flag_value": True}, True, "True"),1181 ({"type": str, "default": False, "flag_value": False}, True, "False"),1182 ({"type": str, "default": "foo", "flag_value": True}, True, "True"),1183 ({"type": str, "default": "foo", "flag_value": False}, True, "False"),1184 ({"type": str, "default": "foo", "flag_value": "bar"}, True, "bar"),1185 ({"type": str, "default": "foo", "flag_value": None}, True, "foo"),1186 ({"type": str, "default": None, "flag_value": True}, True, "True"),1187 ({"type": str, "default": None, "flag_value": False}, True, "False"),1329 # The type passed to the option is responsible to converting the value, whether1330 # we pass the option flag or not.1331 ({"type": bool}, [], False),1332 ({"type": bool}, ["--foo"], True),1333 ({"type": click.BOOL}, [], False),1334 ({"type": click.BOOL}, ["--foo"], True),1335 ({"type": str}, [], None),1336 ({"type": str}, ["--foo"], "True"),1337 # Default value is given as-is to the --foo option when it is not passed,1338 # whatever the type. Now if --foo is passed, the value is always True, whatever1339 # the type. In both case the type of the option is responsible for the1340 # conversion of the value.1341 ({"type": bool, "default": True}, [], True),1342 ({"type": bool, "default": True}, ["--foo"], True),1343 ({"type": bool, "default": False}, [], False),1344 ({"type": bool, "default": False}, ["--foo"], True),1345 # ({"type": bool, "default": "foo"}, [], "foo"),1346 ({"type": bool, "default": "foo"}, ["--foo"], True),1347 ({"type": bool, "default": None}, [], None),1348 ({"type": bool, "default": None}, ["--foo"], True),1349 ({"type": click.BOOL, "default": True}, [], True),1350 ({"type": click.BOOL, "default": True}, ["--foo"], True),1351 ({"type": click.BOOL, "default": False}, [], False),1352 ({"type": click.BOOL, "default": False}, ["--foo"], True),1353 # ({"type": click.BOOL, "default": "foo"}, [], "foo"),1354 ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),1355 ({"type": click.BOOL, "default": None}, [], None),1356 ({"type": click.BOOL, "default": None}, ["--foo"], True),1357 ({"type": str, "default": True}, [], "True"),1358 ({"type": str, "default": True}, ["--foo"], "True"),1359 ({"type": str, "default": False}, [], "False"),1360 ({"type": str, "default": False}, ["--foo"], "True"),1361 ({"type": str, "default": "foo"}, [], "foo"),1362 ({"type": str, "default": "foo"}, ["--foo"], "True"),1363 ({"type": str, "default": None}, [], None),1364 ({"type": str, "default": None}, ["--foo"], "True"),1365 # Flag value is given as-is to the --foo option when it is passed, then1366 # converted by the option type.1367 ({"type": bool, "flag_value": True}, [], False),1368 ({"type": bool, "flag_value": True}, ["--foo"], True),1369 ({"type": bool, "flag_value": False}, [], False),1370 ({"type": bool, "flag_value": False}, ["--foo"], False),1371 ({"type": bool, "flag_value": None}, [], False),1372 ({"type": bool, "flag_value": None}, ["--foo"], None),1373 ({"type": click.BOOL, "flag_value": True}, [], False),1374 ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),1375 ({"type": click.BOOL, "flag_value": False}, [], False),1376 ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),1377 ({"type": click.BOOL, "flag_value": None}, [], False),1378 ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),1379 ({"type": str, "flag_value": True}, [], None),1380 ({"type": str, "flag_value": True}, ["--foo"], "True"),1381 ({"type": str, "flag_value": False}, [], None),1382 ({"type": str, "flag_value": False}, ["--foo"], "False"),1383 ({"type": str, "flag_value": "foo"}, [], None),1384 ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1385 ({"type": str, "flag_value": None}, [], None),1386 ({"type": str, "flag_value": None}, ["--foo"], None),1387 # Not passing --foo returns the default value as-is, in its Python type, then1388 # converted by the option type.1389 ({"type": bool, "default": True, "flag_value": True}, [], True),1390 ({"type": bool, "default": True, "flag_value": False}, [], False),1391 ({"type": bool, "default": False, "flag_value": True}, [], False),1392 ({"type": bool, "default": False, "flag_value": False}, [], False),1393 ({"type": bool, "default": None, "flag_value": True}, [], None),1394 ({"type": bool, "default": None, "flag_value": False}, [], None),1395 ({"type": str, "default": True, "flag_value": True}, [], "True"),1396 ({"type": str, "default": True, "flag_value": False}, [], "False"),1397 ({"type": str, "default": False, "flag_value": True}, [], "False"),1398 ({"type": str, "default": False, "flag_value": False}, [], "False"),1399 ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1400 ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),1401 ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),1402 ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),1403 ({"type": str, "default": None, "flag_value": True}, [], None),1404 ({"type": str, "default": None, "flag_value": False}, [], None),1405 # Passing --foo returns the flag_value that was explicitly set by the user,1406 # with its Python type, but still converted by the option type.1407 ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),1408 ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),1409 ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),1410 ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),1411 ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),1412 ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),1413 ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),1414 ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),1415 ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),1416 ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),1417 ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),1418 ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),1419 ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),1420 ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),1421 ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),1422 ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),1423 ],1424)1190def test_flag_value_and_default(runner, opt_params, pass_flag, expected):1425def test_flag_value_and_default(runner, opt_params, args, expected):1426 @click.command()1427 @click.option("--foo", is_flag=True, **opt_params)1428 def cmd(foo):1194 click.echo(repr(foo))1429 click.echo(repr(foo), nl=False)14301196 result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1197 assert result.output == f"{expected!r}\n"1431 result = runner.invoke(cmd, args)1432 assert result.output == repr(expected)143314341435@pytest.mark.parametrize(1201 "opts",1436 ("args", "opts"),1437 [1203 {"type": bool, "default": "foo"},1204 {"type": bool, "flag_value": "foo"},1205 {"type": click.BOOL, "default": "foo"},1206 {"type": click.BOOL, "flag_value": "foo"},1438 ([], {"type": bool, "default": "foo"}),1439 ([], {"type": click.BOOL, "default": "foo"}),1440 (["--foo"], {"type": bool, "flag_value": "foo"}),1441 (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),1442 ],1443)1209def test_invalid_flag_definition(runner, opts):1444def test_invalid_flag_definition(runner, args, opts):1445 @click.command()1446 @click.option("--foo", is_flag=True, **opts)1447 def cmd(foo):1448 click.echo(foo)14491215 result = runner.invoke(cmd, ["--foo"])1450 result = runner.invoke(cmd, args)1451 assert (1452 "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1453 in result.output1454 )145514561457@pytest.mark.parametrize(1458 ("default", "args", "expected"),1459 # These test cases are similar to the ones in1460 # tests/test_basic.py::test_flag_value_dual_options, so keep them in sync.1461 (1462 # Each option is returning its own flag_value, whatever the default is.1463 (True, ["--js"], "js"),1464 (True, ["--xml"], "xml"),1465 (False, ["--js"], "js"),1466 (False, ["--xml"], "xml"),1467 (None, ["--js"], "js"),1468 (None, ["--xml"], "xml"),1469 (UNSET, ["--js"], "js"),1470 (UNSET, ["--xml"], "xml"),1471 # Check that the last option wins when both are specified.1472 (True, ["--js", "--xml"], "xml"),1473 (True, ["--xml", "--js"], "js"),1474 # Check that the default is returned as-is when no option is specified.1475 ("js", [], "js"),1476 ("xml", [], "xml"),1477 ("jS", [], "jS"),1478 ("xMl", [], "xMl"),1479 (" ᕕ( ᐛ )ᕗ ", [], " ᕕ( ᐛ )ᕗ "),1480 (None, [], None),1481 # Special case: UNSET is not provided as-is to the callback, but normalized to1482 # None.1483 (UNSET, [], None),1484 # Special case: if default=True and flag_value is set, the value returned is the1485 # flag_value, not the True Python value itself.1486 (True, [], "js"),1487 # Non-string defaults are process as strings by the default Parameter's type.1488 (False, [], "False"),1489 (42, [], "42"),1490 (12.3, [], "12.3"),1491 ),1492)1493def test_default_dual_option_callback(runner, default, args, expected):1494 """Check how default is processed by the callback when options compete for the same1495 variable name.14961497 Reproduction of the issue reported in1498 https://github.com/pallets/click/pull/3030#discussion_r22715718191499 """15001501 def _my_func(ctx, param, value):1502 # Print the value received by the callback as-is, so we can check for it.1503 return f"Callback value: {value!r}"15041505 @click.command()1506 @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)1507 @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)1508 def main(fmt):1509 click.secho(fmt, nl=False)15101511 result = runner.invoke(main, args)1512 assert result.output == f"Callback value: {expected!r}"1513 assert result.exit_code == 0151415151516@pytest.mark.parametrize(1517 ("flag_value", "envvar_value", "expected"),1518 [1225 # Envvar is set to false, so the flag default value is returned.1226 ("bar", "False", "False"),1227 # Same as above with alternative states and blank values.1228 ("bar", "0", "False"),1229 ("bar", "f", "False"),1230 ("bar", "", "False"),1231 # Envvar is set to true, so the flag_value is returned.1232 ("bar", "True", "bar"),1233 ("bar", "1", "bar"),1234 ("bar", "t", "bar"),1235 # So far we have the same cases as the test_flag_value_and_default1236 # test case. Now instead of passing a boolean-like value, let's use1237 # the flag_value as the envvar value.1519 # The envvar match exactly the flag value and is case-sensitive.1520 ("bar", "bar", "bar"),1239 # flag_value is expected to be the exact same in the envvar for the flag to be1240 # activated.1241 ("bar", " bar ", "False"),1242 ("bar", "BAR", "False"),1243 ("bar", "random", "False"),1244 ("bar", "bar random", "False"),1245 ("bar", "random bar", "False"),1521 ("BAR", "BAR", "BAR"),1247 ("BAR", "bar", "False"),1522 (" bar ", " bar ", " bar "),1523 ("42", "42", "42"),1524 ("None", "None", "None"),1525 ("True", "True", "True"),1526 ("False", "False", "False"),1527 ("true", "true", "true"),1528 ("false", "false", "false"),1529 ("A B", "A B", "A B"),1530 (" 1 2 ", " 1 2 ", " 1 2 "),1531 ("9.3", "9.3", "9.3"),1532 ("a;n", "a;n", "a;n"),1533 ("x:y", "x:y", "x:y"),1534 ("i/o", "i/o", "i/o"),1535 # Empty or absent envvar is consider unset, so the flag default value is1536 # returned, which is None in this case.1537 ("bar", "", None),1538 ("bar", None, None),1539 ("BAR", "", None),1540 ("BAR", None, None),1541 (" bar ", "", None),1542 (" bar ", None, None),1543 (42, "", None),1544 (42, None, None),1545 ("42", "", None),1546 ("42", None, None),1547 (None, "", None),1548 (None, None, None),1549 ("None", "", None),1550 ("None", None, None),1551 (True, "", None),1552 (True, None, None),1553 ("True", "", None),1554 ("True", None, None),1555 ("true", "", None),1556 ("true", None, None),1557 (False, "", None),1558 (False, None, None),1559 ("False", "", None),1560 ("False", None, None),1561 ("false", "", None),1562 ("false", None, None),1563 # Activate the flag with a value recognized as True by the envvar, which1564 # returns the flag_value.1565 ("bar", "True", "bar"),1566 ("bar", "true", "bar"),1567 ("bar", "trUe", "bar"),1568 ("bar", " TRUE ", "bar"),1569 ("bar", "1", "bar"),1570 ("bar", "yes", "bar"),1571 ("bar", "on", "bar"),1572 ("bar", "t", "bar"),1573 ("bar", "y", "bar"),1574 # Deactivating the flag with a value recognized as False by the envvar, which1575 # explicitly return the 'False' as the option is explicitly declared as a1576 # string.1577 ("bar", "False", "False"),1578 ("bar", "false", "False"),1579 ("bar", "faLse", "False"),1580 ("bar", " FALSE ", "False"),1249 (" bar ", "bar", "False"),1250 (" bar ", "BAR", "False"),1581 ("bar", "0", "False"),1582 ("bar", "no", "False"),1583 ("bar", "off", "False"),1584 ("bar", "f", "False"),1585 ("bar", "n", "False"),1586 # Any other value than the flag_value, or a recogned True or False value, fails1587 # to explicitly activate or deactivate the flag. So the flag default value is1588 # returned, which is None in this case.1589 ("bar", " bar ", None),1590 ("bar", "BAR", None),1591 ("bar", "random", None),1592 ("bar", "bar random", None),1593 ("bar", "random bar", None),1594 ("BAR", "bar", None),1595 (" bar ", "bar", None),1596 (" bar ", "BAR", None),1597 (42, "42", None),1598 (42, "foo", None),1599 (None, "foo", None),1600 ("None", "foo", None),1601 ],1602)1253def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1603def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):1604 """Ensure that flag_value is recognized by the envvar."""16051606 @click.command()1257 @click.option(1258 "--upper", type=str, is_flag=True, flag_value=flag_value, envvar="UPPER"1259 )1607 @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER")1608 def cmd(upper):1261 click.echo(repr(upper))1609 click.echo(repr(upper), nl=False)16101611 result = runner.invoke(cmd, env={"UPPER": envvar_value})1612 assert result.exit_code == 01265 assert result.output == f"{expected!r}\n"1613 assert result.output == repr(expected)161416151616@pytest.mark.parametrize(1269 ("option", "expected"),1617 ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"),1618 [1271 # Not boolean flags1272 pytest.param(Option(["-a"], type=int), False, id="int option"),1273 pytest.param(Option(["-a"], type=bool), False, id="bool non-flag [None]"),1274 pytest.param(Option(["-a"], default=True), False, id="bool non-flag [True]"),1275 pytest.param(Option(["-a"], default=False), False, id="bool non-flag [False]"),1276 pytest.param(Option(["-a"], flag_value=1), False, id="non-bool flag_value"),1277 # Boolean flags1278 pytest.param(Option(["-a"], is_flag=True), True, id="is_flag=True"),1279 pytest.param(Option(["-a/-A"]), True, id="secondary option [implicit flag]"),1280 pytest.param(Option(["-a"], flag_value=True), True, id="bool flag_value"),1619 # Not boolean flags.1620 ("-a", {"type": int}, False, False),1621 ("-a", {"type": bool}, False, False),1622 ("-a", {"default": True}, False, False),1623 ("-a", {"default": False}, False, False),1624 ("-a", {"flag_value": 1}, True, False),1625 # Boolean flags.1626 ("-a", {"is_flag": True}, True, True),1627 ("-a/-A", {}, True, True),1628 ("-a", {"flag_value": True}, True, True),1629 # Non-flag with flag_value.1630 ("-a", {"is_flag": False, "flag_value": 1}, False, False),1631 ],1632)1283def test_bool_flag_auto_detection(option, expected):1284 assert option.is_bool_flag is expected1633def test_flag_auto_detection(1634 opt_decls, opt_params, expect_is_flag, expect_is_bool_flag1635):1636 option = Option([opt_decls], **opt_params)1637 assert option.is_flag is expect_is_flag1638 assert option.is_bool_flag is expect_is_bool_flag163916401641@pytest.mark.parametrize(1642 ("kwargs", "message"),
23 unmodified lines
1666 assert result.exit_code == 0166716681669class HashType(enum.Enum):1316 MD5 = enum.auto()1317 SHA1 = enum.auto()1670 MD5 = "MD5"1671 SHA1 = "SHA1"1672 SHA256 = "SHA-256"167316741675class Number(enum.IntEnum):1676 ONE = enum.auto()1677 TWO = enum.auto()167816791680class Letter(enum.StrEnum):1326 A = enum.auto()1327 B = enum.auto()1681 NAME_1 = "Value-1"1682 NAME_2 = "Value_2"1683 NAME_3 = "42_value"168416851686class Color(enum.Flag):1687 RED = enum.auto()
7 unmodified lines
1695 BLUE = enum.auto()169616971698@pytest.mark.parametrize(1343 ("choices", "metavars"),1699 ("choices", "metavar"),1700 [1345 pytest.param(["foo", "bar"], "[TEXT]", id="text choices"),1346 pytest.param([1, 2], "[INTEGER]", id="int choices"),1347 pytest.param([1.0, 2.0], "[FLOAT]", id="float choices"),1348 pytest.param([True, False], "[BOOLEAN]", id="bool choices"),1349 pytest.param(["foo", 1], "[TEXT|INTEGER]", id="text/int choices"),1350 pytest.param(HashType, "[HASHTYPE]", id="enum choices"),1351 pytest.param(Number, "[NUMBER]", id="int enum choices"),1352 pytest.param(Letter, "[LETTER]", id="str enum choices"),1353 pytest.param(Color, "[COLOR]", id="flag enum choices"),1354 pytest.param(ColorInt, "[COLORINT]", id="int flag enum choices"),1701 (["foo", "bar"], "[TEXT]"),1702 ([1, 2], "[INTEGER]"),1703 ([1.0, 2.0], "[FLOAT]"),1704 ([True, False], "[BOOLEAN]"),1705 (["foo", 1], "[TEXT|INTEGER]"),1706 (HashType, "[HASHTYPE]"),1707 (Number, "[NUMBER]"),1708 (Letter, "[LETTER]"),1709 (Color, "[COLOR]"),1710 (ColorInt, "[COLORINT]"),1711 ],1712)1357def test_usage_show_choices(runner, choices, metavars):1358 """When show_choices=False is set, the --help output1359 should print choice metavars instead of values.1713def test_choice_usage_rendering(runner, choices, metavar):1714 """BY default ``--help`` prints choice's values in the usage message.17151716 But ``show_choices=False`` makes ``--help`` prints choice's METAVAR instead of1717 values.17181719 Also check that usage error message always suggests the actual values.1720 """17211722 @click.command()1723 @click.option("-g", type=click.Choice(choices))1724 def cli_with_choices(g):1725 pass17261727 @click.command()1368 @click.option(1369 "-g",1370 type=click.Choice(choices),1371 show_choices=False,1372 )1728 @click.option("-g", type=click.Choice(choices), show_choices=False)1729 def cli_without_choices(g):1730 pass17311376 result = runner.invoke(cli_with_choices, ["--help"])1377 assert (1378 f"[{'|'.join(i.name if isinstance(i, enum.Enum) else str(i) for i in choices)}]"1379 in result.output1732 display_values = tuple(1733 i.name if isinstance(i, enum.Enum) else str(i) for i in choices1734 )17351736 # Check that the choices values are rendered as-is in the usage message.1737 result = runner.invoke(cli_with_choices, ["--help"])1738 assert f"[{'|'.join(display_values)}]" in result.stdout1739 assert not result.stderr1740 assert result.exit_code == 017411742 # Check that the metavar is rendered instead of the choices values themselves.1743 result = runner.invoke(cli_without_choices, ["--help"])1383 assert metavars in result.output1744 assert metavar in result.stdout1745 assert not result.stderr1746 assert result.exit_code == 017471748 # Check the usage error message suggests the actual accepted values.1749 for cli in (cli_with_choices, cli_without_choices):1750 result = runner.invoke(cli, ["-g", "random"])1751 assert (1752 "\n\nError: Invalid value for '-g': 'random' is not one of "1753 f"{', '.join(map(repr, display_values))}.\n" in result.stderr1754 )1755 assert not result.stdout1756 assert result.exit_code == 2175717581759@pytest.mark.parametrize(1760 ("choices", "default", "default_string"),1761 [1762 (["foo", "bar"], "bar", "bar"),
10 unmodified lines
1773 ([True, False], True, "True"),1774 ([True, False], False, "False"),1775 (["foo", 1], "foo", "foo"),1776 (["foo", 1], 1, "1"),1404 # Enum choices are rendered as their names.1777 # Enum choices are rendered as their names, not values.1778 # See: https://github.com/pallets/click/issues/29111779 (HashType, HashType.SHA1, "SHA1"),1780 # Enum choices allow defaults strings that are their names.1408 (HashType, "SHA1", "SHA1"),1781 (HashType, HashType.SHA256, "SHA256"),1782 (HashType, "SHA256", "SHA256"),1783 (Number, Number.TWO, "TWO"),1410 (Letter, Letter.B, "B"),1784 (Number, "TWO", "TWO"),1785 (Letter, Letter.NAME_1, "NAME_1"),1786 (Letter, Letter.NAME_2, "NAME_2"),1787 (Letter, Letter.NAME_3, "NAME_3"),1788 (Letter, "NAME_1", "NAME_1"),1789 (Letter, "NAME_2", "NAME_2"),1790 (Letter, "NAME_3", "NAME_3"),1791 (Color, Color.GREEN, "GREEN"),1792 (Color, "GREEN", "GREEN"),1793 (ColorInt, ColorInt.GREEN, "GREEN"),1794 (ColorInt, "GREEN", "GREEN"),1795 ],1796)1797def test_choice_default_rendering(runner, choices, default, default_string):1798 @click.command()
37 unmodified lines
1836 with pytest.warns(UserWarning):1837 runner.invoke(cli, [])183818391840OBJECT_SENTINEL = object()1841"""An object-based sentinel value."""184218431844class EnumSentinel(enum.Enum):1845 FALSY_SENTINEL = object()18461847 def __bool__(self) -> Literal[False]:1848 """Force the sentinel to be falsy to make sure it is not caught by Click1849 internal implementation.18501851 Falsy sentinels have been discussed in:1852 https://github.com/pallets/click/pull/3030#pullrequestreview-31066047951853 https://github.com/pallets/click/pull/3030#pullrequestreview-31084715521854 """1855 return False185618571858# Any kind of sentinel value is recognized by Click as a valid flag value.1859@pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))1860@pytest.mark.parametrize(1459 ("multiple", "nargs", "default", "expected_message"),1861 ("args", "expected"),1862 (1863 # Option default to None.1864 ([], None),1865 # Config has no default value, and no flag value, so it requires an argument.1866 (1867 ["--config"],1868 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1869 ),1870 (1871 ["--no-config", "--config"],1872 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1873 ),1874 # Passing --no-config defaults to the sentinel value because of the flag_value,1875 # and then the custom type receives that sentinel and returns a message.1876 (["--no-config"], "No configuration file provided."),1877 # Passing --config with an argument returns the file path.1878 (["--config", "foo.conf"], "foo.conf"),1879 # An argument is not allowed for --no-config, so it raises an error.1880 (1881 ["--no-config", "foo.conf"],1882 re.compile(1883 r"Usage: main \[OPTIONS\]\n"1884 r"Try 'main --help' for help.\n"1885 r"\n"1886 r"Error: Got unexpected extra argument (.+)\n"1887 ),1888 ),1889 # Passing --config with an argument that does not exist raises an error.1890 (1891 ["--config", "random-file.conf"],1892 re.compile(1893 r"Usage: main \[OPTIONS\]\n"1894 r"Try 'main --help' for help.\n"1895 r"\n"1896 r"Error: Invalid value for '-c' / '--config': "1897 r"File 'random-file.conf' does not exist.\n"1898 ),1899 ),1900 (1901 ["--config", "--no-config"],1902 re.compile(1903 r"Usage: main \[OPTIONS\]\n"1904 r"Try 'main --help' for help.\n"1905 r"\n"1906 r"Error: Invalid value for '-c' / '--config': "1907 r"File '--no-config' does not exist.\n"1908 ),1909 ),1910 (1911 ["--config", "--no-config", "foo.conf"],1912 re.compile(1913 r"Usage: main \[OPTIONS\]\n"1914 r"Try 'main --help' for help.\n"1915 r"\n"1916 r"Error: Invalid value for '-c' / '--config': "1917 r"File '--no-config' does not exist.\n"1918 ),1919 ),1920 # --config is passed last and overrides the --no-config option.1921 (["--no-config", "--config", "foo.conf"], "foo.conf"),1922 ),1923)1924def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected):1925 """Check that an object-based sentinel, used as a flag value, is returned as-is1926 to a custom type that is shared by two options, competing for the same variable1927 name.19281929 A reproduction of1930 https://github.com/pallets/click/issues/3024#issuecomment-31465113561931 """19321933 class ConfigParamType(click.ParamType):1934 """A custom type that accepts a file path or a sentinel value."""19351936 def convert(self, value, param, ctx):1937 if value is sentinel:1938 return "No configuration file provided."1939 else:1940 return click.Path(exists=True, dir_okay=False).convert(1941 value, param, ctx1942 )19431944 @click.command()1945 @click.option("-c", "--config", type=ConfigParamType())1946 @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType())1947 def main(config):1948 click.echo(repr(config), nl=False)19491950 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:1951 if "foo.conf" in args:1952 named_tempfile.write("Blah blah")1953 named_tempfile.flush()1954 args = [named_tempfile.name if a == "foo.conf" else a for a in args]19551956 result = runner.invoke(main, args)19571958 if isinstance(expected, re.Pattern):1959 assert re.match(expected, result.output)1960 else:1961 assert result.output == repr(1962 named_tempfile.name if expected == "foo.conf" else expected1963 )196419651966class EngineType(enum.Enum):1967 OSS = enum.auto()1968 PRO = enum.auto()1969 MAX = enum.auto()197019711972class Class1:1973 pass197419751976class Class2:1977 pass197819791980@pytest.mark.parametrize(1981 ("opt_params", "args", "expected"),1982 [1983 # Check that the flag value is returned as-is when the option is passed, and1984 # not normalized to a boolean, even if it is explicitly declared as a flag.1985 ({"type": EngineType, "flag_value": None}, ["--pro"], None),1986 (1462 False, # multiple1463 2, # nargs1464 42, # default (not a list)1465 "'default' must be a list when 'nargs' != 1.",1987 {"type": EngineType, "is_flag": True, "flag_value": None},1988 ["--pro"],1989 None,1990 ),1991 ({"type": EngineType, "flag_value": EngineType.OSS}, ["--pro"], EngineType.OSS),1992 (1468 True, # multiple1469 2, # nargs1470 [1471 "test string which is not a list in the list"1472 ], # default (list of non-lists)1473 "'default' must be a list of lists when 'multiple' is true"1474 " and 'nargs' != 1.",1993 {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},1994 ["--pro"],1995 EngineType.OSS,1996 ),1997 (1998 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},1999 ["--pro"],2000 EngineType.OSS,2001 ),2002 # The default value is returned as-is when the option is not passed, whatever2003 # the flag value.2004 ({"type": EngineType, "flag_value": None}, [], None),2005 ({"type": EngineType, "is_flag": True, "flag_value": None}, [], None),2006 ({"type": EngineType, "flag_value": EngineType.OSS}, [], None),2007 (2008 {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},2009 [],2010 None,2011 ),2012 (2013 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},2014 [],2015 EngineType.OSS,2016 ),2017 # The option has not enough parameters to be detected as flag-like, so it2018 # requires an argument.2019 (2020 {"type": EngineType, "default": EngineType.OSS},2021 ["--pro"],2022 re.compile(re.escape("Error: Option '--pro' requires an argument.\n")),2023 ),2024 ({"type": EngineType, "default": EngineType.OSS}, [], EngineType.OSS),2025 # If a flag value is set, it is returned instead of the default value.2026 (2027 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2028 ["--pro"],2029 EngineType.OSS,2030 ),2031 (2032 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2033 [],2034 EngineType.OSS,2035 ),2036 # Type is not specified and default to string, so the default value is2037 # returned as a string, even if it is a boolean. Also, defaults to the2038 # flag_value instead of the default value to support legacy behavior.2039 ({"flag_value": "1", "default": True}, [], "1"),2040 ({"flag_value": "1", "default": 42}, [], "42"),2041 ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),2042 ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),2043 # See: the result is the same if we force the type to be str.2044 ({"type": str, "flag_value": 1, "default": True}, [], "1"),2045 ({"type": str, "flag_value": 1, "default": 42}, [], "42"),2046 ({"type": str, "flag_value": "1", "default": True}, [], "1"),2047 ({"type": str, "flag_value": "1", "default": 42}, [], "42"),2048 (2049 {"type": str, "flag_value": EngineType.OSS, "default": True},2050 [],2051 "EngineType.OSS",2052 ),2053 ({"type": str, "flag_value": EngineType.OSS, "default": 42}, [], "42"),2054 # But having the flag value set to integer is automaticcally recognized by2055 # Click.2056 ({"flag_value": 1, "default": True}, [], 1),2057 ({"flag_value": 1, "default": 42}, [], 42),2058 ({"type": int, "flag_value": 1, "default": True}, [], 1),2059 ({"type": int, "flag_value": 1, "default": 42}, [], 42),2060 ({"type": int, "flag_value": "1", "default": True}, [], 1),2061 ({"type": int, "flag_value": "1", "default": 42}, [], 42),2062 ],2063)1478def test_default_type_error_raises(multiple, nargs, default, expected_message):1479 with pytest.raises(ValueError, match=expected_message):1480 click.Option(1481 ["--test"],1482 multiple=multiple,1483 nargs=nargs,1484 default=default,1485 )2064def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):2065 """Test how the type and flag_value influence the returned value.20662067 Cover cases reported in:2068 https://github.com/pallets/click/issues/3024#issuecomment-31464807142069 https://github.com/pallets/click/issues/2012#issuecomment-8924370602070 """20712072 @click.command()2073 @click.option("--pro", **opt_params)2074 def scan(pro):2075 click.echo(repr(pro), nl=False)20762077 result = runner.invoke(scan, args)2078 if isinstance(expected, re.Pattern):2079 assert re.match(expected, result.output)2080 else:2081 assert result.output == repr(expected)208220832084@pytest.mark.parametrize(2085 ("opt1_params", "opt2_params", "args", "expected"),2086 [2087 # Dual options sharing the same variable name, are not competitive, and the2088 # flag value is returned as-is. Especially when the type is force to be2089 # unprocessed.2090 (2091 {"flag_value": EngineType.OSS, "type": UNPROCESSED},2092 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2093 [],2094 None,2095 ),2096 (2097 {"flag_value": EngineType.OSS, "type": UNPROCESSED},2098 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2099 ["--opt1"],2100 EngineType.OSS,2101 ),2102 (2103 {"flag_value": EngineType.OSS, "type": UNPROCESSED},2104 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2105 ["--opt2"],2106 EngineType.PRO,2107 ),2108 # Check that passing exotic flag values like classes is supported, but are2109 # rendered to strings when the type is not specified.2110 (2111 {"flag_value": Class1, "default": True},2112 {"flag_value": Class2},2113 [],2114 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2115 ),2116 (2117 {"flag_value": Class1, "default": True},2118 {"flag_value": Class2},2119 ["--opt1"],2120 "<class 'test_options.Class1'>",2121 ),2122 (2123 {"flag_value": Class1, "default": True},2124 {"flag_value": Class2},2125 ["--opt2"],2126 "<class 'test_options.Class2'>",2127 ),2128 # Even the default is processed as a string.2129 ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),2130 ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),2131 # To get the classes as-is, we need to specify the type as UNPROCESSED.2132 (2133 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2134 {"flag_value": Class2, "type": UNPROCESSED},2135 [],2136 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2137 ),2138 (2139 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2140 {"flag_value": Class2, "type": UNPROCESSED},2141 ["--opt1"],2142 Class1,2143 ),2144 (2145 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2146 {"flag_value": Class2, "type": UNPROCESSED},2147 ["--opt2"],2148 Class2,2149 ),2150 # Setting the default to a class, an instance of the class is returned instead2151 # of the class itself, because the default is allowed to be callable (and2152 # consummd). And this happens whatever the type is.2153 (2154 {"flag_value": Class1, "default": Class1},2155 {"flag_value": Class2},2156 [],2157 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2158 ),2159 (2160 {"flag_value": Class1, "default": Class2},2161 {"flag_value": Class2},2162 [],2163 re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),2164 ),2165 (2166 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},2167 {"flag_value": Class2, "type": UNPROCESSED},2168 [],2169 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2170 ),2171 (2172 {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},2173 {"flag_value": Class2, "type": UNPROCESSED},2174 [],2175 re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),2176 ),2177 # Having the flag value set to integer is automaticcally recognized by Click.2178 (2179 {"flag_value": 1, "default": True},2180 {"flag_value": "1"},2181 [],2182 1,2183 ),2184 (2185 {"flag_value": 1, "type": int, "default": True},2186 {"flag_value": "1", "type": int},2187 [],2188 1,2189 ),2190 ],2191)2192def test_custom_type_flag_value_dual_options(2193 runner, opt1_params, opt2_params, args, expected2194):2195 """Test how flag values are processed with dual options competing for the same2196 variable name.21972198 Reproduce issues reported in:2199 https://github.com/pallets/click/issues/3024#issuecomment-31465085362200 https://github.com/pallets/click/issues/2012#issue-9464710492201 https://github.com/pallets/click/issues/2012#issuecomment-8924370602202 """22032204 @click.command()2205 @click.option("--opt1", "dual_option", **opt1_params)2206 @click.option("--opt2", "dual_option", **opt2_params)2207 def cli(dual_option):2208 click.echo(repr(dual_option), nl=False)22092210 result = runner.invoke(cli, args)2211 if isinstance(expected, re.Pattern):2212 assert re.match(expected, result.output)2213 else:2214 assert result.output == repr(expected)221522162217def test_custom_type_frozenset_flag_value(runner):2218 """Check that frozenset is correctly handled as a type, a flag value and a default.22192220 Reproduces https://github.com/pallets/click/issues/26102221 """22222223 @click.command()2224 @click.option(2225 "--without-scm-ignore-files",2226 "scm_ignore_files",2227 is_flag=True,2228 type=frozenset,2229 flag_value=frozenset(),2230 default=frozenset(["git"]),2231 )2232 def rcli(scm_ignore_files):2233 click.echo(repr(scm_ignore_files), nl=False)22342235 result = runner.invoke(rcli)2236 assert result.stdout == "frozenset({'git'})"2237 assert result.exit_code == 022382239 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2240 assert result.stdout == "frozenset()"2241 assert result.exit_code == 0
modified:tests/test_termui.py+218 added
4 unmodified lines
5import pytest67import click._termui_impl8from click._compat import WIN9from click.exceptions import BadParameter10from click.exceptions import MissingParameter111213class FakeClock:14 def __init__(self):
471 unmodified lines
486 # Confirm that the default value is not included in the output when `show_default`487 # is False488 result = runner.invoke(cmd, input="my-input", standalone_mode=False)489 assert "my-default-value" not in result.output490491492REPEAT = object()493"""Sentinel value to indicate that the prompt is expected to be repeated.494495I.e. the value provided by the user is not satisfactory and need to be re-prompted.496"""497498INVALID = object()499"""Sentinel value to indicate that the prompt is expected to be invalid.500501On invalid input, Click will output an error message and re-prompt the user.502"""503504BOOLEAN_FLAG_PROMPT_CASES = [505 ###506 ### Test cases with prompt=True explicitly enabled for the flag.507 ###508 # Prompt is allowed and the flag has no default, so it prompts.509 ({"prompt": True}, [], "[y/N]", "y", True),510 ({"prompt": True}, [], "[y/N]", "n", False),511 # Empty input default to False.512 ({"prompt": True}, [], "[y/N]", "", False),513 # Changing the default to True, makes the prompt change to [Y/n].514 ({"prompt": True, "default": True}, [], "[Y/n]", "", True),515 ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),516 ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),517 # False is the default's default, so it prompts with [y/N].518 ({"prompt": True, "default": False}, [], "[y/N]", "", False),519 ({"prompt": True, "default": False}, [], "[y/N]", "y", True),520 ({"prompt": True, "default": False}, [], "[y/N]", "n", False),521 # Defaulting to None, prompts with [y/n], which makes the user explicitly choose522 # between True or False.523 ({"prompt": True, "default": None}, [], "[y/n]", "y", True),524 ({"prompt": True, "default": None}, [], "[y/n]", "n", False),525 # Random string default is treated as a truthy value, so it prompts with [Y/n].526 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),527 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),528 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),529 ###530 ### Test cases with required=True explicitly enabled for the flag.531 ###532 # A required flag just raises an error unless a default is set.533 ({"required": True}, [], None, None, MissingParameter),534 ({"required": True, "default": True}, [], None, None, True),535 ({"required": True, "default": False}, [], None, None, False),536 ({"required": True, "default": None}, [], None, None, None),537 ({"required": True, "default": "on"}, [], None, None, True),538 ({"required": True, "default": "off"}, [], None, None, False),539 ({"required": True, "default": "foo"}, [], None, None, BadParameter),540 ###541 ### Explicitly passing the flag to the CLI bypass any prompt, whatever the542 ### configuration of the flag.543 ###544 # Flag allowing a prompt.545 ({"prompt": True}, ["--flag"], None, None, True),546 ({"prompt": True}, ["--no-flag"], None, None, False),547 ({"prompt": True, "default": None}, ["--flag"], None, None, True),548 ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),549 ({"prompt": True, "default": True}, ["--flag"], None, None, True),550 ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),551 ({"prompt": True, "default": False}, ["--flag"], None, None, True),552 ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),553 ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),554 ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),555 # Required flag.556 ({"required": True}, ["--flag"], None, None, True),557 ({"required": True}, ["--no-flag"], None, None, False),558 ({"required": True, "default": None}, ["--flag"], None, None, True),559 ({"required": True, "default": None}, ["--no-flag"], None, None, False),560 ({"required": True, "default": True}, ["--flag"], None, None, True),561 ({"required": True, "default": True}, ["--no-flag"], None, None, False),562 ({"required": True, "default": False}, ["--flag"], None, None, True),563 ({"required": True, "default": False}, ["--no-flag"], None, None, False),564 ({"required": True, "default": "foo"}, ["--flag"], None, None, True),565 ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),566]567568FLAG_VALUE_PROMPT_CASES = [569 ###570 ### Test cases with prompt=True explicitly enabled for the flag.571 ###572 # Prompt is allowed and the flag has no default, so it prompts.573 # But the flag_value is not set, so it defaults to a string.574 ({"prompt": True}, [], "", "", REPEAT),575 ({"prompt": True}, [], "", "y", "y"),576 ({"prompt": True}, [], "", "n", "n"),577 ({"prompt": True}, [], "", "foo", "foo"),578 # This time we provide a boolean flag_value, which makes the flag behave like a579 # boolean flag, and use the appropriate variation of [y/n].580 ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),581 ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),582 ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),583 ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),584 ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),585 ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),586 # Other flag values changes the auto-detection of the flag type.587 ({"prompt": True, "flag_value": None}, [], "", "", REPEAT),588 ({"prompt": True, "flag_value": None}, [], "", "y", "y"),589 ({"prompt": True, "flag_value": None}, [], "", "n", "n"),590 ({"prompt": True, "flag_value": "foo"}, [], "", "", REPEAT),591 ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),592 ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),593 ###594 ### Test cases with a flag_value and a default.595 ###596 # default=True597 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),598 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),599 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),600 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "", False),601 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "y", True),602 ({"prompt": True, "default": True, "flag_value": False}, [], "[y/N]", "n", False),603 # default=False604 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),605 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),606 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),607 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),608 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),609 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),610 # default=None611 (612 {"prompt": True, "default": None, "flag_value": True},613 [],614 "[y/n]",615 "",616 INVALID,617 ),618 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),619 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),620 (621 {"prompt": True, "default": None, "flag_value": False},622 [],623 "[y/n]",624 "",625 INVALID,626 ),627 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),628 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),629 # If the flag_value is None, the flag behave like a string flag, whatever the630 # default is.631 ({"prompt": True, "default": True, "flag_value": None}, [], "", "", REPEAT),632 ({"prompt": True, "default": True, "flag_value": None}, [], "", "y", "y"),633 ({"prompt": True, "default": True, "flag_value": None}, [], "", "n", "n"),634 (635 {"prompt": True, "default": False, "flag_value": None},636 [],637 "[False]",638 "",639 "False",640 ),641 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),642 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),643 ({"prompt": True, "default": None, "flag_value": None}, [], "", "", REPEAT),644 ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),645 ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),646]647648649@pytest.mark.parametrize(650 ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),651 # Boolean flag prompt cases.652 [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]653 # Non-boolean flag prompt cases.654 + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],655)656def test_flag_value_prompt(657 runner, opt_decls, opt_params, args, prompt, input, expected658):659 """Check how flag value are prompted and handled by all combinations of660 ``prompt``, ``default``, and ``flag_value`` parameters.661662 Covers concerns raised in issue https://github.com/pallets/click/issues/1992.663 """664665 @click.command()666 @click.option(opt_decls, **opt_params)667 def cli(flag):668 click.echo(repr(flag))669670 invoke_options = {"standalone_mode": False}671 if input is not None:672 assert isinstance(input, str)673 invoke_options["input"] = f"{input}\n"674675 result = runner.invoke(cli, args, **invoke_options)676677 if expected in (MissingParameter, BadParameter):678 assert isinstance(result.exception, expected)679 assert not result.output680 assert result.exit_code == 1681682 else:683 expected_output = ""684 if prompt is not None:685 # Build the expected prompt.686 assert isinstance(prompt, str)687 expected_prompt = f"Flag {prompt}: " if prompt else "Flag: "688689 # Add the user input to the expected output.690 assert isinstance(input, str)691 expected_output += f"{expected_prompt}{input}\n"692693 if expected is INVALID:694 expected_output += "Error: invalid input\n"695696 # The prompt is expected to be repeated.697 if expected in (REPEAT, INVALID):698 expected_output += expected_prompt699700 if expected not in (REPEAT, INVALID):701 expected_output += f"{expected!r}\n"702703 assert result.output == expected_output704 assert not result.stderr705 assert result.exit_code == 0 if expected not in (REPEAT, INVALID) else 1
modified:tests/test_utils.py+51 added
3 unmodified lines
4import subprocess5import sys6from collections import namedtuple7from contextlib import nullcontext8from decimal import Decimal9from fractions import Fraction10from functools import partial11from io import StringIO12from pathlib import Path13from tempfile import tempdir
3 unmodified lines
1718import click._termui_impl19import click.utils20from click._compat import WIN21from click._utils import UNSET222324def test_unset_sentinel():25 value = UNSET2627 assert value28 assert value is UNSET29 assert value == UNSET30 assert repr(value) == "Sentinel.UNSET"31 assert str(value) == "Sentinel.UNSET"32 assert bool(value) is True3334 # Try all native Python values that can be falsy or truthy.35 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing36 real_values = (37 None,38 True,39 False,40 0,41 1,42 0.0,43 1.0,44 0j,45 1j,46 Decimal(0),47 Decimal(1),48 Fraction(0, 1),49 Fraction(1, 1),50 "",51 "a",52 "UNSET",53 "Sentinel.UNSET",54 [1],55 (1),56 {1: "a"},57 set(),58 set([1]),59 frozenset(),60 frozenset([1]),61 range(0),62 range(1),63 )6465 for real_value in real_values:66 assert value != real_value67 assert value is not real_value6869 assert value not in real_values707172def test_echo(runner):73 with runner.isolation() as outstreams:74 click.echo("\N{SNOWMAN}")75 click.echo(b"\x44\x44")
647 unmodified lines
modified:CHANGES.rst+25 added-6 removed
1.. currentmodule:: click23Version 8.2.x4-------------3Version 8.3.04--------------56Unreleased6Released 2025-09-1578- show correct auto complete value for nargs option in combination with flag option :issue:`2813`8- **Improved flag option handling**: Reworked the relationship between ``flag_value``9 and ``default`` parameters for better consistency:1011 * The ``default`` parameter value is now preserved as-is and passed directly12 to CLI functions (no more unexpected transformations)13 * Exception: flag options with ``default=True`` maintain backward compatibility14 by defaulting to their ``flag_value``15 * The ``default`` parameter can now be any type (``bool``, ``None``, etc.)16 * Fixes inconsistencies reported in: :issue:`1992` :issue:`2514` :issue:`2610`17 :issue:`3024` :pr:`3030`18- Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`19 :pr:`3030`20- Show correct auto complete value for ``nargs`` option in combination with flag21 option :issue:`2813`22- Show correct auto complete value for nargs option in combination with flag option :issue:`2813`23- Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`24- Lazily import ``shutil``. :pr:`3023`25- Properly forward exception information to resources registered with26 ``click.core.Context.with_resource()``. :issue:`2447` :pr:`3058`27- Fix regression related to EOF handling in CliRunner. :issue:`2939`:pr:`2940`2829Version 8.2.230-------------3132Released 2025-07-313315- Fix reconciliation of `default`, `flag_value` and `type` parameters for34- Fix reconciliation of ``default``, ``flag_value`` and ``type`` parameters for35 flag options, as well as parsing and normalization of environment variables.36 :issue:`2952` :pr:`2956`37- Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the38 parameter ``param_hint`` that did not allow for a sequence of string where the20 underlying functino ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`39 underlying function ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`40- Use the value of ``Enum`` choices to render their default value in help41 screen. Refs :issue:`2911` :pr:`3004`42- Fix completion for the Z shell (``zsh``) for completion items containing43 colons. :issue:`2703` :pr:`2846`
1250 unmodified lines
modified:pyproject.toml+1 added-1 removed
1[project]2name = "click"3version = "8.2.2"3version = "8.3.0"4description = "Composable command line interface toolkit"5readme = "README.md"6license = "BSD-3-Clause"7license-files = ["LICENSE.txt"]
201 unmodified lines
modified:uv.lock+1 added-1 removed
137 unmodified lines
138]139140[[package]]141name = "click"142version = "8.2.2"142version = "8.3.0"143source = { editable = "." }144dependencies = [145 { name = "colorama", marker = "sys_platform == 'win32'" },146]
1076 unmodified lines