Skip to content
Myr

Differentiate absence of value and value of absence for `default` and `flag_value` arguments (#3030)

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

authored by Rowlando13 · committed by GitHub · parents d1ba34c, dc8e539 · Browse files · 10 files+1852 added−443 removed
This commit

State

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

Diff stats

10 files+1852 added−443 removed

  • tests:+1433 added−252 removed
  • other:+419 added−191 removed

10 files+1852 added−443 removed

modified:docs/options.md+29 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````{caution}339The `default` argument of options always give to the underlying function its value *as-is*.340341But for flags, the interaction between `flag_value` and `default` is a bit special.342343If a flag has a `flag_value`, setting `default` to `True` means that the flag is activated by default. Not that the value passed to the underlying function is the `True` Python value. Instead, the default value will be aligned to the `flag_value` behind the scenes.344345Which means, the in example above, this option:346347```python348@click.option('--upper', 'transformation', flag_value='upper', default=True)349```350351is equivalent to:352353```python354@click.option('--upper', 'transformation', flag_value='upper', default='upper')355```356357This was implemented to support legacy behavior, that will be removed in Click 9.0 to allow for default to take any value, including `True`.358359In the mean time, to avoid confusion, it is recommended to always set `default` to the actual default value you want to pass to the underlying function, and not use `True`, `False` or `None`. Unless that's the precise value you want to explicitly force as default.360````361362## Values from Environment Variables363364To pass in a value in from a specific environment variable use `envvar`.365
43 unmodified lines
409 - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag410 - 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 above411 - Any other value is interpreted as deactivating the flag412389.. caution::390 For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.413```{caution}414For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.415392 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.416So 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.417```418419Once 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.420421## Multiple Options from Environment Values
80 unmodified lines
added:src/click/_utils.py+25 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()1617 def __repr__(self) -> str:18 return f"{self.__class__.__name__}.{self.name}"192021UNSET = Sentinel.UNSET22"""A sentinel object used to indicate that a value is not set."""2324T_UNSET = t.Literal[UNSET] # type: ignore[valid-type]25"""Type hint for the :data:`UNSET` sentinel value."""
modified:src/click/core.py+333 added-167 removed
17 unmodified lines
18from itertools import repeat19from types import TracebackType2021from . import types22from ._utils import UNSET23from .exceptions import Abort24from .exceptions import BadParameter25from .exceptions import ClickException26from .exceptions import Exit
659 unmodified lines
686 .. versionchanged:: 8.0687 Added the ``call`` parameter.688 """689 if self.default_map is not None:689 value = self.default_map.get(name)690 value = self.default_map.get(name, UNSET)691692 if call and callable(value):693 return value()694695 return value696696 return None697 return UNSET698699 def fail(self, message: str) -> t.NoReturn:700 """Aborts the execution of the program with a specific error701 message.
492 unmodified lines
1194 parser = self.make_parser(ctx)1195 opts, args, param_order = parser.parse_args(args=args)11961197 for param in iter_params_for_processing(param_order, self.get_params(ctx)):1197 value, args = param.handle_parse_result(ctx, opts, args)1198 _, args = param.handle_parse_result(ctx, opts, args)11991200 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1201 ctx.fail(1202 ngettext(
812 unmodified lines
2015 otherwise it's skipped.2016 :param is_eager: eager values are processed before non eager ones. This2017 should not be set for arguments or it will inverse the2018 order of processing.2018 :param envvar: a string or list of strings that are environment variables2019 that should be checked.2019 :param envvar: environment variable(s) that are used to provide a default value for2020 this parameter. This can be a string or a sequence of strings. If a sequence is2021 given, only the first non-empty environment variable is used for the parameter.2022 :param shell_complete: A function that returns custom shell2023 completions. Used instead of the param's type completion if2024 given. Takes ``ctx, param, incomplete`` and must return a list2025 of :class:`~click.shell_completion.CompletionItem` or a list of
53 unmodified lines
2079 self,2080 param_decls: cabc.Sequence[str] | None = None,2081 type: types.ParamType | t.Any | None = None,2082 required: bool = False,2083 # XXX The default historically embed two concepts:2084 # - the declaration of a Parameter object carrying the default (handy to2085 # arbitrage the default value of coupled Parameters sharing the same2086 # self.name, like flag options),2087 # - and the actual value of the default.2088 # It is confusing and is the source of many issues discussed in:2089 # https://github.com/pallets/click/pull/30302090 # In the future, we might think of splitting it in two, not unlike2091 # Option.is_flag and Option.flag_value: we could have something like2092 # Parameter.is_default and Parameter.default_value.2081 default: t.Any | t.Callable[[], t.Any] | None = None,2093 default: t.Any | t.Callable[[], t.Any] | None = UNSET,2094 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,2095 nargs: int | None = None,2096 multiple: bool = False,2097 metavar: str | None = None,
40 unmodified lines
2138 f"'nargs' must be {self.type.arity} (or None) for"2139 f" type {self.type!r}, but it was {nargs}."2140 )21412130 # 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 )21632142 if required and deprecated:2143 raise ValueError(2144 f"The {self.param_type_name} '{self.human_readable_name}' "2145 "is deprecated and still required. A deprecated "
6 unmodified lines
21522153 Use :meth:`click.Context.to_info_dict` to traverse the entire2154 CLI structure.21552156 .. versionchanged:: 8.3.02157 Returns ``None`` for the :attr:`default` if it was not set.21582159 .. versionadded:: 8.02160 """2161 return {2162 "name": self.name,
3 unmodified lines
2166 "type": self.type.to_info_dict(),2167 "required": self.required,2168 "nargs": self.nargs,2169 "multiple": self.multiple,2189 "default": self.default,2170 # We explicitly hide the :attr:`UNSET` value to the user, as we choose to2171 # make it an implementation detail. And because ``to_info_dict`` has been2172 # designed for documentation purposes, we return ``None`` instead.2173 "default": self.default if self.default is not UNSET else None,2174 "envvar": self.envvar,2175 }21762177 def __repr__(self) -> str:
59 unmodified lines
2237 Added the ``call`` parameter.2238 """2239 value = ctx.lookup_default(self.name, call=False) # type: ignore22402257 if value is None:2241 if value is UNSET:2242 value = self.default22432244 if call and callable(value):2245 value = value()
5 unmodified lines
22512252 def consume_value(2253 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2254 ) -> tuple[t.Any, ParameterSource]:2271 value = opts.get(self.name) # type: ignore2272 source = ParameterSource.COMMANDLINE2255 """Returns the parameter value produced by the parser.22562274 if value is None:2275 value = self.value_from_envvar(ctx)2276 source = ParameterSource.ENVIRONMENT2257 If the parser did not produce a value from user input, the value is either2258 sourced from the environment variable, the default map, or the parameter's2259 default value. In that order of precedence.22602278 if value is None:2279 value = ctx.lookup_default(self.name) # type: ignore2280 source = ParameterSource.DEFAULT_MAP2261 If no value is found, an internal sentinel value is returned.22622282 if value is None:2283 value = self.get_default(ctx)2284 source = ParameterSource.DEFAULT2263 :meta private:2264 """2265 # Collect from the parse the value passed by the user to the CLI.2266 value = opts.get(self.name, UNSET) # type: ignore2267 # If the value is set, it means it was sourced from the command line by the2268 # parser, otherwise it left unset by default.2269 source = (2270 ParameterSource.COMMANDLINE2271 if value is not UNSET2272 else ParameterSource.DEFAULT2273 )22742275 if value is UNSET:2276 envvar_value = self.value_from_envvar(ctx)2277 if envvar_value is not None:2278 value = envvar_value2279 source = ParameterSource.ENVIRONMENT22802281 if value is UNSET:2282 default_map_value = ctx.lookup_default(self.name) # type: ignore2283 if default_map_value is not UNSET:2284 value = default_map_value2285 source = ParameterSource.DEFAULT_MAP22862287 if value is UNSET:2288 default_value = self.get_default(ctx)2289 if default_value is not UNSET:2290 value = default_value2291 source = ParameterSource.DEFAULT22922293 return value, source22942295 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2289 """Convert and validate a value against the option's2296 """Convert and validate a value against the parameter's2297 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2298 """2292 if value is None:2293 return () if self.multiple or self.nargs == -1 else None2299 if value in (None, UNSET):2300 if self.multiple or self.nargs == -1:2301 return ()2302 else:2303 return value23042305 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2306 try:2307 return _check_iter(value)
4 unmodified lines
2312 raise BadParameter(2313 _("Value must be an iterable."), ctx=ctx, param=self2314 ) from None23152316 # Define the conversion function based on nargs and type.23172318 if self.nargs == 1 or self.type.is_composite:23192320 def convert(value: t.Any) -> t.Any:2321 return self.type(value, param=self, ctx=ctx)
26 unmodified lines
23482349 return convert(value)23502351 def value_is_missing(self, value: t.Any) -> bool:2352 """A value is considered missing if:23532354 - it is :attr:`UNSET`,2355 - or if it is an empty sequence while the parameter is suppose to have2356 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is2357 set).23582359 :meta private:2360 """2340 if value is None:2361 if value is UNSET:2362 return True23632364 if (self.nargs != 1 or self.multiple) and value == ():2365 return True23662367 return False23682369 def process_value(self, ctx: Context, value: t.Any) -> t.Any:2370 """Process the value of this parameter:23712372 1. Type cast the value using :meth:`type_cast_value`.2373 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise2374 :exc:`MissingParameter` if it is required.2375 3. If a :attr:`callback` is set, call it to have the value replaced by the2376 result of the callback. If the value was not set, the callback receive2377 ``None``. This keep the legacy behavior as it was before the introduction of2378 the :attr:`UNSET` sentinel.23792380 :meta private:2381 """2382 value = self.type_cast_value(ctx, value)23832384 if self.required and self.value_is_missing(value):2385 raise MissingParameter(ctx=ctx, param=self)23862387 if self.callback is not None:2388 # Legacy case: UNSET is not exposed directly to the callback, but converted2389 # to None.2390 if value is UNSET:2391 value = None2392 value = self.callback(ctx, self, value)23932394 return value23952396 def resolve_envvar_value(self, ctx: Context) -> str | None:2360 if self.envvar is None:2397 """Returns the value found in the environment variable(s) attached to this2398 parameter.23992400 Environment variables values are `always returned as strings2401 <https://docs.python.org/3/library/os.html#os.environ>`_.24022403 This method returns ``None`` if:24042405 - the :attr:`envvar` property is not set on the :class:`Parameter`,2406 - the environment variable is not found in the environment,2407 - the variable is found in the environment but its value is empty (i.e. the2408 environment variable is present but has an empty string).24092410 If :attr:`envvar` is setup with multiple environment variables,2411 then only the first non-empty value is returned.24122413 .. caution::24142415 The raw value extracted from the environment is not normalized and is2416 returned as-is. Any normalization or reconciliation is performed later by2417 the :class:`Parameter`'s :attr:`type`.24182419 :meta private:2420 """2421 if not self.envvar:2422 return None24232424 if isinstance(self.envvar, str):2425 rv = os.environ.get(self.envvar)
3 unmodified lines
2429 else:2430 for envvar in self.envvar:2431 rv = os.environ.get(envvar)24322433 # Return the first non-empty value of the list of environment variables.2434 if rv:2435 return rv2436 # Else, absence of value is interpreted as an environment variable that2437 # is not set, so proceed to the next one.24382439 return None24402377 def value_from_envvar(self, ctx: Context) -> t.Any | None:2378 rv: t.Any | None = self.resolve_envvar_value(ctx)2441 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:2442 """Process the raw environment variable string for this parameter.24432444 Returns the string as-is or splits it into a sequence of strings if the2445 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set2446 to a value other than ``1``).24472448 :meta private:2449 """2450 rv = self.resolve_envvar_value(ctx)24512452 if rv is not None and self.nargs != 1:2381 rv = self.type.split_envvar_value(rv)2453 return self.type.split_envvar_value(rv)24542455 return rv24562457 def handle_parse_result(2458 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]2459 ) -> tuple[t.Any, list[str]]:2460 """Process the value produced by the parser from user input.24612462 Always process the value through the Parameter's :attr:`type`, wherever it2463 comes from.24642465 If the parameter is deprecated, this method warn the user about it. But only if2466 the value has been explicitly set by the user (and as such, is not coming from2467 a default).24682469 :meta private:2470 """2471 with augment_usage_errors(ctx, param=self):2472 value, source = self.consume_value(ctx, opts)24732474 ctx.set_parameter_source(self.name, source) # type: ignore24752476 # Display a deprecation warning if necessary.2477 if (2478 self.deprecated2393 and value is not None2394 and source2395 not in (2396 ParameterSource.DEFAULT,2397 ParameterSource.DEFAULT_MAP,2398 )2479 and value is not UNSET2480 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)2481 ):2482 extra_message = (2483 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2484 )
6 unmodified lines
2491 extra_message=extra_message,2492 )2493 echo(style(message, fg="red"), err=True)24942413 ctx.set_parameter_source(self.name, source) # type: ignore24142495 # Process the value through the parameter's type.2496 try:2497 value = self.process_value(ctx, value)2498 except Exception:2499 if not ctx.resilient_parsing:2500 raise2501 # In resilient parsing mode, we do not want to fail the command if the2502 # value is incompatible with the parameter type, so we reset the value2503 # to UNSET, which will be interpreted as a missing value.2504 value = UNSET25052421 value = None2506 # Add parameter's value to the context.2507 if (2508 self.expose_value2509 # We skip adding the value if it was previously set by another parameter2510 # targeting the same variable name. This prevents parameters competing for2511 # the same name to override each other.2512 and self.name not in ctx.params2513 ):2514 # Click is logically enforcing that the name is None if the parameter is2515 # not to be exposed. We still assert it here to please the type checker.2516 assert self.name is not None, (2517 f"{self!r} parameter's name should not be None when exposing value."2518 )2519 # Normalize UNSET values to None, as we're about to pass them to the2520 # command function and move them to the pure-Python realm of user-written2521 # code.2522 ctx.params[self.name] = value if value is not UNSET else None25232423 if self.expose_value:2424 ctx.params[self.name] = value # type: ignore24252524 return value, args25252526 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:2527 pass
77 unmodified lines
2605 :param help: the help string.2606 :param hidden: hide this option from help outputs.2607 :param attrs: Other command arguments described in :class:`Parameter`.26082609 .. caution::2610 Flags specifying a ``flag_value`` and whose ``default=True`` will have2611 their ``default`` aligned to the ``flag_value``.26122613 This means there is no way to setup a flag whose default ``True`` and2614 whose ``flag_value`` is something else than ``True``.26152616 This is to support legacy behavior that will be removed in Click 9.0.26172618 .. versionchanged:: 8.22619 ``envvar`` used with ``flag_value`` will always use the ``flag_value``,2620 previously it would use the value of the environment variable.2621
23 unmodified lines
2645 confirmation_prompt: bool | str = False,2646 prompt_required: bool = True,2647 hide_input: bool = False,2648 is_flag: bool | None = None,2542 flag_value: t.Any | None = None,2649 flag_value: t.Any = UNSET,2650 multiple: bool = False,2651 count: bool = False,2652 allow_from_autoenv: bool = True,2653 type: types.ParamType | t.Any | None = None,
34 unmodified lines
2688 self.prompt_required = prompt_required2689 self.hide_input = hide_input2690 self.hidden = hidden26912585 # If prompt is enabled but not required, then the option can be2586 # used as a flag to indicate using prompt or flag_value.2692 # The _flag_needs_value property tells the parser that this option is a flag2693 # that cannot be used standalone and needs a value. With this information, the2694 # parser can determine whether to consider the next user-provided argument in2695 # the CLI as a value for this flag or as a new option.2696 # If prompt is enabled but not required, then it opens the possibility for the2697 # option to gets its value from the user.2698 self._flag_needs_value = self.prompt is not None and not self.prompt_required26992700 # Auto-detect if this is a flag or not.2701 if is_flag is None:2702 # Implicitly a flag because flag_value was set.2591 if flag_value is not None:2703 if flag_value is not UNSET:2704 is_flag = True2705 # Not a flag, but when used as a flag it shows a prompt.2706 elif self._flag_needs_value:2707 is_flag = False2596 # Implicitly a flag because flag options were given.2708 # Implicitly a flag because secondary options names were given.2709 elif self.secondary_opts:2710 is_flag = True2711 # The option is explicitly not a flag. But we do not know yet if it needs a2712 # value or not. So we look at the default value to determine it.2713 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 None2714 self._flag_needs_value = self.default is UNSET27152604 self.default: t.Any | t.Callable[[], t.Any]26052716 if is_flag:2717 # 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:2718 if self.default is UNSET and not self.required and not self.prompt:2719 if multiple:2720 self.default = ()27212722 # Auto-detect the type of the flag based on the flag_value.2723 if type is None:2724 # A flag without a flag_value is a boolean flag.2725 if flag_value is UNSET:2726 self.type = types.BoolParamType()2727 # If the flag value is a boolean, use BoolParamType.2728 elif isinstance(flag_value, bool):2729 self.type = types.BoolParamType()2730 # Otherwise, guess the type from the flag value.2731 else:2612 self.default = False2732 self.type = types.convert_type(None, flag_value)27332614 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)26252734 self.is_flag: bool = bool(is_flag)2735 self.is_bool_flag: bool = bool(2736 is_flag and isinstance(self.type, types.BoolParamType)2737 )2738 self.flag_value: t.Any = flag_value27392740 # Set boolean flag default to False if unset and not required.2741 if self.is_bool_flag:2742 if self.default is UNSET and not self.required:2743 self.default = False27442745 # XXX Support the legacy case of aligning the default value with the flag_value2746 # for flags whose default is explicitly set to True. As long as we have this2747 # condition, there is no way a flag can have a default set to True, unless its2748 # flag_value itself is set to True. Refs:2749 # https://github.com/pallets/click/issues/3024#issuecomment-31461994612750 # https://github.com/pallets/click/pull/3030/files#r22889364932751 if self.default is True and self.flag_value is not UNSET:2752 # This message is a convoluted way to explain that if you want things2753 # to be equal, make them equal.2754 # warnings.warn(2755 # "A flag's `default` value will no longer be aligned with its "2756 # "`flag_value` if `default=True` in Click 9.0. If you want the flag "2757 # "to get the same `default` as its `flag_value`, update the option "2758 # "to make its `default` parameter equal to its `flag_value`.",2759 # DeprecationWarning,2760 # stacklevel=2,2761 # )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 auto-detected as a3074 # boolean flag, is allow to prompt but still declare a non-boolean default.3075 # So with this casting, we aligns the default value to the prompt behavior.3076 # The prompt is going to default to [Y/n]), and so not entering a value for3077 # input is expected to make the option takes True as the default.3078 # Refs: https://github.com/pallets/click/pull/3030#discussion_r22891802493079 else:3080 default = bool(default)3081 return confirm(self.prompt, default)30823083 # If show_default is set to True/False, provide this to `prompt` as well. For3084 # non-bool values of `show_default`, we use `prompt`'s default behavior
2 unmodified lines
3087 prompt_kwargs["show_default"] = self.show_default30883089 return prompt(3090 self.prompt,2960 default=default,3091 # Use ``None`` to inform the prompt() function to reiterate until a valid3092 # value is provided by the user if we have no default.3093 default=None if default is UNSET else default,3094 type=self.type,3095 hide_input=self.hide_input,3096 show_choices=self.show_choices,3097 confirmation_prompt=self.confirmation_prompt,
1 unmodified line
3099 **prompt_kwargs,3100 )31013102 def resolve_envvar_value(self, ctx: Context) -> str | None:2970 """Find which environment variable to read for this option and return2971 its value.3103 """:class:`Option` resolves its environment variable the same way as3104 :func:`Parameter.resolve_envvar_value`, but it also supports3105 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from3106 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`3107 to build dynamiccaly the environment variable name using the3108 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.31092973 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.3110 :meta private:3111 """3112 rv = super().resolve_envvar_value(ctx)31133114 if rv is not None:
11 unmodified lines
3126 return rv31273128 return None31293000 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)3130 def value_from_envvar(self, ctx: Context) -> t.Any:3131 """For :class:`Option`, this method processes the raw environment variable3132 string the same way as :func:`Parameter.value_from_envvar` does.31333134 But in the case of non-boolean flags, the value is analyzed to determine if the3135 flag is activated or not, and returns a boolean of its activation, or the3136 :attr:`flag_value` if the latter is set.31373138 This method also takes care of repeated options (i.e. options with3139 :attr:`multiple` set to ``True``).31403141 :meta private:3142 """3143 rv = self.resolve_envvar_value(ctx)31443145 # Absent environment variable or an empty string is interpreted as unset.3146 if rv is None:3147 return None31483149 # 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 is3150 # flag, its envvar value still needs to be analyzed to determine if the flag is3151 # activated or not.3152 if self.is_flag and not self.is_bool_flag:3153 # If the flag_value is set and match the envvar value, return it3154 # directly.3013 if self.flag_value is not None and rv == self.flag_value:3155 if self.flag_value is not UNSET and rv == self.flag_value:3156 return self.flag_value3157 # Analyze the envvar value as a boolean to know if the flag is3158 # activated or not.3159 return types.BoolParamType.str_to_bool(rv)
11 unmodified lines
31713172 def consume_value(3173 self, ctx: Context, opts: cabc.Mapping[str, Parameter]3174 ) -> tuple[t.Any, ParameterSource]:3175 """For :class:`Option`, the value can be collected from an interactive prompt3176 if the option is a flag that needs a value (and the :attr:`prompt` property is3177 set).31783179 Additionally, this method handles flag option that are activated without a3180 value, in which case the :attr:`flag_value` is returned.31813182 :meta private:3183 """3184 value, source = super().consume_value(ctx, opts)31853035 # 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.3186 # The parser will emit a sentinel value if the option is allowed to as a flag3187 # without a value.3188 if value is _flag_needs_value:3189 # If the option allows for a prompt, we start an interaction with the user.3190 if self.prompt is not None and not ctx.resilient_parsing:3191 value = self.prompt_for_value(ctx)3192 source = ParameterSource.PROMPT3193 # Else the flag takes its flag_value as value.3194 else:3195 value = self.flag_value3196 source = ParameterSource.COMMANDLINE31973046 # A flag which is activated and has a flag_value set, should returns3047 # the latter, unless the value comes from the explicitly sets default.3198 # A flag which is activated always returns the flag value, unless the value3199 # comes from the explicitly sets default.3200 elif (3201 self.is_flag3202 and value is True3203 and not self.is_bool_flag3052 and self.flag_value is not None3053 and source is not ParameterSource.DEFAULT3204 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3205 ):3206 value = self.flag_value32073208 # Re-interpret a multiple option which has been sent as-is by the parser.3209 # Here we replace each occurrence of value-less flags (marked by the3210 # _flag_needs_value sentinel) with the flag_value.3211 elif (3212 self.multiple3059 and value is not None3213 and value is not UNSET3214 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3215 and any(v is _flag_needs_value for v in value)3216 ):3217 value = [self.flag_value if v is _flag_needs_value else v for v in value]3218 source = ParameterSource.COMMANDLINE32193065 # The value wasn't set, or used the param's default, prompt if3066 # prompting is enabled.3220 # The value wasn't set, or used the param's default, prompt for one to the user3221 # if prompting is enabled.3222 elif (3068 source in {None, ParameterSource.DEFAULT}3223 (3224 value is UNSET3225 or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3226 )3227 and self.prompt is not None3228 and (self.required or self.prompt_required)3229 and not ctx.resilient_parsing3230 ):
1 unmodified line
3232 source = ParameterSource.PROMPT32333234 return value, source32353236 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:3237 if self.is_flag and not self.required:3238 if value is UNSET:3239 if self.is_bool_flag:3240 # If the flag is a boolean flag, we return False if it is not set.3241 value = False3242 return super().type_cast_value(ctx, value)324332443245class Argument(Parameter):3246 """Arguments are positional parameters to a command. They generally3247 provide fewer features than options but can have infinite ``nargs``3248 and are required by default.
8 unmodified lines
3257 param_decls: cabc.Sequence[str],3258 required: bool | None = None,3259 **attrs: t.Any,3260 ) -> None:3261 # Auto-detect the requirement status of the argument if not explicitly set.3262 if required is None:3096 if attrs.get("default") is not None:3097 required = False3098 else:3263 # The argument gets automatically required if it has no explicit default3264 # value set and is setup to match at least one value.3265 if attrs.get("default", UNSET) is UNSET:3266 required = attrs.get("nargs", 1) > 03267 # If the argument has a default value, it is not required.3268 else:3269 required = False32703271 if "multiple" in attrs:3272 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")32733274 super().__init__(param_decls, required=required, **attrs)32753106 if __debug__:3107 if self.default is not None and self.nargs == -1:3108 raise TypeError("'default' is not supported for nargs=-1.")31093276 @property3277 def human_readable_name(self) -> str:3278 if self.metavar is not None:3279 return self.metavar
65 unmodified lines
modified:src/click/parser.py+17 added-16 removed
28 unmodified lines
29from collections import deque30from gettext import gettext as _31from gettext import ngettext3233from ._utils import UNSET34from .exceptions import BadArgumentUsage35from .exceptions import BadOptionUsage36from .exceptions import NoSuchOption37from .exceptions import UsageError3839if t.TYPE_CHECKING:40 from ._utils import T_UNSET41 from .core import Argument as CoreArgument42 from .core import Context43 from .core import Option as CoreOption44 from .core import Parameter as CoreParameter
15 unmodified lines
6061 The nargs specification is the number of arguments that should be consumed62 or `-1` to indicate that this position should eat up all the remainders.6362 Missing items are filled with `None`.64 Missing items are filled with ``UNSET``.65 """66 args = deque(args)67 nargs_spec = deque(nargs_spec)66 rv: list[str | tuple[str | None, ...] | None] = []68 rv: list[str | tuple[str | T_UNSET, ...] | T_UNSET] = []69 spos: int | None = None7069 def _fetch(c: deque[V]) -> V | None:71 def _fetch(c: deque[V]) -> V | T_UNSET:72 try:73 if spos is None:74 return c.popleft()75 else:76 return c.pop()77 except IndexError:76 return None78 return UNSET7980 while nargs_spec:81 nargs = _fetch(nargs_spec)8283 if nargs is None:84 continue8586 if nargs == 1:85 rv.append(_fetch(args))87 rv.append(_fetch(args)) # type: ignore[arg-type]88 elif nargs > 1:89 x = [_fetch(args) for _ in range(nargs)]9091 # If we're reversed, we're pulling in the arguments in reverse,
6 unmodified lines
98 if spos is not None:99 raise TypeError("Cannot have two nargs < 0")100101 spos = len(rv)100 rv.append(None)102 rv.append(UNSET)103104 # spos is the position of the wildcard (star). If it's not `None`,105 # we fill it with the remainder.106 if spos is not None:
81 unmodified lines
188 self.obj = obj189190 def process(191 self,190 value: str | cabc.Sequence[str | None] | None,192 value: str | cabc.Sequence[str | None] | None | T_UNSET,193 state: _ParsingState,194 ) -> None:195 if self.nargs > 1:194 assert value is not None195 holes = sum(1 for x in value if x is None)196 assert isinstance(value, cabc.Sequence)197 holes = sum(1 for x in value if x is UNSET)198 if holes == len(value):197 value = None199 value = UNSET200 elif holes != 0:201 raise BadArgumentUsage(202 _("Argument {name!r} takes {nargs} values.").format(203 name=self.dest, nargs=self.nargs204 )205 )206205 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 = None207 # We failed to collect any argument value so we consider the argument as unset.208 if value == ():209 value = UNSET210211 state.opts[self.dest] = value # type: ignore212 state.order.append(self.obj)213
170 unmodified lines
384 opt, _("Option {name!r} does not take a value.").format(name=opt)385 )386387 else:387 value = None388 value = UNSET389390 option.process(value, state)391392 def _match_short_opt(self, arg: str, state: _ParsingState) -> None:
21 unmodified lines
414415 value = self._get_value_from_state(opt, option, state)416417 else:417 value = None418 value = UNSET419420 option.process(value, state)421422 if stop:
111 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 # Legacy case: if default=True and flag_value is set, The value returned is the306 # flag_value, not default 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_options.py+937 added-213 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 # Legacy case: UNSET is not exposed directly to the callback, but converted to1482 # None.1483 (UNSET, [], None),1484 # Legacy case: if default=True and flag_value is set, The value returned is the1485 # flag_value, not default 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"),
75 unmodified lines
1718 def cli_with_choices(g):1719 pass17201721 @click.command()1368 @click.option(1369 "-g",1370 type=click.Choice(choices),1371 show_choices=False,1372 )1722 @click.option("-g", type=click.Choice(choices), show_choices=False)1723 def cli_without_choices(g):1724 pass17251726 result = runner.invoke(cli_with_choices, ["--help"])
77 unmodified lines
1804 with pytest.warns(UserWarning):1805 runner.invoke(cli, [])180618071808OBJECT_SENTINEL = object()1809"""An object-based sentinel value."""181018111812class EnumSentinel(enum.Enum):1813 FALSY_SENTINEL = object()18141815 def __bool__(self) -> Literal[False]:1816 """Force the sentinel to be falsy to make sure it is not caught by Click1817 internal implementation.18181819 Falsy sentinels have been discussed in:1820 https://github.com/pallets/click/pull/3030#pullrequestreview-31066047951821 https://github.com/pallets/click/pull/3030#pullrequestreview-31084715521822 """1823 return False182418251826# Any kind of sentinel value is recognized by Click as a valid flag value.1827@pytest.mark.parametrize("sentinel", (OBJECT_SENTINEL, EnumSentinel.FALSY_SENTINEL))1828@pytest.mark.parametrize(1459 ("multiple", "nargs", "default", "expected_message"),1829 ("args", "expected"),1830 (1831 # Option default to None.1832 ([], None),1833 # Config has no default value, and no flag value, so it requires an argument.1834 (1835 ["--config"],1836 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1837 ),1838 (1839 ["--no-config", "--config"],1840 re.compile(re.escape("Error: Option '--config' requires an argument.\n")),1841 ),1842 # Passing --no-config defaults to the sentinel value because of the flag_value,1843 # and then the custom type receives that sentinel and returns a message.1844 (["--no-config"], "No configuration file provided."),1845 # Passing --config with an argument returns the file path.1846 (["--config", "foo.conf"], "foo.conf"),1847 # An argument is not allowed for --no-config, so it raises an error.1848 (1849 ["--no-config", "foo.conf"],1850 re.compile(1851 r"Usage: main \[OPTIONS\]\n"1852 r"Try 'main --help' for help.\n"1853 r"\n"1854 r"Error: Got unexpected extra argument (.+)\n"1855 ),1856 ),1857 # Passing --config with an argument that does not exist raises an error.1858 (1859 ["--config", "random-file.conf"],1860 re.compile(1861 r"Usage: main \[OPTIONS\]\n"1862 r"Try 'main --help' for help.\n"1863 r"\n"1864 r"Error: Invalid value for '-c' / '--config': "1865 r"File 'random-file.conf' does not exist.\n"1866 ),1867 ),1868 (1869 ["--config", "--no-config"],1870 re.compile(1871 r"Usage: main \[OPTIONS\]\n"1872 r"Try 'main --help' for help.\n"1873 r"\n"1874 r"Error: Invalid value for '-c' / '--config': "1875 r"File '--no-config' does not exist.\n"1876 ),1877 ),1878 (1879 ["--config", "--no-config", "foo.conf"],1880 re.compile(1881 r"Usage: main \[OPTIONS\]\n"1882 r"Try 'main --help' for help.\n"1883 r"\n"1884 r"Error: Invalid value for '-c' / '--config': "1885 r"File '--no-config' does not exist.\n"1886 ),1887 ),1888 # --config is passed last and overrides the --no-config option.1889 (["--no-config", "--config", "foo.conf"], "foo.conf"),1890 ),1891)1892def test_dual_options_custom_type_sentinel_flag_value(runner, sentinel, args, expected):1893 """Check that an object-based sentinel, used as a flag value, is returned as-is1894 to a custom type that is shared by two options, competing for the same variable1895 name.18961897 A reproduction of1898 https://github.com/pallets/click/issues/3024#issuecomment-31465113561899 """19001901 class ConfigParamType(click.ParamType):1902 """A custom type that accepts a file path or a sentinel value."""19031904 def convert(self, value, param, ctx):1905 if value is sentinel:1906 return "No configuration file provided."1907 else:1908 return click.Path(exists=True, dir_okay=False).convert(1909 value, param, ctx1910 )19111912 @click.command()1913 @click.option("-c", "--config", type=ConfigParamType())1914 @click.option("--no-config", "config", flag_value=sentinel, type=ConfigParamType())1915 def main(config):1916 click.echo(repr(config), nl=False)19171918 with tempfile.NamedTemporaryFile(mode="w") as named_tempfile:1919 if "foo.conf" in args:1920 named_tempfile.write("Blah blah")1921 named_tempfile.flush()1922 args = [named_tempfile.name if a == "foo.conf" else a for a in args]19231924 result = runner.invoke(main, args)19251926 if isinstance(expected, re.Pattern):1927 assert re.match(expected, result.output)1928 else:1929 assert result.output == repr(1930 named_tempfile.name if expected == "foo.conf" else expected1931 )193219331934class EngineType(enum.Enum):1935 OSS = enum.auto()1936 PRO = enum.auto()1937 MAX = enum.auto()193819391940class Class1:1941 pass194219431944class Class2:1945 pass194619471948@pytest.mark.parametrize(1949 ("opt_params", "args", "expected"),1950 [1951 # Check that the flag value is returned as-is when the option is passed, and1952 # not normalized to a boolean, even if it is explicitly declared as a flag.1953 ({"type": EngineType, "flag_value": None}, ["--pro"], None),1954 (1462 False, # multiple1463 2, # nargs1464 42, # default (not a list)1465 "'default' must be a list when 'nargs' != 1.",1955 {"type": EngineType, "is_flag": True, "flag_value": None},1956 ["--pro"],1957 None,1958 ),1959 ({"type": EngineType, "flag_value": EngineType.OSS}, ["--pro"], EngineType.OSS),1960 (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.",1961 {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},1962 ["--pro"],1963 EngineType.OSS,1964 ),1965 (1966 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},1967 ["--pro"],1968 EngineType.OSS,1969 ),1970 # The default value is returned as-is when the option is not passed, whatever1971 # the flag value.1972 ({"type": EngineType, "flag_value": None}, [], None),1973 ({"type": EngineType, "is_flag": True, "flag_value": None}, [], None),1974 ({"type": EngineType, "flag_value": EngineType.OSS}, [], None),1975 (1976 {"type": EngineType, "is_flag": True, "flag_value": EngineType.OSS},1977 [],1978 None,1979 ),1980 (1981 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},1982 [],1983 EngineType.OSS,1984 ),1985 # The option has not enough parameters to be detected as flag-like, so it1986 # requires an argument.1987 (1988 {"type": EngineType, "default": EngineType.OSS},1989 ["--pro"],1990 re.compile(re.escape("Error: Option '--pro' requires an argument.\n")),1991 ),1992 ({"type": EngineType, "default": EngineType.OSS}, [], EngineType.OSS),1993 # If a flag value is set, it is returned instead of the default value.1994 (1995 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},1996 ["--pro"],1997 EngineType.OSS,1998 ),1999 (2000 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},2001 [],2002 EngineType.OSS,2003 ),2004 # Type is not specified and default to string, so the default value is2005 # returned as a string, even if it is a boolean. Also, defaults to the2006 # flag_value instead of the default value to support legacy behavior.2007 ({"flag_value": "1", "default": True}, [], "1"),2008 ({"flag_value": "1", "default": 42}, [], "42"),2009 ({"flag_value": EngineType.OSS, "default": True}, [], "EngineType.OSS"),2010 ({"flag_value": EngineType.OSS, "default": 42}, [], "42"),2011 # See: the result is the same if we force the type to be str.2012 ({"type": str, "flag_value": 1, "default": True}, [], "1"),2013 ({"type": str, "flag_value": 1, "default": 42}, [], "42"),2014 ({"type": str, "flag_value": "1", "default": True}, [], "1"),2015 ({"type": str, "flag_value": "1", "default": 42}, [], "42"),2016 (2017 {"type": str, "flag_value": EngineType.OSS, "default": True},2018 [],2019 "EngineType.OSS",2020 ),2021 ({"type": str, "flag_value": EngineType.OSS, "default": 42}, [], "42"),2022 # But having the flag value set to integer is automaticcally recognized by2023 # Click.2024 ({"flag_value": 1, "default": True}, [], 1),2025 ({"flag_value": 1, "default": 42}, [], 42),2026 ({"type": int, "flag_value": 1, "default": True}, [], 1),2027 ({"type": int, "flag_value": 1, "default": 42}, [], 42),2028 ({"type": int, "flag_value": "1", "default": True}, [], 1),2029 ({"type": int, "flag_value": "1", "default": 42}, [], 42),2030 ],2031)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 )2032def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):2033 """Test how the type and flag_value influence the returned value.20342035 Cover cases reported in:2036 https://github.com/pallets/click/issues/3024#issuecomment-31464807142037 https://github.com/pallets/click/issues/2012#issuecomment-8924370602038 """20392040 @click.command()2041 @click.option("--pro", **opt_params)2042 def scan(pro):2043 click.echo(repr(pro), nl=False)20442045 result = runner.invoke(scan, args)2046 if isinstance(expected, re.Pattern):2047 assert re.match(expected, result.output)2048 else:2049 assert result.output == repr(expected)205020512052@pytest.mark.parametrize(2053 ("opt1_params", "opt2_params", "args", "expected"),2054 [2055 # Dual options sharing the same variable name, are not competitive, and the2056 # flag value is returned as-is. Especially when the type is force to be2057 # unprocessed.2058 (2059 {"flag_value": EngineType.OSS, "type": UNPROCESSED},2060 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2061 [],2062 None,2063 ),2064 (2065 {"flag_value": EngineType.OSS, "type": UNPROCESSED},2066 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2067 ["--opt1"],2068 EngineType.OSS,2069 ),2070 (2071 {"flag_value": EngineType.OSS, "type": UNPROCESSED},2072 {"flag_value": EngineType.PRO, "type": UNPROCESSED},2073 ["--opt2"],2074 EngineType.PRO,2075 ),2076 # Check that passing exotic flag values like classes is supported, but are2077 # rendered to strings when the type is not specified.2078 (2079 {"flag_value": Class1, "default": True},2080 {"flag_value": Class2},2081 [],2082 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2083 ),2084 (2085 {"flag_value": Class1, "default": True},2086 {"flag_value": Class2},2087 ["--opt1"],2088 "<class 'test_options.Class1'>",2089 ),2090 (2091 {"flag_value": Class1, "default": True},2092 {"flag_value": Class2},2093 ["--opt2"],2094 "<class 'test_options.Class2'>",2095 ),2096 # Even the default is processed as a string.2097 ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),2098 ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),2099 # To get the classes as-is, we need to specify the type as UNPROCESSED.2100 (2101 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2102 {"flag_value": Class2, "type": UNPROCESSED},2103 [],2104 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2105 ),2106 (2107 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2108 {"flag_value": Class2, "type": UNPROCESSED},2109 ["--opt1"],2110 Class1,2111 ),2112 (2113 {"flag_value": Class1, "type": UNPROCESSED, "default": True},2114 {"flag_value": Class2, "type": UNPROCESSED},2115 ["--opt2"],2116 Class2,2117 ),2118 # Setting the default to a class, an instance of the class is returned instead2119 # of the class itself, because the default is allowed to be callable (and2120 # consummd). And this happens whatever the type is.2121 (2122 {"flag_value": Class1, "default": Class1},2123 {"flag_value": Class2},2124 [],2125 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),2126 ),2127 (2128 {"flag_value": Class1, "default": Class2},2129 {"flag_value": Class2},2130 [],2131 re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),2132 ),2133 (2134 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},2135 {"flag_value": Class2, "type": UNPROCESSED},2136 [],2137 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),2138 ),2139 (2140 {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},2141 {"flag_value": Class2, "type": UNPROCESSED},2142 [],2143 re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),2144 ),2145 # Having the flag value set to integer is automaticcally recognized by Click.2146 (2147 {"flag_value": 1, "default": True},2148 {"flag_value": "1"},2149 [],2150 1,2151 ),2152 (2153 {"flag_value": 1, "type": int, "default": True},2154 {"flag_value": "1", "type": int},2155 [],2156 1,2157 ),2158 ],2159)2160def test_custom_type_flag_value_dual_options(2161 runner, opt1_params, opt2_params, args, expected2162):2163 """Test how flag values are processed with dual options competing for the same2164 variable name.21652166 Reproduce issues reported in:2167 https://github.com/pallets/click/issues/3024#issuecomment-31465085362168 https://github.com/pallets/click/issues/2012#issue-9464710492169 https://github.com/pallets/click/issues/2012#issuecomment-8924370602170 """21712172 @click.command()2173 @click.option("--opt1", "dual_option", **opt1_params)2174 @click.option("--opt2", "dual_option", **opt2_params)2175 def cli(dual_option):2176 click.echo(repr(dual_option), nl=False)21772178 result = runner.invoke(cli, args)2179 if isinstance(expected, re.Pattern):2180 assert re.match(expected, result.output)2181 else:2182 assert result.output == repr(expected)218321842185def test_custom_type_frozenset_flag_value(runner):2186 """Check that frozenset is correctly handled as a type, a flag value and a default.21872188 Reproduces https://github.com/pallets/click/issues/26102189 """21902191 @click.command()2192 @click.option(2193 "--without-scm-ignore-files",2194 "scm_ignore_files",2195 is_flag=True,2196 type=frozenset,2197 flag_value=frozenset(),2198 default=frozenset(["git"]),2199 )2200 def rcli(scm_ignore_files):2201 click.echo(repr(scm_ignore_files), nl=False)22022203 result = runner.invoke(rcli)2204 assert result.stdout == "frozenset({'git'})"2205 assert result.exit_code == 022062207 result = runner.invoke(rcli, ["--without-scm-ignore-files"])2208 assert result.stdout == "frozenset()"2209 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+15 added-4 removed
1.. currentmodule:: click23Version 8.2.x3Version 8.3.x4-------------56Unreleased77- Rework relationship between ``flag_value`` and ``default``: the value given to8 ``default`` is now left untouched, and keep the value it receive. So9 ``default=<desired_value>`` is respected and ``<desired_value>`` is passed on as-is10 to the CLI function. With the exception of flag options, where setting11 ``default=True`` maintain the legacy behavior of defaulting to the ``flag_value``.12 This allow ``default`` to be of any type, including ``bool`` or ``None``, fixing13 inconsistencies reported in: :issue:`1992` :issue:`2012` :issue:`2514`14 :issue:`2610` :issue:`3024` :pr:`3030`15- Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`16 :pr:`3030`17- Show correct auto complete value for ``nargs`` option in combination with flag18 option :issue:`2813`19- Show correct auto complete value for nargs option in combination with flag option :issue:`2813`20- Fix handling of quoted and escaped parameters in Fish autocompletion. :issue:`2995` :pr:`3013`21- Lazily import ``shutil``. :pr:`3023`22
1 unmodified line
24-------------2526Released 2025-07-312717- Fix reconciliation of `default`, `flag_value` and `type` parameters for28- Fix reconciliation of ``default``, ``flag_value`` and ``type`` parameters for29 flag options, as well as parsing and normalization of environment variables.30 :issue:`2952` :pr:`2956`31- Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the32 parameter ``param_hint`` that did not allow for a sequence of string where the22 underlying functino ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`33 underlying function ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`34- Use the value of ``Enum`` choices to render their default value in help35 screen. Refs :issue:`2911` :pr:`3004`36- Fix completion for the Z shell (``zsh``) for completion items containing37 colons. :issue:`2703` :pr:`2846`
1250 unmodified lines