Skip to content
Myr

Differentiate absence of value and value of absence for `default` and `flag_value`

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

authored by Kevin Deldycke · committed by Kevin Deldycke · parent 1f40020 · Browse files · 11 files+1486 added−492 removed
This commit

State

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

Trailers

  • Closes: #1992 #2012 #2514 #2610 #3024

Diff stats

11 files+1486 added−492 removed

  • tests:+1110 added−252 removed
  • other:+376 added−240 removed

11 files+1486 added−492 removed

modified:docs/options.md+6 added-5 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 influence the value-less behavior, force its value with `default='upper'`. Setting flag values can be used to create patterns like this:318319```{eval-rst}320.. click:example::321322 import sys323324 @click.command()325 @click.option('--upper', 'transformation', flag_value='upper', default=True)325 @click.option('--upper', 'transformation', flag_value='upper', default='upper')326 @click.option('--lower', 'transformation', flag_value='lower')327 def info(transformation):328 click.echo(getattr(sys.platform, transformation)())329
55 unmodified lines
385 - Values are stripped of leading and trailing whitespaces before being interpreted, so the `" True "` string is transformed to `"true"` and so activates the flag386 - 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 above387 - Any other value is interpreted as deactivating the flag388389.. caution::390 For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.389```{caution}390For boolean flags with a pair of values, the only recognized environment variable is the one provided to the `envvar` argument.391392 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.392So 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.393```394395Once 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.396397## 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+311 added-216 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.
132 unmodified lines
834 :param name: The name of the parameter.835 :rtype: ParameterSource836837 .. versionchanged:: 8.0837 Returns ``None`` if the parameter was not provided from any838 Returns `None` if the parameter was not provided from any839 source.840 """841 return self._parameter_source.get(name)842
20 unmodified lines
863 provided. This option is disabled by default.864 If enabled this will add ``--help`` as argument865 if no arguments are passed866 :param hidden: hide this command from help outputs.866 :param deprecated: If ``True`` or non-empty string, issues a message867 :param deprecated: If `True` or non-empty string, issues a message868 indicating that the command is deprecated and highlights869 its deprecation in --help. The message can be customized870 by using a string as the value.871
152 unmodified lines
10241025 def get_help_option(self, ctx: Context) -> Option | None:1026 """Returns the help option object.10271027 Skipped if :attr:`add_help_option` is ``False``.1028 Skipped if :attr:`add_help_option` is `False`.10291030 .. versionchanged:: 8.1.81031 The help option is now cached to avoid creating it multiple times.1032 """
161 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(
531 unmodified lines
1734 return decorator17351736 def get_command(self, ctx: Context, cmd_name: str) -> Command | None:1737 """Given a context and a command name, this returns a :class:`Command`1737 object if it exists or returns ``None``.1738 object if it exists or returns `None`.1739 """1740 return self.commands.get(cmd_name)17411742 def list_commands(self, ctx: Context) -> list[str]:
272 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 a2021 sequence is given, only the first non-empty environment variable is2022 used for the parameter.2023 :param shell_complete: A function that returns custom shell2024 completions. Used instead of the param's type completion if2025 given. Takes ``ctx, param, incomplete`` and must return a list2026 of :class:`~click.shell_completion.CompletionItem` or a list of2027 strings.2025 :param deprecated: If ``True`` or non-empty string, issues a message2028 :param deprecated: If `True` or non-empty string, issues a message2029 indicating that the argument is deprecated and highlights2030 its deprecation in --help. The message can be customized2031 by using a string as the value. A deprecated parameter2032 cannot be required, a ValueError will be raised otherwise.
26 unmodified lines
2059 tuples.20602061 .. versionchanged:: 8.02062 Setting a default is no longer required for ``nargs>1``, it will2060 default to ``None``. ``multiple=True`` or ``nargs=-1`` will2063 default to `None`. ``multiple=True`` or ``nargs=-1`` will2064 default to ``()``.20652066 .. versionchanged:: 7.12067 Empty environment variables are ignored rather than taking the
12 unmodified lines
2080 self,2081 param_decls: cabc.Sequence[str] | None = None,2082 type: types.ParamType | t.Any | None = None,2083 required: bool = False,2081 default: t.Any | t.Callable[[], t.Any] | None = None,2084 default: t.Any | t.Callable[[], t.Any] | None = UNSET,2085 callback: t.Callable[[Context, Parameter, t.Any], t.Any] | None = None,2086 nargs: int | None = None,2087 multiple: bool = False,2088 metavar: str | None = None,
40 unmodified lines
2129 f"'nargs' must be {self.type.arity} (or None) for"2130 f" type {self.type!r}, but it was {nargs}."2131 )21322130 # 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 )21632133 if required and deprecated:2134 raise ValueError(2135 f"The {self.param_type_name} '{self.human_readable_name}' "2136 "is deprecated and still required. A deprecated "
6 unmodified lines
21432144 Use :meth:`click.Context.to_info_dict` to traverse the entire2145 CLI structure.21462147 .. versionchanged:: 8.3.02148 Returns `None` for the :attr:`default` if it is :attr:`UNSET`.21492150 We explicitly hide the :attr:`UNSET` value to the user, as we choose to2151 make it an implementation detail. And because ``to_info_dict`` has been2152 designed for documentation purposes, we return `None` instead.21532154 .. versionadded:: 8.02155 """2156 return {2157 "name": self.name,
3 unmodified lines
2161 "type": self.type.to_info_dict(),2162 "required": self.required,2163 "nargs": self.nargs,2164 "multiple": self.multiple,2189 "default": self.default,2165 "default": self.default if self.default is not UNSET else None,2166 "envvar": self.envvar,2167 }21682169 def __repr__(self) -> str:
59 unmodified lines
2229 Added the ``call`` parameter.2230 """2231 value = ctx.lookup_default(self.name, call=False) # type: ignore22322257 if value is None:2233 if value is UNSET:2234 value = self.default22352236 if call and callable(value):2237 value = value()
5 unmodified lines
22432244 def consume_value(2245 self, ctx: Context, opts: cabc.Mapping[str, t.Any]2246 ) -> tuple[t.Any, ParameterSource]:2271 value = opts.get(self.name) # type: ignore2272 source = ParameterSource.COMMANDLINE2247 """Returns the parameter value produced by the parser.22482274 if value is None:2275 value = self.value_from_envvar(ctx)2276 source = ParameterSource.ENVIRONMENT2249 If the parser did not produce a value from user input, the value is either2250 sourced from the environment variable, the default map, or the parameter's2251 default value. In that order of precedence.22522278 if value is None:2279 value = ctx.lookup_default(self.name) # type: ignore2280 source = ParameterSource.DEFAULT_MAP2253 If no value is found, the value is returned as :attr:`UNSET`.2254 """2255 # If the value is set, it means the parser produced a value from user input.2256 value = opts.get(self.name, UNSET) # type: ignore2257 source = (2258 ParameterSource.COMMANDLINE2259 if value is not UNSET2260 else ParameterSource.DEFAULT2261 )22622282 if value is None:2283 value = self.get_default(ctx)2284 source = ParameterSource.DEFAULT2263 if value is UNSET:2264 envvar_value = self.value_from_envvar(ctx)2265 if envvar_value is not None:2266 value = envvar_value2267 source = ParameterSource.ENVIRONMENT22682269 if value is UNSET:2270 default_map_value = ctx.lookup_default(self.name) # type: ignore2271 if default_map_value is not UNSET:2272 value = default_map_value2273 source = ParameterSource.DEFAULT_MAP22742275 if value is UNSET:2276 default_value = self.get_default(ctx)2277 if default_value is not UNSET:2278 value = default_value2279 source = ParameterSource.DEFAULT22802281 return value, source22822283 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:2284 """Convert and validate a value against the option's2285 :attr:`type`, :attr:`multiple`, and :attr:`nargs`.2286 """2292 if value is None:2293 return () if self.multiple or self.nargs == -1 else None2287 if value in (None, UNSET):2288 if self.multiple or self.nargs == -1:2289 return ()2290 else:2291 return value22922293 def check_iter(value: t.Any) -> cabc.Iterator[t.Any]:2294 try:2295 return _check_iter(value)
4 unmodified lines
2300 raise BadParameter(2301 _("Value must be an iterable."), ctx=ctx, param=self2302 ) from None23032304 # Define the conversion function based on nargs and type.23052306 if self.nargs == 1 or self.type.is_composite:23072308 def convert(value: t.Any) -> t.Any:2309 return self.type(value, param=self, ctx=ctx)
26 unmodified lines
23362337 return convert(value)23382339 def value_is_missing(self, value: t.Any) -> bool:2340 """2341 A value is considered missing if:23422343 - it is :attr:`UNSET`,2344 - or if it is an empty sequence while the parameter is suppose to have2345 non-single value (i.e. :attr:`nargs` is not ``1`` or :attr:`multiple` is2346 set).2347 """2340 if value is None:2348 if value is UNSET:2349 return True23502351 if (self.nargs != 1 or self.multiple) and value == ():2352 return True23532354 return False23552356 def process_value(self, ctx: Context, value: t.Any) -> t.Any:2357 """Process the value of this parameter:23582359 1. Type cast the value using :meth:`type_cast_value`.2360 2. Check if the value is missing (see: :meth:`value_is_missing`), and raise2361 :exc:`MissingParameter` if it is required.2362 3. If a :attr:`callback` is set, call it to have the value replaced buy the2363 result of the callback.23642365 .. versionchanged:: 8.323662367 The :attr:`callback` is now receiving the :attr:`UNSET` sentinel if the2368 parameter is not given by the CLI user.23692370 The callback is receiving the value as-is, which let the developer decide2371 how to handle the different cases of `None`, ``UNSET``, or any other value.2372 """2373 value = self.type_cast_value(ctx, value)23742375 if self.required and self.value_is_missing(value):2376 raise MissingParameter(ctx=ctx, param=self)
3 unmodified lines
23802381 return value23822383 def resolve_envvar_value(self, ctx: Context) -> str | None:2360 if self.envvar is None:2361 return None2384 """Returns the value found in the environment variable(s) attached to this2385 parameter.23862363 if isinstance(self.envvar, str):2364 rv = os.environ.get(self.envvar)2387 Environment variables values are `always returned as strings2388 <https://docs.python.org/3/library/os.html#os.environ>`_.23892366 if rv:2367 return rv2368 else:2369 for envvar in self.envvar:2370 rv = os.environ.get(envvar)2390 This method returns `None` if:23912372 if rv:2373 return rv2392 - the :attr:`envvar` property is not set on the :class:`Parameter`,2393 - the environment variable is not found in the environment,2394 - the variable is found in the environment but its value is empty (i.e. the2395 environment variable is present but has an empty string).23962397 If :attr:`envvar` is setup with multiple environment variables,2398 then only the first non-empty value is returned.23992400 .. caution::24012402 The raw value extracted from the environment is not normalized and is2403 returned as-is. Any normalization or reconciliation is performed later by2404 the :class:`Parameter`'s :attr:`type`.2405 """2406 if not self.envvar:2407 return None24082409 envvars = [self.envvar] if isinstance(self.envvar, str) else self.envvar2410 for envvar in envvars:2411 raw_value = os.environ.get(envvar)24122413 # Return the first non-empty value of the list of environment variables.2414 if raw_value:2415 return raw_value2416 # Else, absence of value is interpreted as an environment variable that is2417 # not set, so proceed to the next one.24182419 return None24202377 def value_from_envvar(self, ctx: Context) -> t.Any | None:2378 rv: t.Any | None = self.resolve_envvar_value(ctx)2421 def value_from_envvar(self, ctx: Context) -> str | cabc.Sequence[str] | None:2422 """Process the raw environment variable string for this parameter.24232380 if rv is not None and self.nargs != 1:2381 rv = self.type.split_envvar_value(rv)2424 Returns the string as-is or splits it into a sequence of strings if the2425 parameter is expecting multiple values (i.e. its :attr:`nargs` property is set2426 to a value other than ``1``).2427 """2428 raw_value = self.resolve_envvar_value(ctx)24292383 return rv2430 if raw_value is not None and self.nargs != 1:2431 return self.type.split_envvar_value(raw_value)24322433 return raw_value24342435 def handle_parse_result(2436 self, ctx: Context, opts: cabc.Mapping[str, t.Any], args: list[str]2437 ) -> tuple[t.Any, list[str]]:2438 """Process the value produced by the parser from user input."""2439 with augment_usage_errors(ctx, param=self):2440 value, source = self.consume_value(ctx, opts)24412391 if (2392 self.deprecated2393 and value is not None2394 and source2395 not in (2396 ParameterSource.DEFAULT,2397 ParameterSource.DEFAULT_MAP,2398 )2399 ):2400 extra_message = (2401 f" {self.deprecated}" if isinstance(self.deprecated, str) else ""2402 )2403 message = _(2404 "DeprecationWarning: The {param_type} {name!r} is deprecated."2405 "{extra_message}"2406 ).format(2407 param_type=self.param_type_name,2408 name=self.human_readable_name,2409 extra_message=extra_message,2410 )2411 echo(style(message, fg="red"), err=True)24122442 ctx.set_parameter_source(self.name, source) # type: ignore24432444 # Only try to process the value if it is not coming from the defaults.2445 # Defaults set by the users are under their control and so are left2446 # untouched as Python values: these values does not need to be processed.2447 if source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP):2448 # If the parameter is deprecated, we want to warn the user about it.2449 # If the value is UNSET there is no need to warn the user of a2450 # parameter that has not been invoked.2451 if self.deprecated and value is not UNSET:2452 extra_message = (2453 f" {self.deprecated}"2454 if isinstance(self.deprecated, str)2455 else ""2456 )2457 message = _(2458 "DeprecationWarning: The {param_type} {name!r} is deprecated."2459 "{extra_message}"2460 ).format(2461 param_type=self.param_type_name,2462 name=self.human_readable_name,2463 extra_message=extra_message,2464 )2465 echo(style(message, fg="red"), err=True)24662467 try:2468 value = self.process_value(ctx, value)2469 except Exception:2470 if not ctx.resilient_parsing:2471 raise24722473 # Ignore values that we have a hard time processing.2421 value = None2474 value = UNSET24752423 if self.expose_value:2424 ctx.params[self.name] = value # type: ignore2476 if self.expose_value and self.name not in ctx.params:2477 # Click is logically enforcing that the name is None if the parameter is2478 # not exposed. We still assert it here to please the type checker.2479 assert self.name is not None, (2480 f"{self!r} parameter's name should not be None when exposing value."2481 )2482 # Normalize unset values to None, as we're about to pass them to the2483 # command function and move them to the pure-Python realm of user-written2484 # code.2485 ctx.params[self.name] = value if value is not UNSET else None24862487 return value, args24882489 def get_help_record(self, ctx: Context) -> tuple[str, str] | None:
40 unmodified lines
2530 All other parameters are passed onwards to the parameter constructor.25312532 :param show_default: Show the default value for this option in its2533 help text. Values are not shown by default, unless2473 :attr:`Context.show_default` is ``True``. If this value is a2534 :attr:`Context.show_default` is `True`. If this value is a2535 string, it shows that string in parentheses instead of the2536 actual value. This is particularly useful for dynamic options.2537 For single option boolean flags, the default remains hidden if2477 its value is ``False``.2538 its value is `False`.2539 :param show_envvar: Controls if an environment variable should be2540 shown on the help page and error messages.2541 Normally, environment variables are not shown.2481 :param prompt: If set to ``True`` or a non empty string then the2482 user will be prompted for input. If set to ``True`` the prompt2542 :param prompt: If set to `True` or a non empty string then the2543 user will be prompted for input. If set to `True` the prompt2544 will be the option name capitalized. A deprecated option cannot be2545 prompted.2546 :param confirmation_prompt: Prompt a second time to confirm the2547 value if it was prompted for. Can be set to a string instead of2487 ``True`` to customize the message.2488 :param prompt_required: If set to ``False``, the user will be2548 `True` to customize the message.2549 :param prompt_required: If set to `False`, the user will be2550 prompted for input only when the option was specified as a flag2551 without a value.2491 :param hide_input: If this is ``True`` then the input on the prompt2552 :param hide_input: If this is `True` then the input on the prompt2553 will be hidden from the user. This is useful for password input.2554 :param is_flag: forces this option to act as a flag. The default is2555 auto detection.2556 :param flag_value: which value should be used for this flag if it's
25 unmodified lines
2582 ``Context.show_default``.25832584 .. versionchanged:: 8.12585 The default of a single option boolean flag is not shown if the2525 default value is ``False``.2586 default value is `False`.25872588 .. versionchanged:: 8.0.12589 ``type`` is detected from ``flag_value`` if given.2590 """
8 unmodified lines
2599 confirmation_prompt: bool | str = False,2600 prompt_required: bool = True,2601 hide_input: bool = False,2602 is_flag: bool | None = None,2542 flag_value: t.Any | None = None,2603 flag_value: t.Any = UNSET,2604 multiple: bool = False,2605 count: bool = False,2606 allow_from_autoenv: bool = True,2607 type: types.ParamType | t.Any | None = None,
34 unmodified lines
2642 self.prompt_required = prompt_required2643 self.hide_input = hide_input2644 self.hidden = hidden26452585 # If prompt is enabled but not required, then the option can be2586 # used as a flag to indicate using prompt or flag_value.2646 # The _flag_needs_value property tells the parser that this option is a flag2647 # that cannot be used standalone and needs a value. With this information, the2648 # parser can determine whether to consider the next user-provided argument in2649 # the CLI as a value for this flag or as a new option.2650 # If prompt is enabled but not required, then it opens the possibility for the2651 # option to gets its value from the user.2652 self._flag_needs_value = self.prompt is not None and not self.prompt_required26532654 # Auto-detect if this is a flag or not.2655 if is_flag is None:2656 # Implicitly a flag because flag_value was set.2591 if flag_value is not None:2657 if flag_value is not UNSET:2658 is_flag = True2659 # Not a flag, but when used as a flag it shows a prompt.2660 elif self._flag_needs_value:2661 is_flag = False2596 # Implicitly a flag because flag options were given.2662 # Implicitly a flag because secondary options names were given.2663 elif self.secondary_opts:2664 is_flag = True2665 # The option is explicitly not a flag. But we do not know yet if it needs a2666 # value or not. So we look at the default value to determine it.2667 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 None2668 self._flag_needs_value = self.default is UNSET26692604 self.default: t.Any | t.Callable[[], t.Any]26052670 if is_flag:2671 # 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:2672 if self.default is UNSET and not self.required and not self.prompt:2673 if multiple:2674 self.default = ()26752676 # Auto-detect the type of the flag based on the flag_value.2677 if type is None:2678 # A flag without a flag_value is a boolean flag.2679 if flag_value is UNSET:2680 self.type = types.BoolParamType()2681 # If the flag value is a boolean, use BoolParamType.2682 elif isinstance(flag_value, bool):2683 self.type = types.BoolParamType()2684 # Otherwise, guess the type from the flag value.2685 else:2612 self.default = False2686 self.type = types.convert_type(None, flag_value)26872614 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)26252688 self.is_flag: bool = bool(is_flag)2689 self.is_bool_flag: bool = bool(2690 is_flag and isinstance(self.type, types.BoolParamType)2691 )2692 self.flag_value: t.Any = flag_value26932694 # Set boolean flag default to False if unset and not required.2695 if self.is_bool_flag:2696 if self.default is UNSET and not self.required:2697 self.default = False26982699 # Set the default flag_value if it is not set.2700 if self.flag_value is UNSET:2701 if self.is_flag:2702 self.flag_value = True2703 else:2704 self.flag_value = None27052632 # Counting2706 # Counting.2707 self.count = count2708 if count:2709 if type is None:2710 self.type = types.IntRange(min=0)2637 if self.default is None:2711 if self.default is UNSET:2712 self.default = 027132714 self.allow_from_autoenv = allow_from_autoenv2715 self.help = help
7 unmodified lines
27232724 if self.nargs == -1:2725 raise TypeError("nargs=-1 is not supported for options.")27262653 if self.prompt and self.is_flag and not self.is_bool_flag:2654 raise TypeError("'prompt' is not valid for non-boolean flag.")26552727 if not self.is_bool_flag and self.secondary_opts:2728 raise TypeError("Secondary flag is not valid for non-boolean flag.")27292730 if self.is_bool_flag and self.hide_input and self.prompt is not None:
8 unmodified lines
2739 if self.is_flag:2740 raise TypeError("'count' is not valid with 'is_flag'.")27412742 def to_info_dict(self) -> dict[str, t.Any]:2743 """2744 .. versionchanged:: 8.3.02745 Returns `None` for the :attr:`flag_value` if it is :attr:`UNSET`.27462747 We explicitly hide the :attr:`UNSET` value to the user, as we choose to2748 make it an implementation detail. And because ``to_info_dict`` has been2749 designed for documentation purposes, we return `None` instead.2750 """2751 info_dict = super().to_info_dict()2752 info_dict.update(2753 help=self.help,2754 prompt=self.prompt,2755 is_flag=self.is_flag,2677 flag_value=self.flag_value,2756 flag_value=self.flag_value if self.flag_value is not UNSET else None,2757 count=self.count,2758 hidden=self.hidden,2759 )2760 return info_dict
184 unmodified lines
2945 show_default = self.show_default2946 elif ctx.show_default is not None:2947 show_default = ctx.show_default29482870 if show_default_is_str or (show_default and (default_value is not None)):2949 if show_default_is_str or (2950 show_default and (default_value not in (None, UNSET))2951 ):2952 if show_default_is_str:2953 default_string = f"({self.show_default})"2954 elif isinstance(default_value, (list, tuple)):2955 default_string = ", ".join(str(d) for d in default_value)
31 unmodified lines
2987 extra["required"] = "required"29882989 return extra29902910 @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)29352991 def prompt_for_value(self, ctx: Context) -> t.Any:2992 """This is an alternative flow that can be activated in the full2993 value processing if a value does not exist. It will prompt the2994 user until a valid value exists and then returns the processed2995 value as result.2996 """2997 assert self.prompt is not None29982944 # Calculate the default before prompting anything to be stable.2999 # Calculate the default before prompting anything to lock in the value before3000 # attempting any user interaction.3001 default = self.get_default(ctx)30022947 # If this is a prompt for a flag we need to handle this2948 # differently.3003 # A boolean flag can use a simplified [y/n] confirmation prompt.3004 if self.is_bool_flag:3005 # If we have no boolean default, we force the user to explicitly provide3006 # one.3007 if default in (UNSET, None):3008 default = None3009 else:3010 default = bool(default)3011 return confirm(self.prompt, default)30123013 # If show_default is set to True/False, provide this to `prompt` as well. For3014 # non-bool values of `show_default`, we use `prompt`'s default behavior
2 unmodified lines
3017 prompt_kwargs["show_default"] = self.show_default30183019 return prompt(3020 self.prompt,2960 default=default,3021 # Use `None` to inform the prompt() function to reiterate until a valid3022 # value is provided by the user if we have no default.3023 default=None if default is UNSET else default,3024 type=self.type,3025 hide_input=self.hide_input,3026 show_choices=self.show_choices,3027 confirmation_prompt=self.confirmation_prompt,
1 unmodified line
3029 **prompt_kwargs,3030 )30313032 def resolve_envvar_value(self, ctx: Context) -> str | None:2970 """Find which environment variable to read for this option and return2971 its value.29722973 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.3033 """:class:`Option` resolves its environment variable the same way as3034 :func:`Parameter.resolve_envvar_value`, but it also supports3035 :attr:`Context.auto_envvar_prefix`. If we could not find an environment from3036 the :attr:`envvar` property, we fallback on :attr:`Context.auto_envvar_prefix`3037 to build dynamiccaly the environment variable name using the3038 :python:`{ctx.auto_envvar_prefix}_{self.name.upper()}` template.3039 """2982 rv = super().resolve_envvar_value(ctx)3040 raw_value = super().resolve_envvar_value(ctx)30412984 if rv is not None:2985 return rv3042 if raw_value is not None:3043 return raw_value30443045 if (3046 self.allow_from_autoenv3047 and ctx.auto_envvar_prefix is not None3048 and self.name is not None3049 ):3050 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"2993 rv = os.environ.get(envvar)3051 raw_value = os.environ.get(envvar)30522995 if rv:2996 return rv3053 # Return the first non-empty value of the list of environment variables.3054 if raw_value:3055 return raw_value3056 # Else, absence of value is interpreted as an environment variable that is3057 # not set, so proceed to the next one.30583059 return None30603000 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)3061 def value_from_envvar(self, ctx: Context) -> t.Any:3062 """3063 For :class:`Option`, this method processes the raw environment variable string3064 the same way as :func:`Parameter.value_from_envvar` does.30653066 But in the case of non-boolean flags, the value is analyzed to determine if the3067 flag is activated or not, and returns a boolean of its activation, or the3068 :attr:`flag_value` if the latter is set.30693070 This method also takes care of repeated options (i.e. options with3071 :attr:`multiple` set to `True`).3072 """3073 raw_value = self.resolve_envvar_value(ctx)30743075 # Absent environment variable or an empty string is interpreted as unset.3004 if rv is None:3076 if raw_value is None:3077 return None30783079 # 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 is3080 # flag, its envvar value still needs to be analyzed to determine if the flag is3081 # activated or not.3082 if self.is_flag and not self.is_bool_flag:3083 # If the flag_value is set and match the envvar value, return it3084 # directly.3013 if self.flag_value is not None and rv == self.flag_value:3085 if self.flag_value is not UNSET and raw_value == self.flag_value:3086 return self.flag_value3087 # Analyze the envvar value as a boolean to know if the flag is3088 # activated or not.3017 return types.BoolParamType.str_to_bool(rv)3089 return types.BoolParamType.str_to_bool(raw_value)30903091 # Split the envvar value if it is allowed to be repeated.3092 value_depth = (self.nargs != 1) + bool(self.multiple)3093 if value_depth > 0:3022 multi_rv = self.type.split_envvar_value(rv)3094 multi_rv = self.type.split_envvar_value(raw_value)3095 if self.multiple and self.nargs != 1:3096 multi_rv = batch(multi_rv, self.nargs) # type: ignore[assignment]30973098 return multi_rv30993028 return rv3100 return raw_value31013102 def consume_value(3103 self, ctx: Context, opts: cabc.Mapping[str, Parameter]3104 ) -> tuple[t.Any, ParameterSource]:3105 """3106 For :class:`Option`, the value can be collected from an interactive prompt if3107 the option is a flag that needs a value (and the :attr:`prompt` property is3108 set).31093110 Additionally, this method handles flag option that are activated without a3111 value, in which case the :attr:`flag_value` is returned.3112 """3113 value, source = super().consume_value(ctx, opts)31143035 # 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.3115 # The parser will emit a sentinel value if the option is allowed to as a flag3116 # without a value.3117 if value is _flag_needs_value:3118 # If the option allows for a prompt, we start an interaction with the user.3119 if self.prompt is not None and not ctx.resilient_parsing:3120 value = self.prompt_for_value(ctx)3121 source = ParameterSource.PROMPT3122 # Else the flag takes its flag_value as value.3123 else:3124 value = self.flag_value3125 source = ParameterSource.COMMANDLINE31263046 # A flag which is activated and has a flag_value set, should returns3047 # the latter, unless the value comes from the explicitly sets default.3127 # A flag which is activated always returns the flag value, unless the value3128 # comes from the explicitly sets default.3129 elif (3130 self.is_flag3131 and value is True3132 and not self.is_bool_flag3052 and self.flag_value is not None3053 and source is not ParameterSource.DEFAULT3133 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3134 ):3135 value = self.flag_value31363137 # Re-interpret a multiple option which has been sent as-is by the parser.3138 # Here we replace each occurrence of value-less flags (marked by the3139 # _flag_needs_value sentinel) with the flag_value.3140 elif (3141 self.multiple3059 and value is not None3142 and value is not UNSET3143 and source not in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3144 and any(v is _flag_needs_value for v in value)3145 ):3146 value = [self.flag_value if v is _flag_needs_value else v for v in value]3147 source = ParameterSource.COMMANDLINE31483065 # The value wasn't set, or used the param's default, prompt if3066 # prompting is enabled.3149 # The value wasn't set, or used the param's default, prompt for one to the user3150 # if prompting is enabled.3151 elif (3068 source in {None, ParameterSource.DEFAULT}3152 (3153 value is UNSET3154 or source in (ParameterSource.DEFAULT, ParameterSource.DEFAULT_MAP)3155 )3156 and self.prompt is not None3157 and (self.required or self.prompt_required)3158 and not ctx.resilient_parsing3159 ):
1 unmodified line
3161 source = ParameterSource.PROMPT31623163 return value, source31643165 def type_cast_value(self, ctx: Context, value: t.Any) -> t.Any:3166 if self.is_flag and not self.required:3167 if value is UNSET:3168 if self.is_bool_flag:3169 # If the flag is a boolean flag, we return False if it is not set.3170 value = False3171 return super().type_cast_value(ctx, value)317231733174class Argument(Parameter):3175 """Arguments are positional parameters to a command. They generally3176 provide fewer features than options but can have infinite ``nargs``3177 and are required by default.
8 unmodified lines
3186 param_decls: cabc.Sequence[str],3187 required: bool | None = None,3188 **attrs: t.Any,3189 ) -> None:3190 # Auto-detect the requirement status of the argument if not explicitly set.3191 if required is None:3096 if attrs.get("default") is not None:3097 required = False3098 else:3192 # The argument gets automatically required if it has no explicit default3193 # value set and is setup to match at least one value.3194 if attrs.get("default", UNSET) is UNSET:3195 required = attrs.get("nargs", 1) > 03196 # If the argument has a default value, it is not required.3197 else:3198 required = False31993200 if "multiple" in attrs:3201 raise TypeError("__init__() got an unexpected keyword argument 'multiple'.")32023203 super().__init__(param_decls, required=required, **attrs)32043106 if __debug__:3107 if self.default is not None and self.nargs == -1:3108 raise TypeError("'default' is not supported for nargs=-1.")31093205 @property3206 def human_readable_name(self) -> str:3207 if self.metavar is not None:3208 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:src/click/termui.py+2 added
218 unmodified lines
219220 .. versionadded:: 4.0221 Added the ``err`` parameter.222 """223 assert default in (True, False, None), "default must be True, False, or None"224225 prompt = _build_prompt(226 text,227 prompt_suffix,228 show_default,
651 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+55 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", "expect"),281 (282 # See: https://github.com/pallets/click/issues/3024#issuecomment-3146199461283 (True, ["--upper"], "upper"),284 (True, ["--lower"], "lower"),285 (True, [], "True"),286 ("upper", [], "upper"),287 ),288)289def test_flag_value(runner, default, args, expect):290 @click.command()291 @click.option("--upper", "transformation", flag_value="upper", default=default)292 @click.option("--lower", "transformation", flag_value="lower")293 def cli(transformation):294 click.echo(repr(transformation), nl=False)295296 result = runner.invoke(cli, args)297 assert result.output == repr(expect)298299300def test_file_option(runner):301 @click.command()302 @click.option("--file", type=click.File("w"))303 def input(file):
206 unmodified lines
510 "method", type=click.Choice(["not-none", None], case_sensitive=False)511 )512 def cli(method: str | None):513 assert isinstance(method, str) or method is None478 click.echo(method)514 click.echo(repr(method), nl=False)515516 result = runner.invoke(cli, ["not-none"])517 assert not result.exception482 assert result.output == "not-none\n"518 assert result.output == repr("not-none")519484 # None is not yet supported.520 result = runner.invoke(cli, ["none"])521 assert not result.exception522 assert result.output == repr(None)523524 result = runner.invoke(cli, [])525 assert result.exception526 assert (527 "Error: Missing argument '{not-none|none}'. "528 "Choose from:\n\tnot-none,\n\tnone\n" in result.stderr529 )530531 result = runner.invoke(cli, ["--help"])532 assert result.output.startswith("Usage: cli [OPTIONS] {not-none|none}\n")533534535def test_datetime_option_default(runner):536 @click.command()537 @click.option("--start_date", type=click.DateTime())538 def cli(start_date):
166 unmodified lines
modified:tests/test_options.py+667 added-213 removed
8 unmodified lines
9import pytest1011import click12from click import Option13from click import UNPROCESSED14from click._utils import UNSET151617def test_prefixes(runner):18 @click.command()
67 unmodified lines
86 click.Option(["--a"], prompt=True, deprecated=True)878889def test_invalid_nargs(runner):88 with pytest.raises(TypeError, match="nargs=-1"):90 with pytest.raises(TypeError, match="nargs=-1 is not supported for options."):9192 @click.command()93 @click.option("--foo", nargs=-1)94 def cli(foo):
76 unmodified lines
171 assert "Error: Missing option '-m' / '--message'." in result.output172173174@pytest.mark.parametrize(173 ("multiple", "nargs", "default"),175 ("args", "multiple", "nargs", "default", "expected"),176 [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]]),177 # If multiple values are allowed, defaults should be iterable.178 ([], True, 1, [], ()),179 ([], True, 1, (), ()),180 ([], True, 1, tuple(), ()),181 ([], True, 1, set(), ()),182 ([], True, 1, frozenset(), ()),183 ([], True, 1, {}, ()),184 # Special values.185 ([], True, 1, None, ()),186 ([], True, 1, UNSET, ()),187 # Number of values are kept as-is in the default.188 ([], True, 1, [1], (1,)),189 ([], True, 1, [1, 2], (1, 2)),190 ([], True, 1, [1, 2, 3], (1, 2, 3)),191 ([], True, 1, [1.1, 2.2], (1.1, 2.2)),192 ([], True, 1, ["1", "2"], ("1", "2")),193 ([], True, 1, [None, None], (None, None)),194 # XXX Why items of the defaults are converted to strings and not left as195 # integers?196 ([], True, 1, {1, 2}, ("1", "2")),197 ([], True, 1, frozenset([1, 2]), ("1", "2")),198 ([], True, 1, {1: "a", 2: "b"}, ("1", "2")),199 # Multiple values with nargs > 1.200 ([], True, 2, [], ()),201 ([], True, 2, (), ()),202 ([], True, 2, tuple(), ()),203 ([], True, 2, set(), ()),204 ([], True, 2, frozenset(), ()),205 ([], True, 2, {}, ()),206 ([], True, 2, None, ()),207 ([], True, 2, UNSET, ()),208 ([], True, 2, [[1, 2]], ((1, 2),)),209 ([], True, 2, [[1, 2], [3, 4]], ((1, 2), (3, 4))),210 ([], True, 2, [[1, 2], [3, 4], [5, 6]], ((1, 2), (3, 4), (5, 6))),211 ([], True, 2, [[1.1, 2.2], [3.3, 4.4]], ((1.1, 2.2), (3.3, 4.4))),212 ([], True, 2, [["1", "2"], ["3", "4"]], (("1", "2"), ("3", "4"))),213 ([], True, 2, [[None, None], [None, None]], ((None, None), (None, None))),214 ([], True, 2, [[1, 2.2], ["3", None]], ((1, 2.2), (3, None))),215 ([], True, 2, [[1, 2.2], None], ((1, 2.2), None)),216 #217 ([], False, 2, [1, 2], (1, 2)),218 #219 ],220)187def test_init_good_default_list(runner, multiple, nargs, default):188 click.Option(["-a"], multiple=multiple, nargs=nargs, default=default)221def test_good_defaults_for_multiple(runner, args, multiple, nargs, default, expected):222 @click.command()223 @click.option("-a", multiple=multiple, nargs=nargs, default=default)224 def cmd(a):225 click.echo(repr(a), nl=False)226227 result = runner.invoke(cmd, args)228 assert result.output == repr(expected)229230231@pytest.mark.parametrize(192 ("multiple", "nargs", "default"),232 ("multiple", "nargs", "default", "message"),233 [194 (True, 1, 1),195 # (False, -1, 1),196 (False, 2, [1]),197 (True, 2, [[1]]),234 # Non-iterables defaults.235 (True, 1, "Yo", "Error: Invalid value for '-a': Value must be an iterable."),236 (True, 1, "", "Error: Invalid value for '-a': Value must be an iterable."),237 (238 True,239 1,240 True,241 "Error: Invalid value for '-a': Value must be an iterable.",242 ),243 (244 True,245 1,246 False,247 "Error: Invalid value for '-a': Value must be an iterable.",248 ),249 (True, 1, 12, "Error: Invalid value for '-a': Value must be an iterable."),250 (True, 1, 7.9, "Error: Invalid value for '-a': Value must be an iterable."),251 #252 (False, 2, 42, "Error: Invalid value for '-a': Value must be an iterable."),253 (254 True,255 2,256 ["test string which is not a list in the list"],257 "Error: Invalid value for '-a': Value must be an iterable.",258 ),259 # Multiple options, each with 2 args, but with wrong length.260 (261 True,262 2,263 (1,),264 "Error: Invalid value for '-a': Value must be an iterable.",265 ),266 (267 True,268 2,269 (1, 2, 3),270 "Error: Invalid value for '-a': Value must be an iterable.",271 ),272 # A mix of valid and invalid defaults.273 (274 True,275 2,276 [[1, 2.2], []],277 "Error: Invalid value for '-a': 2 values are required, but 0 were given.",278 ),279 ],280)200def test_init_bad_default_list(runner, multiple, nargs, default):201 type = (str, str) if nargs == 2 else None281def test_bad_defaults_for_multiple(runner, multiple, nargs, default, message):282 @click.command()283 @click.option("-a", multiple=multiple, nargs=nargs, default=default)284 def cmd(a):285 click.echo(repr(a))286203 with pytest.raises(ValueError, match="default"):204 click.Option(["-a"], type=type, multiple=multiple, nargs=nargs, default=default)287 result = runner.invoke(cmd, [])288 assert message in result.stderr289290291@pytest.mark.parametrize("env_key", ["MYPATH", "AUTO_MYPATH"])292def test_empty_envvar(runner, env_key):
43 unmodified lines
336 assert result.output == "foo|bar\n"337338339@pytest.mark.parametrize(256 ("name", "value", "expected"),340 ("envvar_name", "envvar_value", "expected"),341 (342 # Lower-cased variations of value.343 ("SHOUT", "true", True),344 ("SHOUT", "false", False),
8 unmodified lines
353 ("SHOUT", "truE", True),354 ("SHOUT", "FaLsE", False),355 ("SHOUT", "falsE", False),356 # 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),357 ("SHOUT", "true ", True),358 ("SHOUT", " true ", True),359 ("SHOUT", " true", True),360 ("SHOUT", "false ", False),361 ("SHOUT", " false ", False),362 ("SHOUT", " false", False),363 # Integer variations.364 ("SHOUT", "1", True),365 ("SHOUT", "0", False),366 # Alternative states.367 ("SHOUT", "t", True),368 ("SHOUT", "T", True),369 ("SHOUT", " T ", True),370 ("SHOUT", "f", False),371 ("SHOUT", "y", True),372 ("SHOUT", "n", False),373 ("SHOUT", "yes", True),
6 unmodified lines
380 ("SHOUT", " ", False),381 ("SHOUT", " ", False),382 # Variable names are not stripped of spaces and so don't match the383 # flag, which then naturraly takes its default value.298 ("SHOUT ", "True", False),299 ("SHOUT ", "False", False),384 ("SHOUT ", "True", False),385 ("SHOUT ", "False", False),386 (" SHOUT ", "True", False),387 (" SHOUT ", "False", False),388 (" SHOUT", "True", False),389 (" SHOUT", "False", False),390 ("SH OUT", "True", False),391 ("SH OUT", "False", False),392 # Same for random and reverse environment variable names: they are not393 # recognized by the option.394 ("RANDOM", "True", False),395 ("NO_SHOUT", "True", False),396 ("NO_SHOUT", "False", False),397 ("NOSHOUT", "True", False),398 ("NOSHOUT", "False", False),399 ),400)309def test_boolean_envvar_normalization(runner, name, value, expected):401def test_boolean_flag_envvar(runner, envvar_name, envvar_value, expected):402 assert isinstance(envvar_name, str)403 assert isinstance(envvar_value, str) or envvar_value is None404405 @click.command()406 @click.option("--shout/--no-shout", envvar="SHOUT")407 def cli(shout):313 click.echo(f"shout: {shout!r}")408 click.echo(repr(shout), nl=False)409315 result = runner.invoke(cli, [], env={name: value})410 result = runner.invoke(cli, [], env={envvar_name: envvar_value})411 assert result.exit_code == 0317 assert result.output == f"shout: {expected}\n"412 assert result.output == repr(expected)413414415@pytest.mark.parametrize(321 ("name", "value"),416 "value",417 (323 ("SHOUT", "tr ue"),324 ("SHOUT", "10"),325 ("SHOUT", "01"),326 ("SHOUT", "00"),327 ("SHOUT", "11"),328 ("SHOUT", "randomstring"),329 ("SHOUT", "None"),418 # Extra spaces inside the value.419 "tr ue",420 "fa lse",421 # Numbers.422 "10",423 "01",424 "00",425 "11",426 "0.0",427 "1.1",428 # Random strings.429 "randomstring",430 "None",431 "'None'",432 "A B",433 " 1 2 ",434 "9.3",435 "a;n",436 "x:y",437 "i/o",438 ),439)332def test_boolean_envvar_bad_values(runner, name, value):440def test_boolean_envvar_bad_values(runner, value):441 @click.command()442 @click.option("--shout/--no-shout", envvar="SHOUT")443 def cli(shout):336 click.echo(f"shout: {shout!r}")444 click.echo(shout)445338 result = runner.invoke(cli, [], env={name: value})446 result = runner.invoke(cli, [], env={"SHOUT": value})447 assert result.exit_code == 2448 assert (449 f"Invalid value for '--shout': {value!r} is not a valid boolean."450 in result.output
285 unmodified lines
736 result = runner.invoke(cmd, ["-whatever=23"])737 assert result.output == "23\n"738739632def test_missing_option_string_cast():740@pytest.mark.parametrize(741 ("value", "expect_missing", "processed_value"),742 [743 (UNSET, True, None),744 (None, False, None),745 # Default type of the argument is str, so everything is processed as strings.746 ("", False, ""),747 (" ", False, " "),748 ("foo", False, "foo"),749 ("12", False, "12"),750 (12, False, "12"),751 (12.1, False, "12.1"),752 (list(), False, "[]"),753 (tuple(), False, "()"),754 (set(), False, "set()"),755 (frozenset(), False, "frozenset()"),756 (dict(), False, "{}"),757 ],758)759def test_required_option(value, expect_missing, processed_value):760 ctx = click.Context(click.Command(""))761 argument = click.Option(["-a"], required=True)762763 if expect_missing:635 with pytest.raises(click.MissingParameter) as excinfo:636 click.Option(["-a"], required=True).process_value(ctx, None)764 with pytest.raises(click.MissingParameter) as excinfo:765 argument.process_value(ctx, value)766 assert str(excinfo.value) == "Missing parameter: a"767638 assert str(excinfo.value) == "Missing parameter: a"768 else:769 value = argument.process_value(ctx, value)770 assert value == processed_value771772773def test_missing_required_flag(runner):774 cli = click.Command(
456 unmodified lines
1231 assert param.type is click.INT123212331234@pytest.mark.parametrize(1103 ("opt_params", "pass_flag", "expected"),1235 ("opt_params", "args", "expected"),1236 [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"),1237 # The type passed to the option is responsible to converting the value, whether1238 # we pass the option flag or not.1239 ({"type": bool}, [], False),1240 ({"type": bool}, ["--foo"], True),1241 ({"type": click.BOOL}, [], False),1242 ({"type": click.BOOL}, ["--foo"], True),1243 ({"type": str}, [], None),1244 ({"type": str}, ["--foo"], "True"),1245 # Default value is given as-is to the --foo option when it is not passed,1246 # whatever the type. Now if --foo is passed, the value is always True, whatever1247 # the type. In both case the type of the option is responsible for the1248 # conversion of the value.1249 ({"type": bool, "default": True}, [], True),1250 ({"type": bool, "default": True}, ["--foo"], True),1251 ({"type": bool, "default": False}, [], False),1252 ({"type": bool, "default": False}, ["--foo"], True),1253 # ({"type": bool, "default": "foo"}, [], "foo"),1254 ({"type": bool, "default": "foo"}, ["--foo"], True),1255 ({"type": bool, "default": None}, [], None),1256 ({"type": bool, "default": None}, ["--foo"], True),1257 ({"type": click.BOOL, "default": True}, [], True),1258 ({"type": click.BOOL, "default": True}, ["--foo"], True),1259 ({"type": click.BOOL, "default": False}, [], False),1260 ({"type": click.BOOL, "default": False}, ["--foo"], True),1261 # ({"type": click.BOOL, "default": "foo"}, [], "foo"),1262 ({"type": click.BOOL, "default": "foo"}, ["--foo"], True),1263 ({"type": click.BOOL, "default": None}, [], None),1264 ({"type": click.BOOL, "default": None}, ["--foo"], True),1265 ({"type": str, "default": True}, [], "True"),1266 ({"type": str, "default": True}, ["--foo"], "True"),1267 ({"type": str, "default": False}, [], "False"),1268 ({"type": str, "default": False}, ["--foo"], "True"),1269 ({"type": str, "default": "foo"}, [], "foo"),1270 ({"type": str, "default": "foo"}, ["--foo"], "True"),1271 ({"type": str, "default": None}, [], None),1272 ({"type": str, "default": None}, ["--foo"], "True"),1273 # Flag value is given as-is to the --foo option when it is passed, then1274 # converted by the option type.1275 ({"type": bool, "flag_value": True}, [], False),1276 ({"type": bool, "flag_value": True}, ["--foo"], True),1277 ({"type": bool, "flag_value": False}, [], False),1278 ({"type": bool, "flag_value": False}, ["--foo"], False),1279 ({"type": bool, "flag_value": None}, [], False),1280 ({"type": bool, "flag_value": None}, ["--foo"], None),1281 ({"type": click.BOOL, "flag_value": True}, [], False),1282 ({"type": click.BOOL, "flag_value": True}, ["--foo"], True),1283 ({"type": click.BOOL, "flag_value": False}, [], False),1284 ({"type": click.BOOL, "flag_value": False}, ["--foo"], False),1285 ({"type": click.BOOL, "flag_value": None}, [], False),1286 ({"type": click.BOOL, "flag_value": None}, ["--foo"], None),1287 ({"type": str, "flag_value": True}, [], None),1288 ({"type": str, "flag_value": True}, ["--foo"], "True"),1289 ({"type": str, "flag_value": False}, [], None),1290 ({"type": str, "flag_value": False}, ["--foo"], "False"),1291 ({"type": str, "flag_value": "foo"}, [], None),1292 ({"type": str, "flag_value": "foo"}, ["--foo"], "foo"),1293 ({"type": str, "flag_value": None}, [], None),1294 ({"type": str, "flag_value": None}, ["--foo"], None),1295 # Not passing --foo returns the default value as-is, in its Python type, then1296 # converted by the option type.1297 ({"type": bool, "default": True, "flag_value": True}, [], True),1298 ({"type": bool, "default": True, "flag_value": False}, [], True),1299 ({"type": bool, "default": False, "flag_value": True}, [], False),1300 ({"type": bool, "default": False, "flag_value": False}, [], False),1301 ({"type": bool, "default": None, "flag_value": True}, [], None),1302 ({"type": bool, "default": None, "flag_value": False}, [], None),1303 ({"type": str, "default": True, "flag_value": True}, [], "True"),1304 ({"type": str, "default": True, "flag_value": False}, [], "True"),1305 ({"type": str, "default": False, "flag_value": True}, [], "False"),1306 ({"type": str, "default": False, "flag_value": False}, [], "False"),1307 ({"type": str, "default": "foo", "flag_value": True}, [], "foo"),1308 ({"type": str, "default": "foo", "flag_value": False}, [], "foo"),1309 ({"type": str, "default": "foo", "flag_value": "bar"}, [], "foo"),1310 ({"type": str, "default": "foo", "flag_value": None}, [], "foo"),1311 ({"type": str, "default": None, "flag_value": True}, [], None),1312 ({"type": str, "default": None, "flag_value": False}, [], None),1313 # Passing --foo returns the flag_value that was explicitly set by the user,1314 # with its Python type, but still converted by the option type.1315 ({"type": bool, "default": True, "flag_value": True}, ["--foo"], True),1316 ({"type": bool, "default": True, "flag_value": False}, ["--foo"], False),1317 ({"type": bool, "default": False, "flag_value": True}, ["--foo"], True),1318 ({"type": bool, "default": False, "flag_value": False}, ["--foo"], False),1319 ({"type": bool, "default": None, "flag_value": True}, ["--foo"], True),1320 ({"type": bool, "default": None, "flag_value": False}, ["--foo"], False),1321 ({"type": str, "default": True, "flag_value": True}, ["--foo"], "True"),1322 ({"type": str, "default": True, "flag_value": False}, ["--foo"], "False"),1323 ({"type": str, "default": False, "flag_value": True}, ["--foo"], "True"),1324 ({"type": str, "default": False, "flag_value": False}, ["--foo"], "False"),1325 ({"type": str, "default": "foo", "flag_value": True}, ["--foo"], "True"),1326 ({"type": str, "default": "foo", "flag_value": False}, ["--foo"], "False"),1327 ({"type": str, "default": "foo", "flag_value": "bar"}, ["--foo"], "bar"),1328 ({"type": str, "default": "foo", "flag_value": None}, ["--foo"], None),1329 ({"type": str, "default": None, "flag_value": True}, ["--foo"], "True"),1330 ({"type": str, "default": None, "flag_value": False}, ["--foo"], "False"),1331 ],1332)1190def test_flag_value_and_default(runner, opt_params, pass_flag, expected):1333def test_flag_value_and_default(runner, opt_params, args, expected):1334 @click.command()1335 @click.option("--foo", is_flag=True, **opt_params)1336 def cmd(foo):1194 click.echo(repr(foo))1337 click.echo(repr(foo), nl=False)13381196 result = runner.invoke(cmd, ["--foo"] if pass_flag else [])1197 assert result.output == f"{expected!r}\n"1339 result = runner.invoke(cmd, args)1340 assert result.output == repr(expected)134113421343@pytest.mark.parametrize(1201 "opts",1344 ("args", "opts"),1345 [1203 {"type": bool, "default": "foo"},1204 {"type": bool, "flag_value": "foo"},1205 {"type": click.BOOL, "default": "foo"},1206 {"type": click.BOOL, "flag_value": "foo"},1346 ([], {"type": bool, "default": "foo"}),1347 ([], {"type": click.BOOL, "default": "foo"}),1348 (["--foo"], {"type": bool, "flag_value": "foo"}),1349 (["--foo"], {"type": click.BOOL, "flag_value": "foo"}),1350 ],1351)1209def test_invalid_flag_definition(runner, opts):1352def test_invalid_flag_definition(runner, args, opts):1353 @click.command()1354 @click.option("--foo", is_flag=True, **opts)1355 def cmd(foo):1356 click.echo(foo)13571215 result = runner.invoke(cmd, ["--foo"])1358 result = runner.invoke(cmd, args)1359 assert (1360 "Error: Invalid value for '--foo': 'foo' is not a valid boolean"1361 in result.output1362 )136313641365@pytest.mark.parametrize(1366 ("default", "args", "expected"),1367 [1368 (None, [], "A real None"),1369 (UNSET, [], "A real UNSET"),1370 ("random", [], "random"),1371 (None, ["--js"], "js"),1372 (None, ["--xml"], "xml"),1373 ],1374)1375def test_flag_value_callback(runner, default, args, expected):1376 """1377 Reproduction of the issue reported in1378 https://github.com/pallets/click/pull/3030#discussion_r22715718191379 """13801381 def _my_func(ctx, param, value):1382 if value is None:1383 return "A real None"1384 if value is UNSET:1385 return "A real UNSET"1386 return value13871388 @click.command()1389 @click.option("--js", "fmt", flag_value="js", callback=_my_func, default=default)1390 @click.option("--xml", "fmt", flag_value="xml", callback=_my_func)1391 def main(fmt):1392 click.secho(repr(fmt), nl=False)13931394 result = runner.invoke(main, args)1395 assert result.output == repr(expected)1396 assert result.exit_code == 0139713981399@pytest.mark.parametrize(1400 ("flag_value", "envvar_value", "expected"),1401 [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.1402 # The envvar match exactly the flag value and is case-sensitive.1403 ("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"),1404 ("BAR", "BAR", "BAR"),1247 ("BAR", "bar", "False"),1405 (" bar ", " bar ", " bar "),1406 ("42", "42", "42"),1407 ("None", "None", "None"),1408 ("True", "True", "True"),1409 ("False", "False", "False"),1410 ("true", "true", "true"),1411 ("false", "false", "false"),1412 ("A B", "A B", "A B"),1413 (" 1 2 ", " 1 2 ", " 1 2 "),1414 ("9.3", "9.3", "9.3"),1415 ("a;n", "a;n", "a;n"),1416 ("x:y", "x:y", "x:y"),1417 ("i/o", "i/o", "i/o"),1418 # Empty or absent envvar is consider unset, so the flag default value is1419 # returned, which is None in this case.1420 ("bar", "", None),1421 ("bar", None, None),1422 ("BAR", "", None),1423 ("BAR", None, None),1424 (" bar ", "", None),1425 (" bar ", None, None),1426 (42, "", None),1427 (42, None, None),1428 ("42", "", None),1429 ("42", None, None),1430 (None, "", None),1431 (None, None, None),1432 ("None", "", None),1433 ("None", None, None),1434 (True, "", None),1435 (True, None, None),1436 ("True", "", None),1437 ("True", None, None),1438 ("true", "", None),1439 ("true", None, None),1440 (False, "", None),1441 (False, None, None),1442 ("False", "", None),1443 ("False", None, None),1444 ("false", "", None),1445 ("false", None, None),1446 # Activate the flag with a value recognized as True by the envvar, which1447 # returns the flag_value.1448 ("bar", "True", "bar"),1449 ("bar", "true", "bar"),1450 ("bar", "trUe", "bar"),1451 ("bar", " TRUE ", "bar"),1452 ("bar", "1", "bar"),1453 ("bar", "yes", "bar"),1454 ("bar", "on", "bar"),1455 ("bar", "t", "bar"),1456 ("bar", "y", "bar"),1457 # Deactivating the flag with a value recognized as False by the envvar, which1458 # explicitly return the 'False' as the option is explicitely declared as a1459 # string.1460 ("bar", "False", "False"),1461 ("bar", "false", "False"),1462 ("bar", "faLse", "False"),1463 ("bar", " FALSE ", "False"),1249 (" bar ", "bar", "False"),1250 (" bar ", "BAR", "False"),1464 ("bar", "0", "False"),1465 ("bar", "no", "False"),1466 ("bar", "off", "False"),1467 ("bar", "f", "False"),1468 ("bar", "n", "False"),1469 # Any other value than the flag_value, or a recogned True or False value, fails1470 # to explicitely activate or deactivate the flag. So the flag default value is1471 # returned, which is None in this case.1472 ("bar", " bar ", None),1473 ("bar", "BAR", None),1474 ("bar", "random", None),1475 ("bar", "bar random", None),1476 ("bar", "random bar", None),1477 ("BAR", "bar", None),1478 (" bar ", "bar", None),1479 (" bar ", "BAR", None),1480 (42, "42", None),1481 (42, "foo", None),1482 (None, "foo", None),1483 ("None", "foo", None),1484 ],1485)1253def test_envvar_flag_value(runner, flag_value, envvar_value, expected):1486def test_envvar_string_flag_value(runner, flag_value, envvar_value, expected):1487 """Ensure that flag_value is recognized by the envvar."""14881489 @click.command()1257 @click.option(1258 "--upper", type=str, is_flag=True, flag_value=flag_value, envvar="UPPER"1259 )1490 @click.option("--upper", type=str, flag_value=flag_value, envvar="UPPER")1491 def cmd(upper):1261 click.echo(repr(upper))1492 click.echo(repr(upper), nl=False)14931494 result = runner.invoke(cmd, env={"UPPER": envvar_value})1495 assert result.exit_code == 01265 assert result.output == f"{expected!r}\n"1496 assert result.output == repr(expected)149714981499@pytest.mark.parametrize(1269 ("option", "expected"),1500 ("opt_decls", "opt_params", "expect_is_flag", "expect_is_bool_flag"),1501 [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"),1502 # Not boolean flags.1503 ("-a", {"type": int}, False, False),1504 ("-a", {"type": bool}, False, False),1505 ("-a", {"default": True}, False, False),1506 ("-a", {"default": False}, False, False),1507 ("-a", {"flag_value": 1}, True, False),1508 # Boolean flags.1509 ("-a", {"is_flag": True}, True, True),1510 ("-a/-A", {}, True, True),1511 ("-a", {"flag_value": True}, True, True),1512 # Non-flag with flag_value.1513 ("-a", {"is_flag": False, "flag_value": 1}, False, False),1514 ],1515)1283def test_bool_flag_auto_detection(option, expected):1284 assert option.is_bool_flag is expected1516def test_flag_auto_detection(1517 opt_decls, opt_params, expect_is_flag, expect_is_bool_flag1518):1519 option = Option([opt_decls], **opt_params)1520 assert option.is_flag is expect_is_flag1521 assert option.is_bool_flag is expect_is_bool_flag152215231524@pytest.mark.parametrize(1525 ("kwargs", "message"),
75 unmodified lines
1601 def cli_with_choices(g):1602 pass16031604 @click.command()1368 @click.option(1369 "-g",1370 type=click.Choice(choices),1371 show_choices=False,1372 )1605 @click.option("-g", type=click.Choice(choices), show_choices=False)1606 def cli_without_choices(g):1607 pass16081609 result = runner.invoke(cli_with_choices, ["--help"])
77 unmodified lines
1687 with pytest.warns(UserWarning):1688 runner.invoke(cli, [])168916901691def test_custom_type_click_class_flag_value(runner):1692 """A reproduction of1693 https://github.com/pallets/click/issues/3024#issuecomment-31465113561694 """16951696 NO_CONFIG = object()16971698 class ConfigParamType(click.ParamType):1699 name = "config"17001701 def convert(self, value, param, ctx):1702 if value is NO_CONFIG:1703 return value1704 else:1705 return click.Path(exists=True, dir_okay=False).convert(1706 value, param, ctx1707 )17081709 @click.command()1710 @click.option("-c", "--config", type=ConfigParamType())1711 @click.option("--no-config", "config", flag_value=NO_CONFIG, type=ConfigParamType())1712 def main(config):1713 click.echo(repr(config), nl=False)17141715 result = runner.invoke(main)1716 assert result.output == repr(None)171717181719class EngineType(enum.Enum):1720 OSS = enum.auto()1721 PRO = enum.auto()1722 MAX = enum.auto()172317241725class Class1:1726 pass172717281729class Class2:1730 pass173117321733@pytest.mark.parametrize(1459 ("multiple", "nargs", "default", "expected_message"),1734 ("opt_params", "args", "expected"),1735 [1736 # Reproduction of cases from1737 # https://github.com/pallets/click/issues/3024#issuecomment-31464807141738 ({"type": EngineType, "flag_value": None}, [], None),1739 ({"type": EngineType, "flag_value": None}, ["--pro"], None),1740 ({"type": EngineType, "flag_value": EngineType.MAX}, [], None),1741 (1462 False, # multiple1463 2, # nargs1464 42, # default (not a list)1465 "'default' must be a list when 'nargs' != 1.",1742 {"type": EngineType, "flag_value": EngineType.MAX},1743 ["--pro"],1744 EngineType.MAX,1745 ),1746 ({"type": EngineType, "default": EngineType.OSS}, [], EngineType.OSS),1747 (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.",1748 {"type": EngineType, "default": EngineType.OSS},1749 ["--pro"],1750 re.compile(re.escape("Error: Option '--pro' requires an argument.\n")),1751 ),1752 (1753 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},1754 [],1755 EngineType.OSS,1756 ),1757 (1758 {"type": EngineType, "is_flag": True, "default": EngineType.OSS},1759 ["--pro"],1760 EngineType.OSS,1761 ),1762 # Reproduction of cases from1763 # https://github.com/pallets/click/issues/2012#issuecomment-8924370601764 (1765 {"flag_value": EngineType.OSS, "default": True},1766 [],1767 "True",1768 ),1769 (1770 {"type": EngineType, "flag_value": EngineType.OSS, "default": True},1771 [],1772 EngineType.OSS,1773 ),1774 ({"flag_value": 1, "default": True}, [], 1),1775 ({"flag_value": "1", "default": True}, [], "True"),1776 ({"flag_value": 1, "type": str, "default": True}, [], "True"),1777 ({"flag_value": "1", "type": str, "default": True}, [], "True"),1778 ({"flag_value": 1, "type": int, "default": True}, [], 1),1779 ({"flag_value": "1", "type": int, "default": True}, [], 1),1780 ],1781)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 )1782def test_custom_type_flag_value_standalone_option(runner, opt_params, args, expected):1783 @click.command()1784 @click.option("--pro", **opt_params)1785 def scan(pro):1786 click.echo(repr(pro), nl=False)17871788 result = runner.invoke(scan, args)1789 if isinstance(expected, re.Pattern):1790 assert re.match(expected, result.output)1791 else:1792 assert result.output == repr(expected)179317941795@pytest.mark.parametrize(1796 ("opt1_params", "opt2_params", "args", "expected"),1797 [1798 ###1799 ### Reproduces https://github.com/pallets/click/issues/3024#issuecomment-31465085361800 ###1801 (1802 {"flag_value": EngineType.OSS, "type": UNPROCESSED},1803 {"flag_value": EngineType.PRO, "type": UNPROCESSED},1804 [],1805 None,1806 ),1807 (1808 {"flag_value": EngineType.OSS, "type": UNPROCESSED},1809 {"flag_value": EngineType.PRO, "type": UNPROCESSED},1810 ["--opt1"],1811 EngineType.OSS,1812 ),1813 (1814 {"flag_value": EngineType.OSS, "type": UNPROCESSED},1815 {"flag_value": EngineType.PRO, "type": UNPROCESSED},1816 ["--opt2"],1817 EngineType.PRO,1818 ),1819 ###1820 ### Reproduces https://github.com/pallets/click/issues/2012#issue-9464710491821 ###1822 # Default type fallback to string.1823 ({"flag_value": Class1, "default": True}, {"flag_value": Class2}, [], "True"),1824 (1825 {"flag_value": Class1, "default": True},1826 {"flag_value": Class2},1827 ["--opt1"],1828 "<class 'test_options.Class1'>",1829 ),1830 (1831 {"flag_value": Class1, "default": True},1832 {"flag_value": Class2},1833 ["--opt2"],1834 "<class 'test_options.Class2'>",1835 ),1836 # Even the default is processed as a string.1837 ({"flag_value": Class1, "default": "True"}, {"flag_value": Class2}, [], "True"),1838 ({"flag_value": Class1, "default": None}, {"flag_value": Class2}, [], None),1839 # To get the classes as-is, we need to specify the type as UNPROCESSED.1840 (1841 {"flag_value": Class1, "type": UNPROCESSED, "default": True},1842 {"flag_value": Class2, "type": UNPROCESSED},1843 [],1844 True,1845 ),1846 (1847 {"flag_value": Class1, "type": UNPROCESSED, "default": True},1848 {"flag_value": Class2, "type": UNPROCESSED},1849 ["--opt1"],1850 Class1,1851 ),1852 (1853 {"flag_value": Class1, "type": UNPROCESSED, "default": True},1854 {"flag_value": Class2, "type": UNPROCESSED},1855 ["--opt2"],1856 Class2,1857 ),1858 # Setting the default to a class, an instance of the class is returned instead1859 # of the class itself, because the default is allowed to be callable (and1860 # consummd). And this what happens the type is.1861 (1862 {"flag_value": Class1, "default": Class1},1863 {"flag_value": Class2},1864 [],1865 re.compile(r"'<test_options.Class1 object at 0x[0-9A-Fa-f]+>'"),1866 ),1867 (1868 {"flag_value": Class1, "default": Class2},1869 {"flag_value": Class2},1870 [],1871 re.compile(r"'<test_options.Class2 object at 0x[0-9A-Fa-f]+>'"),1872 ),1873 (1874 {"flag_value": Class1, "type": UNPROCESSED, "default": Class1},1875 {"flag_value": Class2, "type": UNPROCESSED},1876 [],1877 re.compile(r"<test_options.Class1 object at 0x[0-9A-Fa-f]+>"),1878 ),1879 (1880 {"flag_value": Class1, "type": UNPROCESSED, "default": Class2},1881 {"flag_value": Class2, "type": UNPROCESSED},1882 [],1883 re.compile(r"<test_options.Class2 object at 0x[0-9A-Fa-f]+>"),1884 ),1885 ###1886 ### Reproduces https://github.com/pallets/click/issues/2012#issuecomment-8924370601887 ###1888 (1889 {"flag_value": 1, "default": True},1890 {"flag_value": "1"},1891 [],1892 1,1893 ),1894 (1895 {"flag_value": 1, "type": int, "default": True},1896 {"flag_value": "1", "type": int},1897 [],1898 1,1899 ),1900 ],1901)1902def test_custom_type_flag_value_dual_options(1903 runner, opt1_params, opt2_params, args, expected1904):1905 @click.command()1906 @click.option("--opt1", "dual_option", **opt1_params)1907 @click.option("--opt2", "dual_option", **opt2_params)1908 def cli(dual_option):1909 click.echo(repr(dual_option), nl=False)19101911 result = runner.invoke(cli, args)1912 if isinstance(expected, re.Pattern):1913 assert re.match(expected, result.output)1914 else:1915 assert result.output == repr(expected)191619171918def test_custom_type_frozenset_flag_value(runner):1919 """A reproduction of https://github.com/pallets/click/issues/2610"""19201921 @click.command()1922 @click.option(1923 "--without-scm-ignore-files",1924 "scm_ignore_files",1925 is_flag=True,1926 type=frozenset,1927 flag_value=frozenset(),1928 default=frozenset(["git"]),1929 )1930 def rcli(scm_ignore_files):1931 click.echo(repr(scm_ignore_files), nl=False)19321933 result = runner.invoke(rcli)1934 assert result.stdout == "frozenset({'git'})"1935 assert result.exit_code == 019361937 result = runner.invoke(rcli, ["--without-scm-ignore-files"])1938 assert result.stdout == "frozenset()"1939 assert result.exit_code == 0
modified:tests/test_termui.py+195 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.output490491492BOOLEAN_FLAG_PROMPT_CASES = [493 ###494 ### Test cases with prompt=True explicitly enabled for the flag.495 ###496 # Prompt is allowed and the flag has no default, so it prompts.497 ({"prompt": True}, [], "[y/N]", "y", True),498 ({"prompt": True}, [], "[y/N]", "n", False),499 # Empty input default to False.500 ({"prompt": True}, [], "[y/N]", "", False),501 # Changing the default to True, makes the prompt change to [Y/n].502 ({"prompt": True, "default": True}, [], "[Y/n]", "", True),503 ({"prompt": True, "default": True}, [], "[Y/n]", "y", True),504 ({"prompt": True, "default": True}, [], "[Y/n]", "n", False),505 # False is the default's default, so it prompts with [y/N].506 ({"prompt": True, "default": False}, [], "[y/N]", "", False),507 ({"prompt": True, "default": False}, [], "[y/N]", "y", True),508 ({"prompt": True, "default": False}, [], "[y/N]", "n", False),509 # Defaulting to None, prompts with [y/n], which makes the user explicitly choose510 # between True or False.511 ({"prompt": True, "default": None}, [], "[y/n]", "y", True),512 ({"prompt": True, "default": None}, [], "[y/n]", "n", False),513 # Random string default is treated as a truthy value, so it prompts with [Y/n].514 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "", True),515 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "y", True),516 ({"prompt": True, "default": "foo"}, [], "[Y/n]", "n", False),517 ###518 ### Test cases with required=True explicitly enabled for the flag.519 ###520 # A required flag just raises an error unless a default is set.521 ({"required": True}, [], None, None, MissingParameter),522 ({"required": True, "default": True}, [], None, None, True),523 ({"required": True, "default": False}, [], None, None, False),524 ({"required": True, "default": None}, [], None, None, None),525 ({"required": True, "default": "on"}, [], None, None, True),526 ({"required": True, "default": "off"}, [], None, None, False),527 ({"required": True, "default": "foo"}, [], None, None, BadParameter),528 ###529 ### Explicitly passing the flag to the CLI bypass any prompt, whatever the530 ### configuration of the flag.531 ###532 # Flag allowing a prompt.533 ({"prompt": True}, ["--flag"], None, None, True),534 ({"prompt": True}, ["--no-flag"], None, None, False),535 ({"prompt": True, "default": None}, ["--flag"], None, None, True),536 ({"prompt": True, "default": None}, ["--no-flag"], None, None, False),537 ({"prompt": True, "default": True}, ["--flag"], None, None, True),538 ({"prompt": True, "default": True}, ["--no-flag"], None, None, False),539 ({"prompt": True, "default": False}, ["--flag"], None, None, True),540 ({"prompt": True, "default": False}, ["--no-flag"], None, None, False),541 ({"prompt": True, "default": "foo"}, ["--flag"], None, None, True),542 ({"prompt": True, "default": "foo"}, ["--no-flag"], None, None, False),543 # Required flag.544 ({"required": True}, ["--flag"], None, None, True),545 ({"required": True}, ["--no-flag"], None, None, False),546 ({"required": True, "default": None}, ["--flag"], None, None, True),547 ({"required": True, "default": None}, ["--no-flag"], None, None, False),548 ({"required": True, "default": True}, ["--flag"], None, None, True),549 ({"required": True, "default": True}, ["--no-flag"], None, None, False),550 ({"required": True, "default": False}, ["--flag"], None, None, True),551 ({"required": True, "default": False}, ["--no-flag"], None, None, False),552 ({"required": True, "default": "foo"}, ["--flag"], None, None, True),553 ({"required": True, "default": "foo"}, ["--no-flag"], None, None, False),554]555556FLAG_VALUE_PROMPT_CASES = [557 ###558 ### Test cases with prompt=True explicitly enabled for the flag.559 ###560 # Prompt is allowed and the flag has no default, so it prompts.561 # But the flag_value is not set, so it defaults to a string.562 # XXX ({"prompt": True}, [], "", "", ""),563 ({"prompt": True}, [], "", "y", "y"),564 ({"prompt": True}, [], "", "n", "n"),565 ({"prompt": True}, [], "", "foo", "foo"),566 # This time we provide a boolean flag_value, which makes the flag behave like a567 # boolean flag, and use the appropriate variation of [y/n].568 ({"prompt": True, "flag_value": True}, [], "[y/N]", "", False),569 ({"prompt": True, "flag_value": True}, [], "[y/N]", "y", True),570 ({"prompt": True, "flag_value": True}, [], "[y/N]", "n", False),571 ({"prompt": True, "flag_value": False}, [], "[y/N]", "", False),572 ({"prompt": True, "flag_value": False}, [], "[y/N]", "y", True),573 ({"prompt": True, "flag_value": False}, [], "[y/N]", "n", False),574 # Other flag values changes the auto-detection of the flag type.575 # XXX ({"prompt": True, "flag_value": None}, [], "", "", ""),576 ({"prompt": True, "flag_value": None}, [], "", "y", "y"),577 ({"prompt": True, "flag_value": None}, [], "", "n", "n"),578 # XXX ({"prompt": True, "flag_value": "foo"}, [], "", "", ""),579 ({"prompt": True, "flag_value": "foo"}, [], "", "y", "y"),580 ({"prompt": True, "flag_value": "foo"}, [], "", "n", "n"),581 ###582 ### Test cases with a flag_value and a default.583 ###584 # default=True585 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "", True),586 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "y", True),587 ({"prompt": True, "default": True, "flag_value": True}, [], "[Y/n]", "n", False),588 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "", True),589 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "y", True),590 ({"prompt": True, "default": True, "flag_value": False}, [], "[Y/n]", "n", False),591 # default=False592 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "", False),593 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "y", True),594 ({"prompt": True, "default": False, "flag_value": True}, [], "[y/N]", "n", False),595 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "", False),596 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "y", True),597 ({"prompt": True, "default": False, "flag_value": False}, [], "[y/N]", "n", False),598 # default=None599 # XXX600 # (601 # {"prompt": True, "default": None, "flag_value": True},602 # [],603 # "[y/n]",604 # "",605 # False,606 # ),607 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "y", True),608 ({"prompt": True, "default": None, "flag_value": True}, [], "[y/n]", "n", False),609 # XXX610 # (611 # {"prompt": True, "default": None, "flag_value": False},612 # [],613 # "[y/n]",614 # "",615 # False,616 # ),617 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "y", True),618 ({"prompt": True, "default": None, "flag_value": False}, [], "[y/n]", "n", False),619 # If the flag_value is None, the flag behave like a string flag, whatever the620 # default is.621 ({"prompt": True, "default": True, "flag_value": None}, [], "[True]", "", "True"),622 ({"prompt": True, "default": True, "flag_value": None}, [], "[True]", "y", "y"),623 ({"prompt": True, "default": True, "flag_value": None}, [], "[True]", "n", "n"),624 (625 {"prompt": True, "default": False, "flag_value": None},626 [],627 "[False]",628 "",629 "False",630 ),631 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "y", "y"),632 ({"prompt": True, "default": False, "flag_value": None}, [], "[False]", "n", "n"),633 # XXX ({"prompt": True, "default": None, "flag_value": None}, [], "", "", "False"),634 ({"prompt": True, "default": None, "flag_value": None}, [], "", "y", "y"),635 ({"prompt": True, "default": None, "flag_value": None}, [], "", "n", "n"),636]637638639@pytest.mark.parametrize(640 ("opt_decls", "opt_params", "args", "prompt", "input", "expected"),641 # Boolean flag prompt cases.642 [("--flag/--no-flag", *case_params) for case_params in BOOLEAN_FLAG_PROMPT_CASES]643 # Non-boolean flag prompt cases.644 + [("--flag", *case_params) for case_params in FLAG_VALUE_PROMPT_CASES],645)646def test_flag_value_prompt(647 runner, opt_decls, opt_params, args, prompt, input, expected648):649 """Covers concerns raised in issue https://github.com/pallets/click/issues/1992."""650651 @click.command()652 @click.option(opt_decls, **opt_params)653 def cli(flag):654 click.echo(repr(flag))655656 invoke_options = {"standalone_mode": False}657 if input is not None:658 assert isinstance(input, str)659 invoke_options["input"] = f"{input}\n"660661 result = runner.invoke(cli, args, **invoke_options)662663 if expected in (MissingParameter, BadParameter):664 assert isinstance(result.exception, expected)665 assert not result.output666 assert result.exit_code == 1667668 else:669 expected_output = ""670 if prompt is not None:671 assert isinstance(prompt, str)672 expected_output += "Flag"673 if prompt:674 expected_output += f" {prompt}"675 expected_output += ": "676 assert isinstance(input, str)677 expected_output += f"{input}\n"678 expected_output += f"{expected!r}\n"679680 assert result.output == expected_output681 assert not result.stderr682 assert result.exit_code == 0
modified:tests/test_utils.py+52 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 True33 assert value is not True3435 # Try all native Python values that can be falsy or truthy.36 # See: https://docs.python.org/3/library/stdtypes.html#truth-value-testing37 real_values = (38 None,39 True,40 False,41 0,42 1,43 0.0,44 1.0,45 0j,46 1j,47 Decimal(0),48 Decimal(1),49 Fraction(0, 1),50 Fraction(1, 1),51 "",52 "a",53 "UNSET",54 "Sentinel.UNSET",55 [1],56 (1),57 {1: "a"},58 set(),59 set([1]),60 frozenset(),61 frozenset([1]),62 range(0),63 range(1),64 )6566 for real_value in real_values:67 assert value != real_value68 assert value is not real_value6970 assert value not in real_values717273def test_echo(runner):74 with runner.isolation() as outstreams:75 click.echo("\N{SNOWMAN}")76 click.echo(b"\x44\x44")
647 unmodified lines
modified:CHANGES.rst+15 added-3 removed
3 unmodified lines
4-------------56Unreleased78- show correct auto complete value for nargs option in combination with flag option :issue:`2813`8- Rework flag value passing by disentangling use of ``default``. Formerly defaults9 for ``flag_value`` were set by passing ``default=True``, now set by passing10 ``default=<desired_value>``. This change breaks all default settings for flag value11 type flags. In all other places in code, ``default`` takes on the default value.12 Fixing this inconsistency allows the fixing of the linked issues and supports a13 more consistent API. :issue:`1992` :issue:`2012`` :issue:`2514` :issue:`2610`14 :issue:`3024` :pr:`3030`15- Custom ``callback`` function are now allowed to receive the ``UNSET`` sentinel16 value. :pr:`3030`17- Allow ``default`` to be set on ``Argument`` for ``nargs = -1``. :issue:`2164`18 :pr:`3030`19- Show correct auto complete value for ``nargs`` option in combination with flag20 option :issue:`2813`2122Version 8.2.223-------------2425Released 2025-07-312615- Fix reconciliation of `default`, `flag_value` and `type` parameters for27- Fix reconciliation of ``default``, ``flag_value`` and ``type`` parameters for28 flag options, as well as parsing and normalization of environment variables.29 :issue:`2952` :pr:`2956`30- Fix typing issue in ``BadParameter`` and ``MissingParameter`` exceptions for the31 parameter ``param_hint`` that did not allow for a sequence of string where the20 underlying functino ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`32 underlying function ``_join_param_hints`` allows for it. :issue:`2777` :pr:`2990`33- Use the value of ``Enum`` choices to render their default value in help34 screen. Refs :issue:`2911` :pr:`3004`35- Fix completion for the Z shell (``zsh``) for completion items containing36 colons. :issue:`2703` :pr:`2846`
1250 unmodified lines